1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.8.  By combining all the individual C code files into this
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45 
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72 
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80 
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 **
95 ** This file defines various limits of what SQLite can process.
96 */
97 
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108 
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129 
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140 
141 /*
142 ** The maximum depth of an expression tree. This is limited to
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144 ** want to place more severe limits on the complexity of an
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154 
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166 
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174 
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181 
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192 
193 /*
194 ** The default number of frames to accumulate in the log file before
195 ** checkpointing the database in WAL mode.
196 */
197 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199 #endif
200 
201 /*
202 ** The maximum number of attached databases.  This must be between 0
203 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204 ** is used internally to track attached databases.
205 */
206 #ifndef SQLITE_MAX_ATTACHED
207 # define SQLITE_MAX_ATTACHED 10
208 #endif
209 
210 
211 /*
212 ** The maximum value of a ?nnn wildcard that the parser will accept.
213 */
214 #ifndef SQLITE_MAX_VARIABLE_NUMBER
215 # define SQLITE_MAX_VARIABLE_NUMBER 999
216 #endif
217 
218 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
219 ** imposed by the use of 16-bit offsets within each page.
220 **
221 ** Earlier versions of SQLite allowed the user to change this value at
222 ** compile time. This is no longer permitted, on the grounds that it creates
223 ** a library that is technically incompatible with an SQLite library
224 ** compiled with a different limit. If a process operating on a database
225 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
226 ** compiled with the default page-size limit will not be able to rollback
227 ** the aborted transaction. This could lead to database corruption.
228 */
229 #ifdef SQLITE_MAX_PAGE_SIZE
230 # undef SQLITE_MAX_PAGE_SIZE
231 #endif
232 #define SQLITE_MAX_PAGE_SIZE 65536
233 
234 
235 /*
236 ** The default size of a database page.
237 */
238 #ifndef SQLITE_DEFAULT_PAGE_SIZE
239 # define SQLITE_DEFAULT_PAGE_SIZE 1024
240 #endif
241 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242 # undef SQLITE_DEFAULT_PAGE_SIZE
243 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244 #endif
245 
246 /*
247 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
248 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249 ** device characteristics (sector-size and atomic write() support),
250 ** SQLite may choose a larger value. This constant is the maximum value
251 ** SQLite will choose on its own.
252 */
253 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255 #endif
256 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259 #endif
260 
261 
262 /*
263 ** Maximum number of pages in one database file.
264 **
265 ** This is really just the default value for the max_page_count pragma.
266 ** This value can be lowered (or raised) at run-time using that the
267 ** max_page_count macro.
268 */
269 #ifndef SQLITE_MAX_PAGE_COUNT
270 # define SQLITE_MAX_PAGE_COUNT 1073741823
271 #endif
272 
273 /*
274 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275 ** operator.
276 */
277 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279 #endif
280 
281 /*
282 ** Maximum depth of recursion for triggers.
283 **
284 ** A value of 1 means that a trigger program will not be able to itself
285 ** fire any triggers. A value of 0 means that no trigger programs at all
286 ** may be executed.
287 */
288 #ifndef SQLITE_MAX_TRIGGER_DEPTH
289 # define SQLITE_MAX_TRIGGER_DEPTH 1000
290 #endif
291 
292 /************** End of sqliteLimit.h *****************************************/
293 /************** Continuing where we left off in sqliteInt.h ******************/
294 
295 /* Disable nuisance warnings on Borland compilers */
296 #if defined(__BORLANDC__)
297 #pragma warn -rch /* unreachable code */
298 #pragma warn -ccc /* Condition is always true or false */
299 #pragma warn -aus /* Assigned value is never used */
300 #pragma warn -csu /* Comparing signed and unsigned */
301 #pragma warn -spa /* Suspicious pointer arithmetic */
302 #endif
303 
304 /* Needed for various definitions... */
305 #ifndef _GNU_SOURCE
306 # define _GNU_SOURCE
307 #endif
308 
309 /*
310 ** Include standard header files as necessary
311 */
312 #ifdef HAVE_STDINT_H
313 #include <stdint.h>
314 #endif
315 #ifdef HAVE_INTTYPES_H
316 #include <inttypes.h>
317 #endif
318 
319 /*
320 ** The number of samples of an index that SQLite takes in order to
321 ** construct a histogram of the table content when running ANALYZE
322 ** and with SQLITE_ENABLE_STAT2
323 */
324 #define SQLITE_INDEX_SAMPLES 10
325 
326 /*
327 ** The following macros are used to cast pointers to integers and
328 ** integers to pointers.  The way you do this varies from one compiler
329 ** to the next, so we have developed the following set of #if statements
330 ** to generate appropriate macros for a wide range of compilers.
331 **
332 ** The correct "ANSI" way to do this is to use the intptr_t type.
333 ** Unfortunately, that typedef is not available on all compilers, or
334 ** if it is available, it requires an #include of specific headers
335 ** that vary from one machine to the next.
336 **
337 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
338 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
339 ** So we have to define the macros in different ways depending on the
340 ** compiler.
341 */
342 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
345 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
346 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
347 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
348 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
349 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
350 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
351 #else                          /* Generates a warning - but it always works */
352 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
353 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
354 #endif
355 
356 /*
357 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
358 ** 0 means mutexes are permanently disable and the library is never
359 ** threadsafe.  1 means the library is serialized which is the highest
360 ** level of threadsafety.  2 means the libary is multithreaded - multiple
361 ** threads can use SQLite as long as no two threads try to use the same
362 ** database connection at the same time.
363 **
364 ** Older versions of SQLite used an optional THREADSAFE macro.
365 ** We support that for legacy.
366 */
367 #if !defined(SQLITE_THREADSAFE)
368 #if defined(THREADSAFE)
369 # define SQLITE_THREADSAFE THREADSAFE
370 #else
371 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
372 #endif
373 #endif
374 
375 /*
376 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
377 ** It determines whether or not the features related to
378 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
379 ** be overridden at runtime using the sqlite3_config() API.
380 */
381 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
382 # define SQLITE_DEFAULT_MEMSTATUS 1
383 #endif
384 
385 /*
386 ** Exactly one of the following macros must be defined in order to
387 ** specify which memory allocation subsystem to use.
388 **
389 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
390 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
391 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
392 **
393 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
394 ** assert() macro is enabled, each call into the Win32 native heap subsystem
395 ** will cause HeapValidate to be called.  If heap validation should fail, an
396 ** assertion will be triggered.
397 **
398 ** (Historical note:  There used to be several other options, but we've
399 ** pared it down to just these two.)
400 **
401 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
402 ** the default.
403 */
404 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
405 # error "At most one of the following compile-time configuration options\
406  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
407 #endif
408 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
409 # define SQLITE_SYSTEM_MALLOC 1
410 #endif
411 
412 /*
413 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
414 ** sizes of memory allocations below this value where possible.
415 */
416 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
417 # define SQLITE_MALLOC_SOFT_LIMIT 1024
418 #endif
419 
420 /*
421 ** We need to define _XOPEN_SOURCE as follows in order to enable
422 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
423 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
424 ** so it is omitted there.  See ticket #2673.
425 **
426 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
427 ** implemented on some systems.  So we avoid defining it at all
428 ** if it is already defined or if it is unneeded because we are
429 ** not doing a threadsafe build.  Ticket #2681.
430 **
431 ** See also ticket #2741.
432 */
433 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
434 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
435 #endif
436 
437 /*
438 ** The TCL headers are only needed when compiling the TCL bindings.
439 */
440 #if defined(SQLITE_TCL) || defined(TCLSH)
441 # include <tcl.h>
442 #endif
443 
444 /*
445 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
446 ** Setting NDEBUG makes the code smaller and run faster.  So the following
447 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
448 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
449 ** feature.
450 */
451 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
452 # define NDEBUG 1
453 #endif
454 
455 /*
456 ** The testcase() macro is used to aid in coverage testing.  When
457 ** doing coverage testing, the condition inside the argument to
458 ** testcase() must be evaluated both true and false in order to
459 ** get full branch coverage.  The testcase() macro is inserted
460 ** to help ensure adequate test coverage in places where simple
461 ** condition/decision coverage is inadequate.  For example, testcase()
462 ** can be used to make sure boundary values are tested.  For
463 ** bitmask tests, testcase() can be used to make sure each bit
464 ** is significant and used at least once.  On switch statements
465 ** where multiple cases go to the same block of code, testcase()
466 ** can insure that all cases are evaluated.
467 **
468 */
469 #ifdef SQLITE_COVERAGE_TEST
470 SQLITE_PRIVATE   void sqlite3Coverage(int);
471 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
472 #else
473 # define testcase(X)
474 #endif
475 
476 /*
477 ** The TESTONLY macro is used to enclose variable declarations or
478 ** other bits of code that are needed to support the arguments
479 ** within testcase() and assert() macros.
480 */
481 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
482 # define TESTONLY(X)  X
483 #else
484 # define TESTONLY(X)
485 #endif
486 
487 /*
488 ** Sometimes we need a small amount of code such as a variable initialization
489 ** to setup for a later assert() statement.  We do not want this code to
490 ** appear when assert() is disabled.  The following macro is therefore
491 ** used to contain that setup code.  The "VVA" acronym stands for
492 ** "Verification, Validation, and Accreditation".  In other words, the
493 ** code within VVA_ONLY() will only run during verification processes.
494 */
495 #ifndef NDEBUG
496 # define VVA_ONLY(X)  X
497 #else
498 # define VVA_ONLY(X)
499 #endif
500 
501 /*
502 ** The ALWAYS and NEVER macros surround boolean expressions which
503 ** are intended to always be true or false, respectively.  Such
504 ** expressions could be omitted from the code completely.  But they
505 ** are included in a few cases in order to enhance the resilience
506 ** of SQLite to unexpected behavior - to make the code "self-healing"
507 ** or "ductile" rather than being "brittle" and crashing at the first
508 ** hint of unplanned behavior.
509 **
510 ** In other words, ALWAYS and NEVER are added for defensive code.
511 **
512 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
513 ** be true and false so that the unreachable code then specify will
514 ** not be counted as untested code.
515 */
516 #if defined(SQLITE_COVERAGE_TEST)
517 # define ALWAYS(X)      (1)
518 # define NEVER(X)       (0)
519 #elif !defined(NDEBUG)
520 # define ALWAYS(X)      ((X)?1:(assert(0),0))
521 # define NEVER(X)       ((X)?(assert(0),1):0)
522 #else
523 # define ALWAYS(X)      (X)
524 # define NEVER(X)       (X)
525 #endif
526 
527 /*
528 ** Return true (non-zero) if the input is a integer that is too large
529 ** to fit in 32-bits.  This macro is used inside of various testcase()
530 ** macros to verify that we have tested SQLite for large-file support.
531 */
532 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
533 
534 /*
535 ** The macro unlikely() is a hint that surrounds a boolean
536 ** expression that is usually false.  Macro likely() surrounds
537 ** a boolean expression that is usually true.  GCC is able to
538 ** use these hints to generate better code, sometimes.
539 */
540 #if defined(__GNUC__) && 0
541 # define likely(X)    __builtin_expect((X),1)
542 # define unlikely(X)  __builtin_expect((X),0)
543 #else
544 # define likely(X)    !!(X)
545 # define unlikely(X)  !!(X)
546 #endif
547 
548 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
549 /************** Begin file sqlite3.h *****************************************/
550 /*
551 ** 2001 September 15
552 **
553 ** The author disclaims copyright to this source code.  In place of
554 ** a legal notice, here is a blessing:
555 **
556 **    May you do good and not evil.
557 **    May you find forgiveness for yourself and forgive others.
558 **    May you share freely, never taking more than you give.
559 **
560 *************************************************************************
561 ** This header file defines the interface that the SQLite library
562 ** presents to client programs.  If a C-function, structure, datatype,
563 ** or constant definition does not appear in this file, then it is
564 ** not a published API of SQLite, is subject to change without
565 ** notice, and should not be referenced by programs that use SQLite.
566 **
567 ** Some of the definitions that are in this file are marked as
568 ** "experimental".  Experimental interfaces are normally new
569 ** features recently added to SQLite.  We do not anticipate changes
570 ** to experimental interfaces but reserve the right to make minor changes
571 ** if experience from use "in the wild" suggest such changes are prudent.
572 **
573 ** The official C-language API documentation for SQLite is derived
574 ** from comments in this file.  This file is the authoritative source
575 ** on how SQLite interfaces are suppose to operate.
576 **
577 ** The name of this file under configuration management is "sqlite.h.in".
578 ** The makefile makes some minor changes to this file (such as inserting
579 ** the version number) and changes its name to "sqlite3.h" as
580 ** part of the build process.
581 */
582 #ifndef _SQLITE3_H_
583 #define _SQLITE3_H_
584 #include <stdarg.h>     /* Needed for the definition of va_list */
585 #include <stdint.h>
586 
587 /*
588 ** Make sure we can call this stuff from C++.
589 */
590 #if 0
591 extern "C" {
592 #endif
593 
594 
595 /*
596 ** Add the ability to override 'extern'
597 */
598 #ifndef SQLITE_EXTERN
599 # define SQLITE_EXTERN extern
600 #endif
601 
602 #ifndef SQLITE_API
603 # define SQLITE_API
604 #endif
605 
606 
607 /*
608 ** These no-op macros are used in front of interfaces to mark those
609 ** interfaces as either deprecated or experimental.  New applications
610 ** should not use deprecated interfaces - they are support for backwards
611 ** compatibility only.  Application writers should be aware that
612 ** experimental interfaces are subject to change in point releases.
613 **
614 ** These macros used to resolve to various kinds of compiler magic that
615 ** would generate warning messages when they were used.  But that
616 ** compiler magic ended up generating such a flurry of bug reports
617 ** that we have taken it all out and gone back to using simple
618 ** noop macros.
619 */
620 #define SQLITE_DEPRECATED
621 #define SQLITE_EXPERIMENTAL
622 
623 /*
624 ** Ensure these symbols were not defined by some previous header file.
625 */
626 #ifdef SQLITE_VERSION
627 # undef SQLITE_VERSION
628 #endif
629 #ifdef SQLITE_VERSION_NUMBER
630 # undef SQLITE_VERSION_NUMBER
631 #endif
632 
633 /*
634 ** CAPI3REF: Compile-Time Library Version Numbers
635 **
636 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
637 ** evaluates to a string literal that is the SQLite version in the
638 ** format "X.Y.Z" where X is the major version number (always 3 for
639 ** SQLite3) and Y is the minor version number and Z is the release number.)^
640 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
641 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
642 ** numbers used in [SQLITE_VERSION].)^
643 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
644 ** be larger than the release from which it is derived.  Either Y will
645 ** be held constant and Z will be incremented or else Y will be incremented
646 ** and Z will be reset to zero.
647 **
648 ** Since version 3.6.18, SQLite source code has been stored in the
649 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
650 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
651 ** a string which identifies a particular check-in of SQLite
652 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
653 ** string contains the date and time of the check-in (UTC) and an SHA1
654 ** hash of the entire source tree.
655 **
656 ** See also: [sqlite3_libversion()],
657 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
658 ** [sqlite_version()] and [sqlite_source_id()].
659 */
660 #define SQLITE_VERSION        "3.7.8"
661 #define SQLITE_VERSION_NUMBER 3007008
662 #define SQLITE_SOURCE_ID      "2011-09-19 14:49:19 3e0da808d2f5b4d12046e05980ca04578f581177"
663 
664 /*
665 ** CAPI3REF: Run-Time Library Version Numbers
666 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
667 **
668 ** These interfaces provide the same information as the [SQLITE_VERSION],
669 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
670 ** but are associated with the library instead of the header file.  ^(Cautious
671 ** programmers might include assert() statements in their application to
672 ** verify that values returned by these interfaces match the macros in
673 ** the header, and thus insure that the application is
674 ** compiled with matching library and header files.
675 **
676 ** <blockquote><pre>
677 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
678 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
679 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
680 ** </pre></blockquote>)^
681 **
682 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
683 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
684 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
685 ** function is provided for use in DLLs since DLL users usually do not have
686 ** direct access to string constants within the DLL.  ^The
687 ** sqlite3_libversion_number() function returns an integer equal to
688 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
689 ** a pointer to a string constant whose value is the same as the
690 ** [SQLITE_SOURCE_ID] C preprocessor macro.
691 **
692 ** See also: [sqlite_version()] and [sqlite_source_id()].
693 */
694 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
695 SQLITE_API const char *sqlite3_libversion(void);
696 SQLITE_API const char *sqlite3_sourceid(void);
697 SQLITE_API int sqlite3_libversion_number(void);
698 
699 /*
700 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
701 **
702 ** ^The sqlite3_compileoption_used() function returns 0 or 1
703 ** indicating whether the specified option was defined at
704 ** compile time.  ^The SQLITE_ prefix may be omitted from the
705 ** option name passed to sqlite3_compileoption_used().
706 **
707 ** ^The sqlite3_compileoption_get() function allows iterating
708 ** over the list of options that were defined at compile time by
709 ** returning the N-th compile time option string.  ^If N is out of range,
710 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
711 ** prefix is omitted from any strings returned by
712 ** sqlite3_compileoption_get().
713 **
714 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
715 ** and sqlite3_compileoption_get() may be omitted by specifying the
716 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
717 **
718 ** See also: SQL functions [sqlite_compileoption_used()] and
719 ** [sqlite_compileoption_get()] and the [compile_options pragma].
720 */
721 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
722 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
723 SQLITE_API const char *sqlite3_compileoption_get(int N);
724 #endif
725 
726 /*
727 ** CAPI3REF: Test To See If The Library Is Threadsafe
728 **
729 ** ^The sqlite3_threadsafe() function returns zero if and only if
730 ** SQLite was compiled mutexing code omitted due to the
731 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
732 **
733 ** SQLite can be compiled with or without mutexes.  When
734 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
735 ** are enabled and SQLite is threadsafe.  When the
736 ** [SQLITE_THREADSAFE] macro is 0,
737 ** the mutexes are omitted.  Without the mutexes, it is not safe
738 ** to use SQLite concurrently from more than one thread.
739 **
740 ** Enabling mutexes incurs a measurable performance penalty.
741 ** So if speed is of utmost importance, it makes sense to disable
742 ** the mutexes.  But for maximum safety, mutexes should be enabled.
743 ** ^The default behavior is for mutexes to be enabled.
744 **
745 ** This interface can be used by an application to make sure that the
746 ** version of SQLite that it is linking against was compiled with
747 ** the desired setting of the [SQLITE_THREADSAFE] macro.
748 **
749 ** This interface only reports on the compile-time mutex setting
750 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
751 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
752 ** can be fully or partially disabled using a call to [sqlite3_config()]
753 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
754 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
755 ** sqlite3_threadsafe() function shows only the compile-time setting of
756 ** thread safety, not any run-time changes to that setting made by
757 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
758 ** is unchanged by calls to sqlite3_config().)^
759 **
760 ** See the [threading mode] documentation for additional information.
761 */
762 SQLITE_API int sqlite3_threadsafe(void);
763 
764 /*
765 ** CAPI3REF: Database Connection Handle
766 ** KEYWORDS: {database connection} {database connections}
767 **
768 ** Each open SQLite database is represented by a pointer to an instance of
769 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
770 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
771 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
772 ** is its destructor.  There are many other interfaces (such as
773 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
774 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
775 ** sqlite3 object.
776 */
777 typedef struct sqlite3 sqlite3;
778 
779 /*
780 ** CAPI3REF: 64-Bit Integer Types
781 ** KEYWORDS: sqlite_int64 sqlite_uint64
782 **
783 ** Because there is no cross-platform way to specify 64-bit integer types
784 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
785 **
786 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
787 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
788 ** compatibility only.
789 **
790 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
791 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
792 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
793 ** between 0 and +18446744073709551615 inclusive.
794 */
795 #ifdef SQLITE_INT64_TYPE
796   typedef SQLITE_INT64_TYPE sqlite_int64;
797   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
798 #elif defined(_MSC_VER) || defined(__BORLANDC__)
799   typedef __int64 sqlite_int64;
800   typedef unsigned __int64 sqlite_uint64;
801 #else
802   typedef long long int sqlite_int64;
803   typedef unsigned long long int sqlite_uint64;
804 #endif
805 typedef sqlite_int64 sqlite3_int64;
806 typedef sqlite_uint64 sqlite3_uint64;
807 
808 /*
809 ** If compiling for a processor that lacks floating point support,
810 ** substitute integer for floating-point.
811 */
812 #ifdef SQLITE_OMIT_FLOATING_POINT
813 # define double sqlite3_int64
814 #endif
815 
816 /*
817 ** CAPI3REF: Closing A Database Connection
818 **
819 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
820 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
821 ** successfully destroyed and all associated resources are deallocated.
822 **
823 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
824 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
825 ** the [sqlite3] object prior to attempting to close the object.  ^If
826 ** sqlite3_close() is called on a [database connection] that still has
827 ** outstanding [prepared statements] or [BLOB handles], then it returns
828 ** SQLITE_BUSY.
829 **
830 ** ^If [sqlite3_close()] is invoked while a transaction is open,
831 ** the transaction is automatically rolled back.
832 **
833 ** The C parameter to [sqlite3_close(C)] must be either a NULL
834 ** pointer or an [sqlite3] object pointer obtained
835 ** from [sqlite3_open()], [sqlite3_open16()], or
836 ** [sqlite3_open_v2()], and not previously closed.
837 ** ^Calling sqlite3_close() with a NULL pointer argument is a
838 ** harmless no-op.
839 */
840 SQLITE_API int sqlite3_close(sqlite3 *);
841 
842 /*
843 ** The type for a callback function.
844 ** This is legacy and deprecated.  It is included for historical
845 ** compatibility and is not documented.
846 */
847 typedef int (*sqlite3_callback)(void*,int,char**, char**);
848 
849 /*
850 ** CAPI3REF: One-Step Query Execution Interface
851 **
852 ** The sqlite3_exec() interface is a convenience wrapper around
853 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
854 ** that allows an application to run multiple statements of SQL
855 ** without having to use a lot of C code.
856 **
857 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
858 ** semicolon-separate SQL statements passed into its 2nd argument,
859 ** in the context of the [database connection] passed in as its 1st
860 ** argument.  ^If the callback function of the 3rd argument to
861 ** sqlite3_exec() is not NULL, then it is invoked for each result row
862 ** coming out of the evaluated SQL statements.  ^The 4th argument to
863 ** sqlite3_exec() is relayed through to the 1st argument of each
864 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
865 ** is NULL, then no callback is ever invoked and result rows are
866 ** ignored.
867 **
868 ** ^If an error occurs while evaluating the SQL statements passed into
869 ** sqlite3_exec(), then execution of the current statement stops and
870 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
871 ** is not NULL then any error message is written into memory obtained
872 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
873 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
874 ** on error message strings returned through the 5th parameter of
875 ** of sqlite3_exec() after the error message string is no longer needed.
876 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
877 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
878 ** NULL before returning.
879 **
880 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
881 ** routine returns SQLITE_ABORT without invoking the callback again and
882 ** without running any subsequent SQL statements.
883 **
884 ** ^The 2nd argument to the sqlite3_exec() callback function is the
885 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
886 ** callback is an array of pointers to strings obtained as if from
887 ** [sqlite3_column_text()], one for each column.  ^If an element of a
888 ** result row is NULL then the corresponding string pointer for the
889 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
890 ** sqlite3_exec() callback is an array of pointers to strings where each
891 ** entry represents the name of corresponding result column as obtained
892 ** from [sqlite3_column_name()].
893 **
894 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
895 ** to an empty string, or a pointer that contains only whitespace and/or
896 ** SQL comments, then no SQL statements are evaluated and the database
897 ** is not changed.
898 **
899 ** Restrictions:
900 **
901 ** <ul>
902 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
903 **      is a valid and open [database connection].
904 ** <li> The application must not close [database connection] specified by
905 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
906 ** <li> The application must not modify the SQL statement text passed into
907 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
908 ** </ul>
909 */
910 SQLITE_API int sqlite3_exec(
911   sqlite3*,                                  /* An open database */
912   const char *sql,                           /* SQL to be evaluated */
913   int (*callback)(void*,int,char**,char**),  /* Callback function */
914   void *,                                    /* 1st argument to callback */
915   char **errmsg                              /* Error msg written here */
916 );
917 
918 /*
919 ** CAPI3REF: Result Codes
920 ** KEYWORDS: SQLITE_OK {error code} {error codes}
921 ** KEYWORDS: {result code} {result codes}
922 **
923 ** Many SQLite functions return an integer result code from the set shown
924 ** here in order to indicates success or failure.
925 **
926 ** New error codes may be added in future versions of SQLite.
927 **
928 ** See also: [SQLITE_IOERR_READ | extended result codes],
929 ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
930 */
931 #define SQLITE_OK           0   /* Successful result */
932 /* beginning-of-error-codes */
933 #define SQLITE_ERROR        1   /* SQL error or missing database */
934 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
935 #define SQLITE_PERM         3   /* Access permission denied */
936 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
937 #define SQLITE_BUSY         5   /* The database file is locked */
938 #define SQLITE_LOCKED       6   /* A table in the database is locked */
939 #define SQLITE_NOMEM        7   /* A malloc() failed */
940 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
941 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
942 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
943 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
944 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
945 #define SQLITE_FULL        13   /* Insertion failed because database is full */
946 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
947 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
948 #define SQLITE_EMPTY       16   /* Database is empty */
949 #define SQLITE_SCHEMA      17   /* The database schema changed */
950 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
951 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
952 #define SQLITE_MISMATCH    20   /* Data type mismatch */
953 #define SQLITE_MISUSE      21   /* Library used incorrectly */
954 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
955 #define SQLITE_AUTH        23   /* Authorization denied */
956 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
957 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
958 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
959 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
960 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
961 /* end-of-error-codes */
962 
963 /*
964 ** CAPI3REF: Extended Result Codes
965 ** KEYWORDS: {extended error code} {extended error codes}
966 ** KEYWORDS: {extended result code} {extended result codes}
967 **
968 ** In its default configuration, SQLite API routines return one of 26 integer
969 ** [SQLITE_OK | result codes].  However, experience has shown that many of
970 ** these result codes are too coarse-grained.  They do not provide as
971 ** much information about problems as programmers might like.  In an effort to
972 ** address this, newer versions of SQLite (version 3.3.8 and later) include
973 ** support for additional result codes that provide more detailed information
974 ** about errors. The extended result codes are enabled or disabled
975 ** on a per database connection basis using the
976 ** [sqlite3_extended_result_codes()] API.
977 **
978 ** Some of the available extended result codes are listed here.
979 ** One may expect the number of extended result codes will be expand
980 ** over time.  Software that uses extended result codes should expect
981 ** to see new result codes in future releases of SQLite.
982 **
983 ** The SQLITE_OK result code will never be extended.  It will always
984 ** be exactly zero.
985 */
986 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
987 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
988 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
989 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
990 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
991 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
992 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
993 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
994 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
995 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
996 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
997 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
998 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
999 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1000 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1001 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1002 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1003 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1004 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1005 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1006 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1007 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1008 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1009 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1010 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1011 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1012 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1013 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1014 
1015 /*
1016 ** CAPI3REF: Flags For File Open Operations
1017 **
1018 ** These bit values are intended for use in the
1019 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1020 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1021 */
1022 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1023 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1024 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1025 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1026 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1027 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1028 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1029 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1030 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1031 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1032 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1033 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1034 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1035 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1036 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1037 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1038 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1039 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1040 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1041 
1042 /* Reserved:                         0x00F00000 */
1043 
1044 /*
1045 ** CAPI3REF: Device Characteristics
1046 **
1047 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1048 ** object returns an integer which is a vector of the these
1049 ** bit values expressing I/O characteristics of the mass storage
1050 ** device that holds the file that the [sqlite3_io_methods]
1051 ** refers to.
1052 **
1053 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1054 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1055 ** mean that writes of blocks that are nnn bytes in size and
1056 ** are aligned to an address which is an integer multiple of
1057 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1058 ** that when data is appended to a file, the data is appended
1059 ** first then the size of the file is extended, never the other
1060 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1061 ** information is written to disk in the same order as calls
1062 ** to xWrite().
1063 */
1064 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1065 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1066 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1067 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1068 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1069 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1070 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1071 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1072 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1073 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1074 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1075 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1076 
1077 /*
1078 ** CAPI3REF: File Locking Levels
1079 **
1080 ** SQLite uses one of these integer values as the second
1081 ** argument to calls it makes to the xLock() and xUnlock() methods
1082 ** of an [sqlite3_io_methods] object.
1083 */
1084 #define SQLITE_LOCK_NONE          0
1085 #define SQLITE_LOCK_SHARED        1
1086 #define SQLITE_LOCK_RESERVED      2
1087 #define SQLITE_LOCK_PENDING       3
1088 #define SQLITE_LOCK_EXCLUSIVE     4
1089 
1090 /*
1091 ** CAPI3REF: Synchronization Type Flags
1092 **
1093 ** When SQLite invokes the xSync() method of an
1094 ** [sqlite3_io_methods] object it uses a combination of
1095 ** these integer values as the second argument.
1096 **
1097 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1098 ** sync operation only needs to flush data to mass storage.  Inode
1099 ** information need not be flushed. If the lower four bits of the flag
1100 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1101 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1102 ** to use Mac OS X style fullsync instead of fsync().
1103 **
1104 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1105 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1106 ** settings.  The [synchronous pragma] determines when calls to the
1107 ** xSync VFS method occur and applies uniformly across all platforms.
1108 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1109 ** energetic or rigorous or forceful the sync operations are and
1110 ** only make a difference on Mac OSX for the default SQLite code.
1111 ** (Third-party VFS implementations might also make the distinction
1112 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1113 ** operating systems natively supported by SQLite, only Mac OSX
1114 ** cares about the difference.)
1115 */
1116 #define SQLITE_SYNC_NORMAL        0x00002
1117 #define SQLITE_SYNC_FULL          0x00003
1118 #define SQLITE_SYNC_DATAONLY      0x00010
1119 
1120 /*
1121 ** CAPI3REF: OS Interface Open File Handle
1122 **
1123 ** An [sqlite3_file] object represents an open file in the
1124 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1125 ** implementations will
1126 ** want to subclass this object by appending additional fields
1127 ** for their own use.  The pMethods entry is a pointer to an
1128 ** [sqlite3_io_methods] object that defines methods for performing
1129 ** I/O operations on the open file.
1130 */
1131 typedef struct sqlite3_file sqlite3_file;
1132 struct sqlite3_file {
1133   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1134 };
1135 
1136 /*
1137 ** CAPI3REF: OS Interface File Virtual Methods Object
1138 **
1139 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1140 ** [sqlite3_file] object (or, more commonly, a subclass of the
1141 ** [sqlite3_file] object) with a pointer to an instance of this object.
1142 ** This object defines the methods used to perform various operations
1143 ** against the open file represented by the [sqlite3_file] object.
1144 **
1145 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1146 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1147 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1148 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1149 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1150 ** to NULL.
1151 **
1152 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1153 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1154 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1155 ** flag may be ORed in to indicate that only the data of the file
1156 ** and not its inode needs to be synced.
1157 **
1158 ** The integer values to xLock() and xUnlock() are one of
1159 ** <ul>
1160 ** <li> [SQLITE_LOCK_NONE],
1161 ** <li> [SQLITE_LOCK_SHARED],
1162 ** <li> [SQLITE_LOCK_RESERVED],
1163 ** <li> [SQLITE_LOCK_PENDING], or
1164 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1165 ** </ul>
1166 ** xLock() increases the lock. xUnlock() decreases the lock.
1167 ** The xCheckReservedLock() method checks whether any database connection,
1168 ** either in this process or in some other process, is holding a RESERVED,
1169 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1170 ** if such a lock exists and false otherwise.
1171 **
1172 ** The xFileControl() method is a generic interface that allows custom
1173 ** VFS implementations to directly control an open file using the
1174 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1175 ** integer opcode.  The third argument is a generic pointer intended to
1176 ** point to a structure that may contain arguments or space in which to
1177 ** write return values.  Potential uses for xFileControl() might be
1178 ** functions to enable blocking locks with timeouts, to change the
1179 ** locking strategy (for example to use dot-file locks), to inquire
1180 ** about the status of a lock, or to break stale locks.  The SQLite
1181 ** core reserves all opcodes less than 100 for its own use.
1182 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1183 ** Applications that define a custom xFileControl method should use opcodes
1184 ** greater than 100 to avoid conflicts.  VFS implementations should
1185 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1186 ** recognize.
1187 **
1188 ** The xSectorSize() method returns the sector size of the
1189 ** device that underlies the file.  The sector size is the
1190 ** minimum write that can be performed without disturbing
1191 ** other bytes in the file.  The xDeviceCharacteristics()
1192 ** method returns a bit vector describing behaviors of the
1193 ** underlying device:
1194 **
1195 ** <ul>
1196 ** <li> [SQLITE_IOCAP_ATOMIC]
1197 ** <li> [SQLITE_IOCAP_ATOMIC512]
1198 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1199 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1200 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1201 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1202 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1203 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1204 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1205 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1206 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1207 ** </ul>
1208 **
1209 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1210 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1211 ** mean that writes of blocks that are nnn bytes in size and
1212 ** are aligned to an address which is an integer multiple of
1213 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1214 ** that when data is appended to a file, the data is appended
1215 ** first then the size of the file is extended, never the other
1216 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1217 ** information is written to disk in the same order as calls
1218 ** to xWrite().
1219 **
1220 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1221 ** in the unread portions of the buffer with zeros.  A VFS that
1222 ** fails to zero-fill short reads might seem to work.  However,
1223 ** failure to zero-fill short reads will eventually lead to
1224 ** database corruption.
1225 */
1226 typedef struct sqlite3_io_methods sqlite3_io_methods;
1227 struct sqlite3_io_methods {
1228   int iVersion;
1229   int (*xClose)(sqlite3_file*);
1230   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1231   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1232   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1233   int (*xSync)(sqlite3_file*, int flags);
1234   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1235   int (*xLock)(sqlite3_file*, int);
1236   int (*xUnlock)(sqlite3_file*, int);
1237   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1238   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1239   int (*xSectorSize)(sqlite3_file*);
1240   int (*xDeviceCharacteristics)(sqlite3_file*);
1241   /* Methods above are valid for version 1 */
1242   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1243   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1244   void (*xShmBarrier)(sqlite3_file*);
1245   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1246   /* Methods above are valid for version 2 */
1247   /* Additional methods may be added in future releases */
1248 };
1249 
1250 /*
1251 ** CAPI3REF: Standard File Control Opcodes
1252 **
1253 ** These integer constants are opcodes for the xFileControl method
1254 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1255 ** interface.
1256 **
1257 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1258 ** opcode causes the xFileControl method to write the current state of
1259 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1260 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1261 ** into an integer that the pArg argument points to. This capability
1262 ** is used during testing and only needs to be supported when SQLITE_TEST
1263 ** is defined.
1264 **
1265 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1266 ** layer a hint of how large the database file will grow to be during the
1267 ** current transaction.  This hint is not guaranteed to be accurate but it
1268 ** is often close.  The underlying VFS might choose to preallocate database
1269 ** file space based on this hint in order to help writes to the database
1270 ** file run faster.
1271 **
1272 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1273 ** extends and truncates the database file in chunks of a size specified
1274 ** by the user. The fourth argument to [sqlite3_file_control()] should
1275 ** point to an integer (type int) containing the new chunk-size to use
1276 ** for the nominated database. Allocating database file space in large
1277 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1278 ** improve performance on some systems.
1279 **
1280 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1281 ** to the [sqlite3_file] object associated with a particular database
1282 ** connection.  See the [sqlite3_file_control()] documentation for
1283 ** additional information.
1284 **
1285 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1286 ** SQLite and sent to all VFSes in place of a call to the xSync method
1287 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1288 ** Some specialized VFSes need this signal in order to operate correctly
1289 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1290 ** VFSes do not need this signal and should silently ignore this opcode.
1291 ** Applications should not call [sqlite3_file_control()] with this
1292 ** opcode as doing so may disrupt the operation of the specialized VFSes
1293 ** that do require it.
1294 **
1295 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1296 ** retry counts and intervals for certain disk I/O operations for the
1297 ** windows [VFS] in order to work to provide robustness against
1298 ** anti-virus programs.  By default, the windows VFS will retry file read,
1299 ** file write, and file delete opertions up to 10 times, with a delay
1300 ** of 25 milliseconds before the first retry and with the delay increasing
1301 ** by an additional 25 milliseconds with each subsequent retry.  This
1302 ** opcode allows those to values (10 retries and 25 milliseconds of delay)
1303 ** to be adjusted.  The values are changed for all database connections
1304 ** within the same process.  The argument is a pointer to an array of two
1305 ** integers where the first integer i the new retry count and the second
1306 ** integer is the delay.  If either integer is negative, then the setting
1307 ** is not changed but instead the prior value of that setting is written
1308 ** into the array entry, allowing the current retry settings to be
1309 ** interrogated.  The zDbName parameter is ignored.
1310 **
1311 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1312 ** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
1313 ** write ahead log and shared memory files used for transaction control
1314 ** are automatically deleted when the latest connection to the database
1315 ** closes.  Setting persistent WAL mode causes those files to persist after
1316 ** close.  Persisting the files is useful when other processes that do not
1317 ** have write permission on the directory containing the database file want
1318 ** to read the database file, as the WAL and shared memory files must exist
1319 ** in order for the database to be readable.  The fourth parameter to
1320 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1321 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1322 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1323 ** WAL persistence setting.
1324 **
1325 */
1326 #define SQLITE_FCNTL_LOCKSTATE        1
1327 #define SQLITE_GET_LOCKPROXYFILE      2
1328 #define SQLITE_SET_LOCKPROXYFILE      3
1329 #define SQLITE_LAST_ERRNO             4
1330 #define SQLITE_FCNTL_SIZE_HINT        5
1331 #define SQLITE_FCNTL_CHUNK_SIZE       6
1332 #define SQLITE_FCNTL_FILE_POINTER     7
1333 #define SQLITE_FCNTL_SYNC_OMITTED     8
1334 #define SQLITE_FCNTL_WIN32_AV_RETRY   9
1335 #define SQLITE_FCNTL_PERSIST_WAL     10
1336 
1337 /*
1338 ** CAPI3REF: Mutex Handle
1339 **
1340 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1341 ** abstract type for a mutex object.  The SQLite core never looks
1342 ** at the internal representation of an [sqlite3_mutex].  It only
1343 ** deals with pointers to the [sqlite3_mutex] object.
1344 **
1345 ** Mutexes are created using [sqlite3_mutex_alloc()].
1346 */
1347 typedef struct sqlite3_mutex sqlite3_mutex;
1348 
1349 /*
1350 ** CAPI3REF: OS Interface Object
1351 **
1352 ** An instance of the sqlite3_vfs object defines the interface between
1353 ** the SQLite core and the underlying operating system.  The "vfs"
1354 ** in the name of the object stands for "virtual file system".  See
1355 ** the [VFS | VFS documentation] for further information.
1356 **
1357 ** The value of the iVersion field is initially 1 but may be larger in
1358 ** future versions of SQLite.  Additional fields may be appended to this
1359 ** object when the iVersion value is increased.  Note that the structure
1360 ** of the sqlite3_vfs object changes in the transaction between
1361 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1362 ** modified.
1363 **
1364 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1365 ** structure used by this VFS.  mxPathname is the maximum length of
1366 ** a pathname in this VFS.
1367 **
1368 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1369 ** the pNext pointer.  The [sqlite3_vfs_register()]
1370 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1371 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1372 ** searches the list.  Neither the application code nor the VFS
1373 ** implementation should use the pNext pointer.
1374 **
1375 ** The pNext field is the only field in the sqlite3_vfs
1376 ** structure that SQLite will ever modify.  SQLite will only access
1377 ** or modify this field while holding a particular static mutex.
1378 ** The application should never modify anything within the sqlite3_vfs
1379 ** object once the object has been registered.
1380 **
1381 ** The zName field holds the name of the VFS module.  The name must
1382 ** be unique across all VFS modules.
1383 **
1384 ** [[sqlite3_vfs.xOpen]]
1385 ** ^SQLite guarantees that the zFilename parameter to xOpen
1386 ** is either a NULL pointer or string obtained
1387 ** from xFullPathname() with an optional suffix added.
1388 ** ^If a suffix is added to the zFilename parameter, it will
1389 ** consist of a single "-" character followed by no more than
1390 ** 10 alphanumeric and/or "-" characters.
1391 ** ^SQLite further guarantees that
1392 ** the string will be valid and unchanged until xClose() is
1393 ** called. Because of the previous sentence,
1394 ** the [sqlite3_file] can safely store a pointer to the
1395 ** filename if it needs to remember the filename for some reason.
1396 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1397 ** must invent its own temporary name for the file.  ^Whenever the
1398 ** xFilename parameter is NULL it will also be the case that the
1399 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1400 **
1401 ** The flags argument to xOpen() includes all bits set in
1402 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1403 ** or [sqlite3_open16()] is used, then flags includes at least
1404 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1405 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1406 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1407 **
1408 ** ^(SQLite will also add one of the following flags to the xOpen()
1409 ** call, depending on the object being opened:
1410 **
1411 ** <ul>
1412 ** <li>  [SQLITE_OPEN_MAIN_DB]
1413 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1414 ** <li>  [SQLITE_OPEN_TEMP_DB]
1415 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1416 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1417 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1418 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1419 ** <li>  [SQLITE_OPEN_WAL]
1420 ** </ul>)^
1421 **
1422 ** The file I/O implementation can use the object type flags to
1423 ** change the way it deals with files.  For example, an application
1424 ** that does not care about crash recovery or rollback might make
1425 ** the open of a journal file a no-op.  Writes to this journal would
1426 ** also be no-ops, and any attempt to read the journal would return
1427 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1428 ** file will be doing page-aligned sector reads and writes in a random
1429 ** order and set up its I/O subsystem accordingly.
1430 **
1431 ** SQLite might also add one of the following flags to the xOpen method:
1432 **
1433 ** <ul>
1434 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1435 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1436 ** </ul>
1437 **
1438 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1439 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1440 ** will be set for TEMP databases and their journals, transient
1441 ** databases, and subjournals.
1442 **
1443 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1444 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1445 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1446 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1447 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1448 ** be created, and that it is an error if it already exists.
1449 ** It is <i>not</i> used to indicate the file should be opened
1450 ** for exclusive access.
1451 **
1452 ** ^At least szOsFile bytes of memory are allocated by SQLite
1453 ** to hold the  [sqlite3_file] structure passed as the third
1454 ** argument to xOpen.  The xOpen method does not have to
1455 ** allocate the structure; it should just fill it in.  Note that
1456 ** the xOpen method must set the sqlite3_file.pMethods to either
1457 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1458 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1459 ** element will be valid after xOpen returns regardless of the success
1460 ** or failure of the xOpen call.
1461 **
1462 ** [[sqlite3_vfs.xAccess]]
1463 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1464 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1465 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1466 ** to test whether a file is at least readable.   The file can be a
1467 ** directory.
1468 **
1469 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1470 ** output buffer xFullPathname.  The exact size of the output buffer
1471 ** is also passed as a parameter to both  methods. If the output buffer
1472 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1473 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1474 ** to prevent this by setting mxPathname to a sufficiently large value.
1475 **
1476 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1477 ** interfaces are not strictly a part of the filesystem, but they are
1478 ** included in the VFS structure for completeness.
1479 ** The xRandomness() function attempts to return nBytes bytes
1480 ** of good-quality randomness into zOut.  The return value is
1481 ** the actual number of bytes of randomness obtained.
1482 ** The xSleep() method causes the calling thread to sleep for at
1483 ** least the number of microseconds given.  ^The xCurrentTime()
1484 ** method returns a Julian Day Number for the current date and time as
1485 ** a floating point value.
1486 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1487 ** Day Number multiplied by 86400000 (the number of milliseconds in
1488 ** a 24-hour day).
1489 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1490 ** date and time if that method is available (if iVersion is 2 or
1491 ** greater and the function pointer is not NULL) and will fall back
1492 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1493 **
1494 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1495 ** are not used by the SQLite core.  These optional interfaces are provided
1496 ** by some VFSes to facilitate testing of the VFS code. By overriding
1497 ** system calls with functions under its control, a test program can
1498 ** simulate faults and error conditions that would otherwise be difficult
1499 ** or impossible to induce.  The set of system calls that can be overridden
1500 ** varies from one VFS to another, and from one version of the same VFS to the
1501 ** next.  Applications that use these interfaces must be prepared for any
1502 ** or all of these interfaces to be NULL or for their behavior to change
1503 ** from one release to the next.  Applications must not attempt to access
1504 ** any of these methods if the iVersion of the VFS is less than 3.
1505 */
1506 typedef struct sqlite3_vfs sqlite3_vfs;
1507 typedef void (*sqlite3_syscall_ptr)(void);
1508 struct sqlite3_vfs {
1509   int iVersion;            /* Structure version number (currently 3) */
1510   int szOsFile;            /* Size of subclassed sqlite3_file */
1511   int mxPathname;          /* Maximum file pathname length */
1512   sqlite3_vfs *pNext;      /* Next registered VFS */
1513   const char *zName;       /* Name of this virtual file system */
1514   void *pAppData;          /* Pointer to application-specific data */
1515   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1516                int flags, int *pOutFlags);
1517   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1518   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1519   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1520   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1521   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1522   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1523   void (*xDlClose)(sqlite3_vfs*, void*);
1524   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1525   int (*xSleep)(sqlite3_vfs*, int microseconds);
1526   int (*xCurrentTime)(sqlite3_vfs*, double*);
1527   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1528   /*
1529   ** The methods above are in version 1 of the sqlite_vfs object
1530   ** definition.  Those that follow are added in version 2 or later
1531   */
1532   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1533   /*
1534   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1535   ** Those below are for version 3 and greater.
1536   */
1537   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1538   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1539   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1540   /*
1541   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1542   ** New fields may be appended in figure versions.  The iVersion
1543   ** value will increment whenever this happens.
1544   */
1545 };
1546 
1547 /*
1548 ** CAPI3REF: Flags for the xAccess VFS method
1549 **
1550 ** These integer constants can be used as the third parameter to
1551 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1552 ** what kind of permissions the xAccess method is looking for.
1553 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1554 ** simply checks whether the file exists.
1555 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1556 ** checks whether the named directory is both readable and writable
1557 ** (in other words, if files can be added, removed, and renamed within
1558 ** the directory).
1559 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1560 ** [temp_store_directory pragma], though this could change in a future
1561 ** release of SQLite.
1562 ** With SQLITE_ACCESS_READ, the xAccess method
1563 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1564 ** currently unused, though it might be used in a future release of
1565 ** SQLite.
1566 */
1567 #define SQLITE_ACCESS_EXISTS    0
1568 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1569 #define SQLITE_ACCESS_READ      2   /* Unused */
1570 
1571 /*
1572 ** CAPI3REF: Flags for the xShmLock VFS method
1573 **
1574 ** These integer constants define the various locking operations
1575 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1576 ** following are the only legal combinations of flags to the
1577 ** xShmLock method:
1578 **
1579 ** <ul>
1580 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1581 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1582 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1583 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1584 ** </ul>
1585 **
1586 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1587 ** was given no the corresponding lock.
1588 **
1589 ** The xShmLock method can transition between unlocked and SHARED or
1590 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1591 ** and EXCLUSIVE.
1592 */
1593 #define SQLITE_SHM_UNLOCK       1
1594 #define SQLITE_SHM_LOCK         2
1595 #define SQLITE_SHM_SHARED       4
1596 #define SQLITE_SHM_EXCLUSIVE    8
1597 
1598 /*
1599 ** CAPI3REF: Maximum xShmLock index
1600 **
1601 ** The xShmLock method on [sqlite3_io_methods] may use values
1602 ** between 0 and this upper bound as its "offset" argument.
1603 ** The SQLite core will never attempt to acquire or release a
1604 ** lock outside of this range
1605 */
1606 #define SQLITE_SHM_NLOCK        8
1607 
1608 
1609 /*
1610 ** CAPI3REF: Initialize The SQLite Library
1611 **
1612 ** ^The sqlite3_initialize() routine initializes the
1613 ** SQLite library.  ^The sqlite3_shutdown() routine
1614 ** deallocates any resources that were allocated by sqlite3_initialize().
1615 ** These routines are designed to aid in process initialization and
1616 ** shutdown on embedded systems.  Workstation applications using
1617 ** SQLite normally do not need to invoke either of these routines.
1618 **
1619 ** A call to sqlite3_initialize() is an "effective" call if it is
1620 ** the first time sqlite3_initialize() is invoked during the lifetime of
1621 ** the process, or if it is the first time sqlite3_initialize() is invoked
1622 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1623 ** of sqlite3_initialize() does any initialization.  All other calls
1624 ** are harmless no-ops.)^
1625 **
1626 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1627 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1628 ** an effective call to sqlite3_shutdown() does any deinitialization.
1629 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1630 **
1631 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1632 ** is not.  The sqlite3_shutdown() interface must only be called from a
1633 ** single thread.  All open [database connections] must be closed and all
1634 ** other SQLite resources must be deallocated prior to invoking
1635 ** sqlite3_shutdown().
1636 **
1637 ** Among other things, ^sqlite3_initialize() will invoke
1638 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1639 ** will invoke sqlite3_os_end().
1640 **
1641 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1642 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1643 ** the library (perhaps it is unable to allocate a needed resource such
1644 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1645 **
1646 ** ^The sqlite3_initialize() routine is called internally by many other
1647 ** SQLite interfaces so that an application usually does not need to
1648 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1649 ** calls sqlite3_initialize() so the SQLite library will be automatically
1650 ** initialized when [sqlite3_open()] is called if it has not be initialized
1651 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1652 ** compile-time option, then the automatic calls to sqlite3_initialize()
1653 ** are omitted and the application must call sqlite3_initialize() directly
1654 ** prior to using any other SQLite interface.  For maximum portability,
1655 ** it is recommended that applications always invoke sqlite3_initialize()
1656 ** directly prior to using any other SQLite interface.  Future releases
1657 ** of SQLite may require this.  In other words, the behavior exhibited
1658 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1659 ** default behavior in some future release of SQLite.
1660 **
1661 ** The sqlite3_os_init() routine does operating-system specific
1662 ** initialization of the SQLite library.  The sqlite3_os_end()
1663 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1664 ** performed by these routines include allocation or deallocation
1665 ** of static resources, initialization of global variables,
1666 ** setting up a default [sqlite3_vfs] module, or setting up
1667 ** a default configuration using [sqlite3_config()].
1668 **
1669 ** The application should never invoke either sqlite3_os_init()
1670 ** or sqlite3_os_end() directly.  The application should only invoke
1671 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1672 ** interface is called automatically by sqlite3_initialize() and
1673 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1674 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1675 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1676 ** When [custom builds | built for other platforms]
1677 ** (using the [SQLITE_OS_OTHER=1] compile-time
1678 ** option) the application must supply a suitable implementation for
1679 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1680 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1681 ** must return [SQLITE_OK] on success and some other [error code] upon
1682 ** failure.
1683 */
1684 SQLITE_API int sqlite3_initialize(void);
1685 SQLITE_API int sqlite3_shutdown(void);
1686 SQLITE_API int sqlite3_os_init(void);
1687 SQLITE_API int sqlite3_os_end(void);
1688 
1689 /*
1690 ** CAPI3REF: Configuring The SQLite Library
1691 **
1692 ** The sqlite3_config() interface is used to make global configuration
1693 ** changes to SQLite in order to tune SQLite to the specific needs of
1694 ** the application.  The default configuration is recommended for most
1695 ** applications and so this routine is usually not necessary.  It is
1696 ** provided to support rare applications with unusual needs.
1697 **
1698 ** The sqlite3_config() interface is not threadsafe.  The application
1699 ** must insure that no other SQLite interfaces are invoked by other
1700 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1701 ** may only be invoked prior to library initialization using
1702 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1703 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1704 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1705 ** Note, however, that ^sqlite3_config() can be called as part of the
1706 ** implementation of an application-defined [sqlite3_os_init()].
1707 **
1708 ** The first argument to sqlite3_config() is an integer
1709 ** [configuration option] that determines
1710 ** what property of SQLite is to be configured.  Subsequent arguments
1711 ** vary depending on the [configuration option]
1712 ** in the first argument.
1713 **
1714 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1715 ** ^If the option is unknown or SQLite is unable to set the option
1716 ** then this routine returns a non-zero [error code].
1717 */
1718 SQLITE_API int sqlite3_config(int, ...);
1719 
1720 /*
1721 ** CAPI3REF: Configure database connections
1722 **
1723 ** The sqlite3_db_config() interface is used to make configuration
1724 ** changes to a [database connection].  The interface is similar to
1725 ** [sqlite3_config()] except that the changes apply to a single
1726 ** [database connection] (specified in the first argument).
1727 **
1728 ** The second argument to sqlite3_db_config(D,V,...)  is the
1729 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1730 ** that indicates what aspect of the [database connection] is being configured.
1731 ** Subsequent arguments vary depending on the configuration verb.
1732 **
1733 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1734 ** the call is considered successful.
1735 */
1736 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1737 
1738 /*
1739 ** CAPI3REF: Memory Allocation Routines
1740 **
1741 ** An instance of this object defines the interface between SQLite
1742 ** and low-level memory allocation routines.
1743 **
1744 ** This object is used in only one place in the SQLite interface.
1745 ** A pointer to an instance of this object is the argument to
1746 ** [sqlite3_config()] when the configuration option is
1747 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1748 ** By creating an instance of this object
1749 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1750 ** during configuration, an application can specify an alternative
1751 ** memory allocation subsystem for SQLite to use for all of its
1752 ** dynamic memory needs.
1753 **
1754 ** Note that SQLite comes with several [built-in memory allocators]
1755 ** that are perfectly adequate for the overwhelming majority of applications
1756 ** and that this object is only useful to a tiny minority of applications
1757 ** with specialized memory allocation requirements.  This object is
1758 ** also used during testing of SQLite in order to specify an alternative
1759 ** memory allocator that simulates memory out-of-memory conditions in
1760 ** order to verify that SQLite recovers gracefully from such
1761 ** conditions.
1762 **
1763 ** The xMalloc, xRealloc, and xFree methods must work like the
1764 ** malloc(), realloc() and free() functions from the standard C library.
1765 ** ^SQLite guarantees that the second argument to
1766 ** xRealloc is always a value returned by a prior call to xRoundup.
1767 **
1768 ** xSize should return the allocated size of a memory allocation
1769 ** previously obtained from xMalloc or xRealloc.  The allocated size
1770 ** is always at least as big as the requested size but may be larger.
1771 **
1772 ** The xRoundup method returns what would be the allocated size of
1773 ** a memory allocation given a particular requested size.  Most memory
1774 ** allocators round up memory allocations at least to the next multiple
1775 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1776 ** Every memory allocation request coming in through [sqlite3_malloc()]
1777 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1778 ** that causes the corresponding memory allocation to fail.
1779 **
1780 ** The xInit method initializes the memory allocator.  (For example,
1781 ** it might allocate any require mutexes or initialize internal data
1782 ** structures.  The xShutdown method is invoked (indirectly) by
1783 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1784 ** by xInit.  The pAppData pointer is used as the only parameter to
1785 ** xInit and xShutdown.
1786 **
1787 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1788 ** the xInit method, so the xInit method need not be threadsafe.  The
1789 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1790 ** not need to be threadsafe either.  For all other methods, SQLite
1791 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1792 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1793 ** it is by default) and so the methods are automatically serialized.
1794 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1795 ** methods must be threadsafe or else make their own arrangements for
1796 ** serialization.
1797 **
1798 ** SQLite will never invoke xInit() more than once without an intervening
1799 ** call to xShutdown().
1800 */
1801 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1802 struct sqlite3_mem_methods {
1803   void *(*xMalloc)(int);         /* Memory allocation function */
1804   void (*xFree)(void*);          /* Free a prior allocation */
1805   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1806   int (*xSize)(void*);           /* Return the size of an allocation */
1807   int (*xRoundup)(int);          /* Round up request size to allocation size */
1808   int (*xInit)(void*);           /* Initialize the memory allocator */
1809   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1810   void *pAppData;                /* Argument to xInit() and xShutdown() */
1811 };
1812 
1813 /*
1814 ** CAPI3REF: Configuration Options
1815 ** KEYWORDS: {configuration option}
1816 **
1817 ** These constants are the available integer configuration options that
1818 ** can be passed as the first argument to the [sqlite3_config()] interface.
1819 **
1820 ** New configuration options may be added in future releases of SQLite.
1821 ** Existing configuration options might be discontinued.  Applications
1822 ** should check the return code from [sqlite3_config()] to make sure that
1823 ** the call worked.  The [sqlite3_config()] interface will return a
1824 ** non-zero [error code] if a discontinued or unsupported configuration option
1825 ** is invoked.
1826 **
1827 ** <dl>
1828 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1829 ** <dd>There are no arguments to this option.  ^This option sets the
1830 ** [threading mode] to Single-thread.  In other words, it disables
1831 ** all mutexing and puts SQLite into a mode where it can only be used
1832 ** by a single thread.   ^If SQLite is compiled with
1833 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1834 ** it is not possible to change the [threading mode] from its default
1835 ** value of Single-thread and so [sqlite3_config()] will return
1836 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1837 ** configuration option.</dd>
1838 **
1839 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1840 ** <dd>There are no arguments to this option.  ^This option sets the
1841 ** [threading mode] to Multi-thread.  In other words, it disables
1842 ** mutexing on [database connection] and [prepared statement] objects.
1843 ** The application is responsible for serializing access to
1844 ** [database connections] and [prepared statements].  But other mutexes
1845 ** are enabled so that SQLite will be safe to use in a multi-threaded
1846 ** environment as long as no two threads attempt to use the same
1847 ** [database connection] at the same time.  ^If SQLite is compiled with
1848 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1849 ** it is not possible to set the Multi-thread [threading mode] and
1850 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1851 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1852 **
1853 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1854 ** <dd>There are no arguments to this option.  ^This option sets the
1855 ** [threading mode] to Serialized. In other words, this option enables
1856 ** all mutexes including the recursive
1857 ** mutexes on [database connection] and [prepared statement] objects.
1858 ** In this mode (which is the default when SQLite is compiled with
1859 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1860 ** to [database connections] and [prepared statements] so that the
1861 ** application is free to use the same [database connection] or the
1862 ** same [prepared statement] in different threads at the same time.
1863 ** ^If SQLite is compiled with
1864 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1865 ** it is not possible to set the Serialized [threading mode] and
1866 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1867 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1868 **
1869 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1870 ** <dd> ^(This option takes a single argument which is a pointer to an
1871 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1872 ** alternative low-level memory allocation routines to be used in place of
1873 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1874 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1875 ** before the [sqlite3_config()] call returns.</dd>
1876 **
1877 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1878 ** <dd> ^(This option takes a single argument which is a pointer to an
1879 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1880 ** structure is filled with the currently defined memory allocation routines.)^
1881 ** This option can be used to overload the default memory allocation
1882 ** routines with a wrapper that simulations memory allocation failure or
1883 ** tracks memory usage, for example. </dd>
1884 **
1885 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1886 ** <dd> ^This option takes single argument of type int, interpreted as a
1887 ** boolean, which enables or disables the collection of memory allocation
1888 ** statistics. ^(When memory allocation statistics are disabled, the
1889 ** following SQLite interfaces become non-operational:
1890 **   <ul>
1891 **   <li> [sqlite3_memory_used()]
1892 **   <li> [sqlite3_memory_highwater()]
1893 **   <li> [sqlite3_soft_heap_limit64()]
1894 **   <li> [sqlite3_status()]
1895 **   </ul>)^
1896 ** ^Memory allocation statistics are enabled by default unless SQLite is
1897 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1898 ** allocation statistics are disabled by default.
1899 ** </dd>
1900 **
1901 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1902 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1903 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1904 ** aligned memory buffer from which the scratch allocations will be
1905 ** drawn, the size of each scratch allocation (sz),
1906 ** and the maximum number of scratch allocations (N).  The sz
1907 ** argument must be a multiple of 16.
1908 ** The first argument must be a pointer to an 8-byte aligned buffer
1909 ** of at least sz*N bytes of memory.
1910 ** ^SQLite will use no more than two scratch buffers per thread.  So
1911 ** N should be set to twice the expected maximum number of threads.
1912 ** ^SQLite will never require a scratch buffer that is more than 6
1913 ** times the database page size. ^If SQLite needs needs additional
1914 ** scratch memory beyond what is provided by this configuration option, then
1915 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1916 **
1917 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1918 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1919 ** the database page cache with the default page cache implementation.
1920 ** This configuration should not be used if an application-define page
1921 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1922 ** There are three arguments to this option: A pointer to 8-byte aligned
1923 ** memory, the size of each page buffer (sz), and the number of pages (N).
1924 ** The sz argument should be the size of the largest database page
1925 ** (a power of two between 512 and 32768) plus a little extra for each
1926 ** page header.  ^The page header size is 20 to 40 bytes depending on
1927 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1928 ** to make sz a little too large.  The first
1929 ** argument should point to an allocation of at least sz*N bytes of memory.
1930 ** ^SQLite will use the memory provided by the first argument to satisfy its
1931 ** memory needs for the first N pages that it adds to cache.  ^If additional
1932 ** page cache memory is needed beyond what is provided by this option, then
1933 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1934 ** The pointer in the first argument must
1935 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1936 ** will be undefined.</dd>
1937 **
1938 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1939 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1940 ** for all of its dynamic memory allocation needs beyond those provided
1941 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1942 ** There are three arguments: An 8-byte aligned pointer to the memory,
1943 ** the number of bytes in the memory buffer, and the minimum allocation size.
1944 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1945 ** to using its default memory allocator (the system malloc() implementation),
1946 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1947 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1948 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1949 ** allocator is engaged to handle all of SQLites memory allocation needs.
1950 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1951 ** boundary or subsequent behavior of SQLite will be undefined.
1952 ** The minimum allocation size is capped at 2^12. Reasonable values
1953 ** for the minimum allocation size are 2^5 through 2^8.</dd>
1954 **
1955 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1956 ** <dd> ^(This option takes a single argument which is a pointer to an
1957 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1958 ** alternative low-level mutex routines to be used in place
1959 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1960 ** content of the [sqlite3_mutex_methods] structure before the call to
1961 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1962 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1963 ** the entire mutexing subsystem is omitted from the build and hence calls to
1964 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1965 ** return [SQLITE_ERROR].</dd>
1966 **
1967 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1968 ** <dd> ^(This option takes a single argument which is a pointer to an
1969 ** instance of the [sqlite3_mutex_methods] structure.  The
1970 ** [sqlite3_mutex_methods]
1971 ** structure is filled with the currently defined mutex routines.)^
1972 ** This option can be used to overload the default mutex allocation
1973 ** routines with a wrapper used to track mutex usage for performance
1974 ** profiling or testing, for example.   ^If SQLite is compiled with
1975 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1976 ** the entire mutexing subsystem is omitted from the build and hence calls to
1977 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1978 ** return [SQLITE_ERROR].</dd>
1979 **
1980 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1981 ** <dd> ^(This option takes two arguments that determine the default
1982 ** memory allocation for the lookaside memory allocator on each
1983 ** [database connection].  The first argument is the
1984 ** size of each lookaside buffer slot and the second is the number of
1985 ** slots allocated to each database connection.)^  ^(This option sets the
1986 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1987 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1988 ** configuration on individual connections.)^ </dd>
1989 **
1990 ** [[SQLITE_CONFIG_PCACHE]] <dt>SQLITE_CONFIG_PCACHE</dt>
1991 ** <dd> ^(This option takes a single argument which is a pointer to
1992 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1993 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1994 ** object and uses it for page cache memory allocations.</dd>
1995 **
1996 ** [[SQLITE_CONFIG_GETPCACHE]] <dt>SQLITE_CONFIG_GETPCACHE</dt>
1997 ** <dd> ^(This option takes a single argument which is a pointer to an
1998 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1999 ** page cache implementation into that object.)^ </dd>
2000 **
2001 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2002 ** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2003 ** function with a call signature of void(*)(void*,int,const char*),
2004 ** and a pointer to void. ^If the function pointer is not NULL, it is
2005 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2006 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2007 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2008 ** passed through as the first parameter to the application-defined logger
2009 ** function whenever that function is invoked.  ^The second parameter to
2010 ** the logger function is a copy of the first parameter to the corresponding
2011 ** [sqlite3_log()] call and is intended to be a [result code] or an
2012 ** [extended result code].  ^The third parameter passed to the logger is
2013 ** log message after formatting via [sqlite3_snprintf()].
2014 ** The SQLite logging interface is not reentrant; the logger function
2015 ** supplied by the application must not invoke any SQLite interface.
2016 ** In a multi-threaded application, the application-defined logger
2017 ** function must be threadsafe. </dd>
2018 **
2019 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2020 ** <dd> This option takes a single argument of type int. If non-zero, then
2021 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2022 ** is globally disabled. If URI handling is globally enabled, all filenames
2023 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2024 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2025 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2026 ** connection is opened. If it is globally disabled, filenames are
2027 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2028 ** database connection is opened. By default, URI handling is globally
2029 ** disabled. The default value may be changed by compiling with the
2030 ** [SQLITE_USE_URI] symbol defined.
2031 ** </dl>
2032 */
2033 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2034 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2035 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2036 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2037 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2038 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2039 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2040 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2041 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2042 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2043 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2044 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2045 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2046 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
2047 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
2048 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2049 #define SQLITE_CONFIG_URI          17  /* int */
2050 
2051 /*
2052 ** CAPI3REF: Database Connection Configuration Options
2053 **
2054 ** These constants are the available integer configuration options that
2055 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2056 **
2057 ** New configuration options may be added in future releases of SQLite.
2058 ** Existing configuration options might be discontinued.  Applications
2059 ** should check the return code from [sqlite3_db_config()] to make sure that
2060 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2061 ** non-zero [error code] if a discontinued or unsupported configuration option
2062 ** is invoked.
2063 **
2064 ** <dl>
2065 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2066 ** <dd> ^This option takes three additional arguments that determine the
2067 ** [lookaside memory allocator] configuration for the [database connection].
2068 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2069 ** pointer to a memory buffer to use for lookaside memory.
2070 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2071 ** may be NULL in which case SQLite will allocate the
2072 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2073 ** size of each lookaside buffer slot.  ^The third argument is the number of
2074 ** slots.  The size of the buffer in the first argument must be greater than
2075 ** or equal to the product of the second and third arguments.  The buffer
2076 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2077 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2078 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2079 ** configuration for a database connection can only be changed when that
2080 ** connection is not currently using lookaside memory, or in other words
2081 ** when the "current value" returned by
2082 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2083 ** Any attempt to change the lookaside memory configuration when lookaside
2084 ** memory is in use leaves the configuration unchanged and returns
2085 ** [SQLITE_BUSY].)^</dd>
2086 **
2087 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2088 ** <dd> ^This option is used to enable or disable the enforcement of
2089 ** [foreign key constraints].  There should be two additional arguments.
2090 ** The first argument is an integer which is 0 to disable FK enforcement,
2091 ** positive to enable FK enforcement or negative to leave FK enforcement
2092 ** unchanged.  The second parameter is a pointer to an integer into which
2093 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2094 ** following this call.  The second parameter may be a NULL pointer, in
2095 ** which case the FK enforcement setting is not reported back. </dd>
2096 **
2097 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2098 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2099 ** There should be two additional arguments.
2100 ** The first argument is an integer which is 0 to disable triggers,
2101 ** positive to enable triggers or negative to leave the setting unchanged.
2102 ** The second parameter is a pointer to an integer into which
2103 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2104 ** following this call.  The second parameter may be a NULL pointer, in
2105 ** which case the trigger setting is not reported back. </dd>
2106 **
2107 ** </dl>
2108 */
2109 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2110 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2111 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2112 
2113 
2114 /*
2115 ** CAPI3REF: Enable Or Disable Extended Result Codes
2116 **
2117 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2118 ** [extended result codes] feature of SQLite. ^The extended result
2119 ** codes are disabled by default for historical compatibility.
2120 */
2121 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2122 
2123 /*
2124 ** CAPI3REF: Last Insert Rowid
2125 **
2126 ** ^Each entry in an SQLite table has a unique 64-bit signed
2127 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2128 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2129 ** names are not also used by explicitly declared columns. ^If
2130 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2131 ** is another alias for the rowid.
2132 **
2133 ** ^This routine returns the [rowid] of the most recent
2134 ** successful [INSERT] into the database from the [database connection]
2135 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2136 ** records the last insert rowid of both ordinary tables and [virtual tables].
2137 ** ^If no successful [INSERT]s
2138 ** have ever occurred on that database connection, zero is returned.
2139 **
2140 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2141 ** method, then this routine will return the [rowid] of the inserted
2142 ** row as long as the trigger or virtual table method is running.
2143 ** But once the trigger or virtual table method ends, the value returned
2144 ** by this routine reverts to what it was before the trigger or virtual
2145 ** table method began.)^
2146 **
2147 ** ^An [INSERT] that fails due to a constraint violation is not a
2148 ** successful [INSERT] and does not change the value returned by this
2149 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2150 ** and INSERT OR ABORT make no changes to the return value of this
2151 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2152 ** encounters a constraint violation, it does not fail.  The
2153 ** INSERT continues to completion after deleting rows that caused
2154 ** the constraint problem so INSERT OR REPLACE will always change
2155 ** the return value of this interface.)^
2156 **
2157 ** ^For the purposes of this routine, an [INSERT] is considered to
2158 ** be successful even if it is subsequently rolled back.
2159 **
2160 ** This function is accessible to SQL statements via the
2161 ** [last_insert_rowid() SQL function].
2162 **
2163 ** If a separate thread performs a new [INSERT] on the same
2164 ** database connection while the [sqlite3_last_insert_rowid()]
2165 ** function is running and thus changes the last insert [rowid],
2166 ** then the value returned by [sqlite3_last_insert_rowid()] is
2167 ** unpredictable and might not equal either the old or the new
2168 ** last insert [rowid].
2169 */
2170 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2171 
2172 /*
2173 ** CAPI3REF: Count The Number Of Rows Modified
2174 **
2175 ** ^This function returns the number of database rows that were changed
2176 ** or inserted or deleted by the most recently completed SQL statement
2177 ** on the [database connection] specified by the first parameter.
2178 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2179 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2180 ** triggers or [foreign key actions] are not counted.)^ Use the
2181 ** [sqlite3_total_changes()] function to find the total number of changes
2182 ** including changes caused by triggers and foreign key actions.
2183 **
2184 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2185 ** are not counted.  Only real table changes are counted.
2186 **
2187 ** ^(A "row change" is a change to a single row of a single table
2188 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2189 ** are changed as side effects of [REPLACE] constraint resolution,
2190 ** rollback, ABORT processing, [DROP TABLE], or by any other
2191 ** mechanisms do not count as direct row changes.)^
2192 **
2193 ** A "trigger context" is a scope of execution that begins and
2194 ** ends with the script of a [CREATE TRIGGER | trigger].
2195 ** Most SQL statements are
2196 ** evaluated outside of any trigger.  This is the "top level"
2197 ** trigger context.  If a trigger fires from the top level, a
2198 ** new trigger context is entered for the duration of that one
2199 ** trigger.  Subtriggers create subcontexts for their duration.
2200 **
2201 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2202 ** not create a new trigger context.
2203 **
2204 ** ^This function returns the number of direct row changes in the
2205 ** most recent INSERT, UPDATE, or DELETE statement within the same
2206 ** trigger context.
2207 **
2208 ** ^Thus, when called from the top level, this function returns the
2209 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2210 ** that also occurred at the top level.  ^(Within the body of a trigger,
2211 ** the sqlite3_changes() interface can be called to find the number of
2212 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2213 ** statement within the body of the same trigger.
2214 ** However, the number returned does not include changes
2215 ** caused by subtriggers since those have their own context.)^
2216 **
2217 ** See also the [sqlite3_total_changes()] interface, the
2218 ** [count_changes pragma], and the [changes() SQL function].
2219 **
2220 ** If a separate thread makes changes on the same database connection
2221 ** while [sqlite3_changes()] is running then the value returned
2222 ** is unpredictable and not meaningful.
2223 */
2224 SQLITE_API int sqlite3_changes(sqlite3*);
2225 
2226 /*
2227 ** CAPI3REF: Total Number Of Rows Modified
2228 **
2229 ** ^This function returns the number of row changes caused by [INSERT],
2230 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2231 ** ^(The count returned by sqlite3_total_changes() includes all changes
2232 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2233 ** [foreign key actions]. However,
2234 ** the count does not include changes used to implement [REPLACE] constraints,
2235 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2236 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2237 ** though if the INSTEAD OF trigger makes changes of its own, those changes
2238 ** are counted.)^
2239 ** ^The sqlite3_total_changes() function counts the changes as soon as
2240 ** the statement that makes them is completed (when the statement handle
2241 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2242 **
2243 ** See also the [sqlite3_changes()] interface, the
2244 ** [count_changes pragma], and the [total_changes() SQL function].
2245 **
2246 ** If a separate thread makes changes on the same database connection
2247 ** while [sqlite3_total_changes()] is running then the value
2248 ** returned is unpredictable and not meaningful.
2249 */
2250 SQLITE_API int sqlite3_total_changes(sqlite3*);
2251 
2252 /*
2253 ** CAPI3REF: Interrupt A Long-Running Query
2254 **
2255 ** ^This function causes any pending database operation to abort and
2256 ** return at its earliest opportunity. This routine is typically
2257 ** called in response to a user action such as pressing "Cancel"
2258 ** or Ctrl-C where the user wants a long query operation to halt
2259 ** immediately.
2260 **
2261 ** ^It is safe to call this routine from a thread different from the
2262 ** thread that is currently running the database operation.  But it
2263 ** is not safe to call this routine with a [database connection] that
2264 ** is closed or might close before sqlite3_interrupt() returns.
2265 **
2266 ** ^If an SQL operation is very nearly finished at the time when
2267 ** sqlite3_interrupt() is called, then it might not have an opportunity
2268 ** to be interrupted and might continue to completion.
2269 **
2270 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2271 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2272 ** that is inside an explicit transaction, then the entire transaction
2273 ** will be rolled back automatically.
2274 **
2275 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2276 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2277 ** that are started after the sqlite3_interrupt() call and before the
2278 ** running statements reaches zero are interrupted as if they had been
2279 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2280 ** that are started after the running statement count reaches zero are
2281 ** not effected by the sqlite3_interrupt().
2282 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2283 ** SQL statements is a no-op and has no effect on SQL statements
2284 ** that are started after the sqlite3_interrupt() call returns.
2285 **
2286 ** If the database connection closes while [sqlite3_interrupt()]
2287 ** is running then bad things will likely happen.
2288 */
2289 SQLITE_API void sqlite3_interrupt(sqlite3*);
2290 
2291 /*
2292 ** CAPI3REF: Determine If An SQL Statement Is Complete
2293 **
2294 ** These routines are useful during command-line input to determine if the
2295 ** currently entered text seems to form a complete SQL statement or
2296 ** if additional input is needed before sending the text into
2297 ** SQLite for parsing.  ^These routines return 1 if the input string
2298 ** appears to be a complete SQL statement.  ^A statement is judged to be
2299 ** complete if it ends with a semicolon token and is not a prefix of a
2300 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2301 ** string literals or quoted identifier names or comments are not
2302 ** independent tokens (they are part of the token in which they are
2303 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2304 ** and comments that follow the final semicolon are ignored.
2305 **
2306 ** ^These routines return 0 if the statement is incomplete.  ^If a
2307 ** memory allocation fails, then SQLITE_NOMEM is returned.
2308 **
2309 ** ^These routines do not parse the SQL statements thus
2310 ** will not detect syntactically incorrect SQL.
2311 **
2312 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2313 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2314 ** automatically by sqlite3_complete16().  If that initialization fails,
2315 ** then the return value from sqlite3_complete16() will be non-zero
2316 ** regardless of whether or not the input SQL is complete.)^
2317 **
2318 ** The input to [sqlite3_complete()] must be a zero-terminated
2319 ** UTF-8 string.
2320 **
2321 ** The input to [sqlite3_complete16()] must be a zero-terminated
2322 ** UTF-16 string in native byte order.
2323 */
2324 SQLITE_API int sqlite3_complete(const char *sql);
2325 SQLITE_API int sqlite3_complete16(const void *sql);
2326 
2327 /*
2328 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2329 **
2330 ** ^This routine sets a callback function that might be invoked whenever
2331 ** an attempt is made to open a database table that another thread
2332 ** or process has locked.
2333 **
2334 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2335 ** is returned immediately upon encountering the lock.  ^If the busy callback
2336 ** is not NULL, then the callback might be invoked with two arguments.
2337 **
2338 ** ^The first argument to the busy handler is a copy of the void* pointer which
2339 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2340 ** the busy handler callback is the number of times that the busy handler has
2341 ** been invoked for this locking event.  ^If the
2342 ** busy callback returns 0, then no additional attempts are made to
2343 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2344 ** ^If the callback returns non-zero, then another attempt
2345 ** is made to open the database for reading and the cycle repeats.
2346 **
2347 ** The presence of a busy handler does not guarantee that it will be invoked
2348 ** when there is lock contention. ^If SQLite determines that invoking the busy
2349 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2350 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2351 ** Consider a scenario where one process is holding a read lock that
2352 ** it is trying to promote to a reserved lock and
2353 ** a second process is holding a reserved lock that it is trying
2354 ** to promote to an exclusive lock.  The first process cannot proceed
2355 ** because it is blocked by the second and the second process cannot
2356 ** proceed because it is blocked by the first.  If both processes
2357 ** invoke the busy handlers, neither will make any progress.  Therefore,
2358 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2359 ** will induce the first process to release its read lock and allow
2360 ** the second process to proceed.
2361 **
2362 ** ^The default busy callback is NULL.
2363 **
2364 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2365 ** when SQLite is in the middle of a large transaction where all the
2366 ** changes will not fit into the in-memory cache.  SQLite will
2367 ** already hold a RESERVED lock on the database file, but it needs
2368 ** to promote this lock to EXCLUSIVE so that it can spill cache
2369 ** pages into the database file without harm to concurrent
2370 ** readers.  ^If it is unable to promote the lock, then the in-memory
2371 ** cache will be left in an inconsistent state and so the error
2372 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2373 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2374 ** forces an automatic rollback of the changes.  See the
2375 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2376 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2377 ** this is important.
2378 **
2379 ** ^(There can only be a single busy handler defined for each
2380 ** [database connection].  Setting a new busy handler clears any
2381 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2382 ** will also set or clear the busy handler.
2383 **
2384 ** The busy callback should not take any actions which modify the
2385 ** database connection that invoked the busy handler.  Any such actions
2386 ** result in undefined behavior.
2387 **
2388 ** A busy handler must not close the database connection
2389 ** or [prepared statement] that invoked the busy handler.
2390 */
2391 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2392 
2393 /*
2394 ** CAPI3REF: Set A Busy Timeout
2395 **
2396 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2397 ** for a specified amount of time when a table is locked.  ^The handler
2398 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2399 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2400 ** the handler returns 0 which causes [sqlite3_step()] to return
2401 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2402 **
2403 ** ^Calling this routine with an argument less than or equal to zero
2404 ** turns off all busy handlers.
2405 **
2406 ** ^(There can only be a single busy handler for a particular
2407 ** [database connection] any any given moment.  If another busy handler
2408 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2409 ** this routine, that other busy handler is cleared.)^
2410 */
2411 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2412 
2413 /*
2414 ** CAPI3REF: Convenience Routines For Running Queries
2415 **
2416 ** This is a legacy interface that is preserved for backwards compatibility.
2417 ** Use of this interface is not recommended.
2418 **
2419 ** Definition: A <b>result table</b> is memory data structure created by the
2420 ** [sqlite3_get_table()] interface.  A result table records the
2421 ** complete query results from one or more queries.
2422 **
2423 ** The table conceptually has a number of rows and columns.  But
2424 ** these numbers are not part of the result table itself.  These
2425 ** numbers are obtained separately.  Let N be the number of rows
2426 ** and M be the number of columns.
2427 **
2428 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2429 ** There are (N+1)*M elements in the array.  The first M pointers point
2430 ** to zero-terminated strings that  contain the names of the columns.
2431 ** The remaining entries all point to query results.  NULL values result
2432 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2433 ** string representation as returned by [sqlite3_column_text()].
2434 **
2435 ** A result table might consist of one or more memory allocations.
2436 ** It is not safe to pass a result table directly to [sqlite3_free()].
2437 ** A result table should be deallocated using [sqlite3_free_table()].
2438 **
2439 ** ^(As an example of the result table format, suppose a query result
2440 ** is as follows:
2441 **
2442 ** <blockquote><pre>
2443 **        Name        | Age
2444 **        -----------------------
2445 **        Alice       | 43
2446 **        Bob         | 28
2447 **        Cindy       | 21
2448 ** </pre></blockquote>
2449 **
2450 ** There are two column (M==2) and three rows (N==3).  Thus the
2451 ** result table has 8 entries.  Suppose the result table is stored
2452 ** in an array names azResult.  Then azResult holds this content:
2453 **
2454 ** <blockquote><pre>
2455 **        azResult&#91;0] = "Name";
2456 **        azResult&#91;1] = "Age";
2457 **        azResult&#91;2] = "Alice";
2458 **        azResult&#91;3] = "43";
2459 **        azResult&#91;4] = "Bob";
2460 **        azResult&#91;5] = "28";
2461 **        azResult&#91;6] = "Cindy";
2462 **        azResult&#91;7] = "21";
2463 ** </pre></blockquote>)^
2464 **
2465 ** ^The sqlite3_get_table() function evaluates one or more
2466 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2467 ** string of its 2nd parameter and returns a result table to the
2468 ** pointer given in its 3rd parameter.
2469 **
2470 ** After the application has finished with the result from sqlite3_get_table(),
2471 ** it must pass the result table pointer to sqlite3_free_table() in order to
2472 ** release the memory that was malloced.  Because of the way the
2473 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2474 ** function must not try to call [sqlite3_free()] directly.  Only
2475 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2476 **
2477 ** The sqlite3_get_table() interface is implemented as a wrapper around
2478 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2479 ** to any internal data structures of SQLite.  It uses only the public
2480 ** interface defined here.  As a consequence, errors that occur in the
2481 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2482 ** reflected in subsequent calls to [sqlite3_errcode()] or
2483 ** [sqlite3_errmsg()].
2484 */
2485 SQLITE_API int sqlite3_get_table(
2486   sqlite3 *db,          /* An open database */
2487   const char *zSql,     /* SQL to be evaluated */
2488   char ***pazResult,    /* Results of the query */
2489   int *pnRow,           /* Number of result rows written here */
2490   int *pnColumn,        /* Number of result columns written here */
2491   char **pzErrmsg       /* Error msg written here */
2492 );
2493 SQLITE_API void sqlite3_free_table(char **result);
2494 
2495 /*
2496 ** CAPI3REF: Formatted String Printing Functions
2497 **
2498 ** These routines are work-alikes of the "printf()" family of functions
2499 ** from the standard C library.
2500 **
2501 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2502 ** results into memory obtained from [sqlite3_malloc()].
2503 ** The strings returned by these two routines should be
2504 ** released by [sqlite3_free()].  ^Both routines return a
2505 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2506 ** memory to hold the resulting string.
2507 **
2508 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2509 ** the standard C library.  The result is written into the
2510 ** buffer supplied as the second parameter whose size is given by
2511 ** the first parameter. Note that the order of the
2512 ** first two parameters is reversed from snprintf().)^  This is an
2513 ** historical accident that cannot be fixed without breaking
2514 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2515 ** returns a pointer to its buffer instead of the number of
2516 ** characters actually written into the buffer.)^  We admit that
2517 ** the number of characters written would be a more useful return
2518 ** value but we cannot change the implementation of sqlite3_snprintf()
2519 ** now without breaking compatibility.
2520 **
2521 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2522 ** guarantees that the buffer is always zero-terminated.  ^The first
2523 ** parameter "n" is the total size of the buffer, including space for
2524 ** the zero terminator.  So the longest string that can be completely
2525 ** written will be n-1 characters.
2526 **
2527 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2528 **
2529 ** These routines all implement some additional formatting
2530 ** options that are useful for constructing SQL statements.
2531 ** All of the usual printf() formatting options apply.  In addition, there
2532 ** is are "%q", "%Q", and "%z" options.
2533 **
2534 ** ^(The %q option works like %s in that it substitutes a null-terminated
2535 ** string from the argument list.  But %q also doubles every '\'' character.
2536 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2537 ** character it escapes that character and allows it to be inserted into
2538 ** the string.
2539 **
2540 ** For example, assume the string variable zText contains text as follows:
2541 **
2542 ** <blockquote><pre>
2543 **  char *zText = "It's a happy day!";
2544 ** </pre></blockquote>
2545 **
2546 ** One can use this text in an SQL statement as follows:
2547 **
2548 ** <blockquote><pre>
2549 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2550 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2551 **  sqlite3_free(zSQL);
2552 ** </pre></blockquote>
2553 **
2554 ** Because the %q format string is used, the '\'' character in zText
2555 ** is escaped and the SQL generated is as follows:
2556 **
2557 ** <blockquote><pre>
2558 **  INSERT INTO table1 VALUES('It''s a happy day!')
2559 ** </pre></blockquote>
2560 **
2561 ** This is correct.  Had we used %s instead of %q, the generated SQL
2562 ** would have looked like this:
2563 **
2564 ** <blockquote><pre>
2565 **  INSERT INTO table1 VALUES('It's a happy day!');
2566 ** </pre></blockquote>
2567 **
2568 ** This second example is an SQL syntax error.  As a general rule you should
2569 ** always use %q instead of %s when inserting text into a string literal.
2570 **
2571 ** ^(The %Q option works like %q except it also adds single quotes around
2572 ** the outside of the total string.  Additionally, if the parameter in the
2573 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2574 ** single quotes).)^  So, for example, one could say:
2575 **
2576 ** <blockquote><pre>
2577 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2578 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2579 **  sqlite3_free(zSQL);
2580 ** </pre></blockquote>
2581 **
2582 ** The code above will render a correct SQL statement in the zSQL
2583 ** variable even if the zText variable is a NULL pointer.
2584 **
2585 ** ^(The "%z" formatting option works like "%s" but with the
2586 ** addition that after the string has been read and copied into
2587 ** the result, [sqlite3_free()] is called on the input string.)^
2588 */
2589 SQLITE_API char *sqlite3_mprintf(const char*,...);
2590 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2591 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2592 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2593 
2594 /*
2595 ** CAPI3REF: Memory Allocation Subsystem
2596 **
2597 ** The SQLite core uses these three routines for all of its own
2598 ** internal memory allocation needs. "Core" in the previous sentence
2599 ** does not include operating-system specific VFS implementation.  The
2600 ** Windows VFS uses native malloc() and free() for some operations.
2601 **
2602 ** ^The sqlite3_malloc() routine returns a pointer to a block
2603 ** of memory at least N bytes in length, where N is the parameter.
2604 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2605 ** memory, it returns a NULL pointer.  ^If the parameter N to
2606 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2607 ** a NULL pointer.
2608 **
2609 ** ^Calling sqlite3_free() with a pointer previously returned
2610 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2611 ** that it might be reused.  ^The sqlite3_free() routine is
2612 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2613 ** to sqlite3_free() is harmless.  After being freed, memory
2614 ** should neither be read nor written.  Even reading previously freed
2615 ** memory might result in a segmentation fault or other severe error.
2616 ** Memory corruption, a segmentation fault, or other severe error
2617 ** might result if sqlite3_free() is called with a non-NULL pointer that
2618 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2619 **
2620 ** ^(The sqlite3_realloc() interface attempts to resize a
2621 ** prior memory allocation to be at least N bytes, where N is the
2622 ** second parameter.  The memory allocation to be resized is the first
2623 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2624 ** is a NULL pointer then its behavior is identical to calling
2625 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2626 ** ^If the second parameter to sqlite3_realloc() is zero or
2627 ** negative then the behavior is exactly the same as calling
2628 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2629 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2630 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2631 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2632 ** of the prior allocation are copied into the beginning of buffer returned
2633 ** by sqlite3_realloc() and the prior allocation is freed.
2634 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2635 ** is not freed.
2636 **
2637 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2638 ** is always aligned to at least an 8 byte boundary, or to a
2639 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2640 ** option is used.
2641 **
2642 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2643 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2644 ** implementation of these routines to be omitted.  That capability
2645 ** is no longer provided.  Only built-in memory allocators can be used.
2646 **
2647 ** The Windows OS interface layer calls
2648 ** the system malloc() and free() directly when converting
2649 ** filenames between the UTF-8 encoding used by SQLite
2650 ** and whatever filename encoding is used by the particular Windows
2651 ** installation.  Memory allocation errors are detected, but
2652 ** they are reported back as [SQLITE_CANTOPEN] or
2653 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2654 **
2655 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2656 ** must be either NULL or else pointers obtained from a prior
2657 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2658 ** not yet been released.
2659 **
2660 ** The application must not read or write any part of
2661 ** a block of memory after it has been released using
2662 ** [sqlite3_free()] or [sqlite3_realloc()].
2663 */
2664 SQLITE_API void *sqlite3_malloc(int);
2665 SQLITE_API void *sqlite3_realloc(void*, int);
2666 SQLITE_API void sqlite3_free(void*);
2667 
2668 /*
2669 ** CAPI3REF: Memory Allocator Statistics
2670 **
2671 ** SQLite provides these two interfaces for reporting on the status
2672 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2673 ** routines, which form the built-in memory allocation subsystem.
2674 **
2675 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2676 ** of memory currently outstanding (malloced but not freed).
2677 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2678 ** value of [sqlite3_memory_used()] since the high-water mark
2679 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2680 ** [sqlite3_memory_highwater()] include any overhead
2681 ** added by SQLite in its implementation of [sqlite3_malloc()],
2682 ** but not overhead added by the any underlying system library
2683 ** routines that [sqlite3_malloc()] may call.
2684 **
2685 ** ^The memory high-water mark is reset to the current value of
2686 ** [sqlite3_memory_used()] if and only if the parameter to
2687 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2688 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2689 ** prior to the reset.
2690 */
2691 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2692 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2693 
2694 /*
2695 ** CAPI3REF: Pseudo-Random Number Generator
2696 **
2697 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2698 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2699 ** already uses the largest possible [ROWID].  The PRNG is also used for
2700 ** the build-in random() and randomblob() SQL functions.  This interface allows
2701 ** applications to access the same PRNG for other purposes.
2702 **
2703 ** ^A call to this routine stores N bytes of randomness into buffer P.
2704 **
2705 ** ^The first time this routine is invoked (either internally or by
2706 ** the application) the PRNG is seeded using randomness obtained
2707 ** from the xRandomness method of the default [sqlite3_vfs] object.
2708 ** ^On all subsequent invocations, the pseudo-randomness is generated
2709 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2710 ** method.
2711 */
2712 SQLITE_API void sqlite3_randomness(int N, void *P);
2713 
2714 /*
2715 ** CAPI3REF: Compile-Time Authorization Callbacks
2716 **
2717 ** ^This routine registers an authorizer callback with a particular
2718 ** [database connection], supplied in the first argument.
2719 ** ^The authorizer callback is invoked as SQL statements are being compiled
2720 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2721 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2722 ** points during the compilation process, as logic is being created
2723 ** to perform various actions, the authorizer callback is invoked to
2724 ** see if those actions are allowed.  ^The authorizer callback should
2725 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2726 ** specific action but allow the SQL statement to continue to be
2727 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2728 ** rejected with an error.  ^If the authorizer callback returns
2729 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2730 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2731 ** the authorizer will fail with an error message.
2732 **
2733 ** When the callback returns [SQLITE_OK], that means the operation
2734 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2735 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2736 ** authorizer will fail with an error message explaining that
2737 ** access is denied.
2738 **
2739 ** ^The first parameter to the authorizer callback is a copy of the third
2740 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2741 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2742 ** the particular action to be authorized. ^The third through sixth parameters
2743 ** to the callback are zero-terminated strings that contain additional
2744 ** details about the action to be authorized.
2745 **
2746 ** ^If the action code is [SQLITE_READ]
2747 ** and the callback returns [SQLITE_IGNORE] then the
2748 ** [prepared statement] statement is constructed to substitute
2749 ** a NULL value in place of the table column that would have
2750 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2751 ** return can be used to deny an untrusted user access to individual
2752 ** columns of a table.
2753 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2754 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2755 ** [truncate optimization] is disabled and all rows are deleted individually.
2756 **
2757 ** An authorizer is used when [sqlite3_prepare | preparing]
2758 ** SQL statements from an untrusted source, to ensure that the SQL statements
2759 ** do not try to access data they are not allowed to see, or that they do not
2760 ** try to execute malicious statements that damage the database.  For
2761 ** example, an application may allow a user to enter arbitrary
2762 ** SQL queries for evaluation by a database.  But the application does
2763 ** not want the user to be able to make arbitrary changes to the
2764 ** database.  An authorizer could then be put in place while the
2765 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2766 ** disallows everything except [SELECT] statements.
2767 **
2768 ** Applications that need to process SQL from untrusted sources
2769 ** might also consider lowering resource limits using [sqlite3_limit()]
2770 ** and limiting database size using the [max_page_count] [PRAGMA]
2771 ** in addition to using an authorizer.
2772 **
2773 ** ^(Only a single authorizer can be in place on a database connection
2774 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2775 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2776 ** The authorizer is disabled by default.
2777 **
2778 ** The authorizer callback must not do anything that will modify
2779 ** the database connection that invoked the authorizer callback.
2780 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2781 ** database connections for the meaning of "modify" in this paragraph.
2782 **
2783 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2784 ** statement might be re-prepared during [sqlite3_step()] due to a
2785 ** schema change.  Hence, the application should ensure that the
2786 ** correct authorizer callback remains in place during the [sqlite3_step()].
2787 **
2788 ** ^Note that the authorizer callback is invoked only during
2789 ** [sqlite3_prepare()] or its variants.  Authorization is not
2790 ** performed during statement evaluation in [sqlite3_step()], unless
2791 ** as stated in the previous paragraph, sqlite3_step() invokes
2792 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2793 */
2794 SQLITE_API int sqlite3_set_authorizer(
2795   sqlite3*,
2796   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2797   void *pUserData
2798 );
2799 
2800 /*
2801 ** CAPI3REF: Authorizer Return Codes
2802 **
2803 ** The [sqlite3_set_authorizer | authorizer callback function] must
2804 ** return either [SQLITE_OK] or one of these two constants in order
2805 ** to signal SQLite whether or not the action is permitted.  See the
2806 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2807 ** information.
2808 **
2809 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2810 ** from the [sqlite3_vtab_on_conflict()] interface.
2811 */
2812 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2813 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2814 
2815 /*
2816 ** CAPI3REF: Authorizer Action Codes
2817 **
2818 ** The [sqlite3_set_authorizer()] interface registers a callback function
2819 ** that is invoked to authorize certain SQL statement actions.  The
2820 ** second parameter to the callback is an integer code that specifies
2821 ** what action is being authorized.  These are the integer action codes that
2822 ** the authorizer callback may be passed.
2823 **
2824 ** These action code values signify what kind of operation is to be
2825 ** authorized.  The 3rd and 4th parameters to the authorization
2826 ** callback function will be parameters or NULL depending on which of these
2827 ** codes is used as the second parameter.  ^(The 5th parameter to the
2828 ** authorizer callback is the name of the database ("main", "temp",
2829 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2830 ** is the name of the inner-most trigger or view that is responsible for
2831 ** the access attempt or NULL if this access attempt is directly from
2832 ** top-level SQL code.
2833 */
2834 /******************************************* 3rd ************ 4th ***********/
2835 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2836 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2837 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2838 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2839 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2840 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2841 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2842 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2843 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2844 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2845 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2846 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2847 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2848 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2849 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2850 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2851 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2852 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2853 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2854 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2855 #define SQLITE_SELECT               21   /* NULL            NULL            */
2856 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2857 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2858 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2859 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2860 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2861 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2862 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2863 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2864 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2865 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2866 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2867 #define SQLITE_COPY                  0   /* No longer used */
2868 
2869 /*
2870 ** CAPI3REF: Tracing And Profiling Functions
2871 **
2872 ** These routines register callback functions that can be used for
2873 ** tracing and profiling the execution of SQL statements.
2874 **
2875 ** ^The callback function registered by sqlite3_trace() is invoked at
2876 ** various times when an SQL statement is being run by [sqlite3_step()].
2877 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2878 ** SQL statement text as the statement first begins executing.
2879 ** ^(Additional sqlite3_trace() callbacks might occur
2880 ** as each triggered subprogram is entered.  The callbacks for triggers
2881 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2882 **
2883 ** ^The callback function registered by sqlite3_profile() is invoked
2884 ** as each SQL statement finishes.  ^The profile callback contains
2885 ** the original statement text and an estimate of wall-clock time
2886 ** of how long that statement took to run.  ^The profile callback
2887 ** time is in units of nanoseconds, however the current implementation
2888 ** is only capable of millisecond resolution so the six least significant
2889 ** digits in the time are meaningless.  Future versions of SQLite
2890 ** might provide greater resolution on the profiler callback.  The
2891 ** sqlite3_profile() function is considered experimental and is
2892 ** subject to change in future versions of SQLite.
2893 */
2894 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2895 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2896    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2897 
2898 /*
2899 ** CAPI3REF: Query Progress Callbacks
2900 **
2901 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2902 ** function X to be invoked periodically during long running calls to
2903 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2904 ** database connection D.  An example use for this
2905 ** interface is to keep a GUI updated during a large query.
2906 **
2907 ** ^The parameter P is passed through as the only parameter to the
2908 ** callback function X.  ^The parameter N is the number of
2909 ** [virtual machine instructions] that are evaluated between successive
2910 ** invocations of the callback X.
2911 **
2912 ** ^Only a single progress handler may be defined at one time per
2913 ** [database connection]; setting a new progress handler cancels the
2914 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2915 ** ^The progress handler is also disabled by setting N to a value less
2916 ** than 1.
2917 **
2918 ** ^If the progress callback returns non-zero, the operation is
2919 ** interrupted.  This feature can be used to implement a
2920 ** "Cancel" button on a GUI progress dialog box.
2921 **
2922 ** The progress handler callback must not do anything that will modify
2923 ** the database connection that invoked the progress handler.
2924 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2925 ** database connections for the meaning of "modify" in this paragraph.
2926 **
2927 */
2928 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2929 
2930 /*
2931 ** CAPI3REF: Opening A New Database Connection
2932 **
2933 ** ^These routines open an SQLite database file as specified by the
2934 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2935 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2936 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2937 ** returned in *ppDb, even if an error occurs.  The only exception is that
2938 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2939 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2940 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2941 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2942 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2943 ** an English language description of the error following a failure of any
2944 ** of the sqlite3_open() routines.
2945 **
2946 ** ^The default encoding for the database will be UTF-8 if
2947 ** sqlite3_open() or sqlite3_open_v2() is called and
2948 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2949 **
2950 ** Whether or not an error occurs when it is opened, resources
2951 ** associated with the [database connection] handle should be released by
2952 ** passing it to [sqlite3_close()] when it is no longer required.
2953 **
2954 ** The sqlite3_open_v2() interface works like sqlite3_open()
2955 ** except that it accepts two additional parameters for additional control
2956 ** over the new database connection.  ^(The flags parameter to
2957 ** sqlite3_open_v2() can take one of
2958 ** the following three values, optionally combined with the
2959 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2960 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2961 **
2962 ** <dl>
2963 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2964 ** <dd>The database is opened in read-only mode.  If the database does not
2965 ** already exist, an error is returned.</dd>)^
2966 **
2967 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2968 ** <dd>The database is opened for reading and writing if possible, or reading
2969 ** only if the file is write protected by the operating system.  In either
2970 ** case the database must already exist, otherwise an error is returned.</dd>)^
2971 **
2972 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2973 ** <dd>The database is opened for reading and writing, and is created if
2974 ** it does not already exist. This is the behavior that is always used for
2975 ** sqlite3_open() and sqlite3_open16().</dd>)^
2976 ** </dl>
2977 **
2978 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2979 ** combinations shown above optionally combined with other
2980 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2981 ** then the behavior is undefined.
2982 **
2983 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2984 ** opens in the multi-thread [threading mode] as long as the single-thread
2985 ** mode has not been set at compile-time or start-time.  ^If the
2986 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2987 ** in the serialized [threading mode] unless single-thread was
2988 ** previously selected at compile-time or start-time.
2989 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2990 ** eligible to use [shared cache mode], regardless of whether or not shared
2991 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2992 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2993 ** participate in [shared cache mode] even if it is enabled.
2994 **
2995 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2996 ** [sqlite3_vfs] object that defines the operating system interface that
2997 ** the new database connection should use.  ^If the fourth parameter is
2998 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2999 **
3000 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3001 ** is created for the connection.  ^This in-memory database will vanish when
3002 ** the database connection is closed.  Future versions of SQLite might
3003 ** make use of additional special filenames that begin with the ":" character.
3004 ** It is recommended that when a database filename actually does begin with
3005 ** a ":" character you should prefix the filename with a pathname such as
3006 ** "./" to avoid ambiguity.
3007 **
3008 ** ^If the filename is an empty string, then a private, temporary
3009 ** on-disk database will be created.  ^This private database will be
3010 ** automatically deleted as soon as the database connection is closed.
3011 **
3012 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3013 **
3014 ** ^If [URI filename] interpretation is enabled, and the filename argument
3015 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3016 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3017 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3018 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3019 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3020 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3021 ** by default, but future releases of SQLite might enable URI filename
3022 ** interpretation by default.  See "[URI filenames]" for additional
3023 ** information.
3024 **
3025 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3026 ** authority, then it must be either an empty string or the string
3027 ** "localhost". ^If the authority is not an empty string or "localhost", an
3028 ** error is returned to the caller. ^The fragment component of a URI, if
3029 ** present, is ignored.
3030 **
3031 ** ^SQLite uses the path component of the URI as the name of the disk file
3032 ** which contains the database. ^If the path begins with a '/' character,
3033 ** then it is interpreted as an absolute path. ^If the path does not begin
3034 ** with a '/' (meaning that the authority section is omitted from the URI)
3035 ** then the path is interpreted as a relative path.
3036 ** ^On windows, the first component of an absolute path
3037 ** is a drive specification (e.g. "C:").
3038 **
3039 ** [[core URI query parameters]]
3040 ** The query component of a URI may contain parameters that are interpreted
3041 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3042 ** SQLite interprets the following three query parameters:
3043 **
3044 ** <ul>
3045 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3046 **     a VFS object that provides the operating system interface that should
3047 **     be used to access the database file on disk. ^If this option is set to
3048 **     an empty string the default VFS object is used. ^Specifying an unknown
3049 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3050 **     present, then the VFS specified by the option takes precedence over
3051 **     the value passed as the fourth parameter to sqlite3_open_v2().
3052 **
3053 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3054 **     "rwc". Attempting to set it to any other value is an error)^.
3055 **     ^If "ro" is specified, then the database is opened for read-only
3056 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3057 **     third argument to sqlite3_prepare_v2(). ^If the mode option is set to
3058 **     "rw", then the database is opened for read-write (but not create)
3059 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3060 **     been set. ^Value "rwc" is equivalent to setting both
3061 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
3062 **     used, it is an error to specify a value for the mode parameter that is
3063 **     less restrictive than that specified by the flags passed as the third
3064 **     parameter.
3065 **
3066 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3067 **     "private". ^Setting it to "shared" is equivalent to setting the
3068 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3069 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3070 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3071 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3072 **     a URI filename, its value overrides any behaviour requested by setting
3073 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3074 ** </ul>
3075 **
3076 ** ^Specifying an unknown parameter in the query component of a URI is not an
3077 ** error.  Future versions of SQLite might understand additional query
3078 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3079 ** additional information.
3080 **
3081 ** [[URI filename examples]] <h3>URI filename examples</h3>
3082 **
3083 ** <table border="1" align=center cellpadding=5>
3084 ** <tr><th> URI filenames <th> Results
3085 ** <tr><td> file:data.db <td>
3086 **          Open the file "data.db" in the current directory.
3087 ** <tr><td> file:/home/fred/data.db<br>
3088 **          file:///home/fred/data.db <br>
3089 **          file://localhost/home/fred/data.db <br> <td>
3090 **          Open the database file "/home/fred/data.db".
3091 ** <tr><td> file://darkstar/home/fred/data.db <td>
3092 **          An error. "darkstar" is not a recognized authority.
3093 ** <tr><td style="white-space:nowrap">
3094 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3095 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3096 **          C:. Note that the %20 escaping in this example is not strictly
3097 **          necessary - space characters can be used literally
3098 **          in URI filenames.
3099 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3100 **          Open file "data.db" in the current directory for read-only access.
3101 **          Regardless of whether or not shared-cache mode is enabled by
3102 **          default, use a private cache.
3103 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3104 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3105 ** <tr><td> file:data.db?mode=readonly <td>
3106 **          An error. "readonly" is not a valid option for the "mode" parameter.
3107 ** </table>
3108 **
3109 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3110 ** query components of a URI. A hexadecimal escape sequence consists of a
3111 ** percent sign - "%" - followed by exactly two hexadecimal digits
3112 ** specifying an octet value. ^Before the path or query components of a
3113 ** URI filename are interpreted, they are encoded using UTF-8 and all
3114 ** hexadecimal escape sequences replaced by a single byte containing the
3115 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3116 ** the results are undefined.
3117 **
3118 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3119 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3120 ** codepage is currently defined.  Filenames containing international
3121 ** characters must be converted to UTF-8 prior to passing them into
3122 ** sqlite3_open() or sqlite3_open_v2().
3123 */
3124 SQLITE_API int sqlite3_open(
3125   const char *filename,   /* Database filename (UTF-8) */
3126   sqlite3 **ppDb          /* OUT: SQLite db handle */
3127 );
3128 SQLITE_API int sqlite3_open16(
3129   const void *filename,   /* Database filename (UTF-16) */
3130   sqlite3 **ppDb          /* OUT: SQLite db handle */
3131 );
3132 SQLITE_API int sqlite3_open_v2(
3133   const char *filename,   /* Database filename (UTF-8) */
3134   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3135   int flags,              /* Flags */
3136   const char *zVfs        /* Name of VFS module to use */
3137 );
3138 
3139 /*
3140 ** CAPI3REF: Obtain Values For URI Parameters
3141 **
3142 ** This is a utility routine, useful to VFS implementations, that checks
3143 ** to see if a database file was a URI that contained a specific query
3144 ** parameter, and if so obtains the value of the query parameter.
3145 **
3146 ** The zFilename argument is the filename pointer passed into the xOpen()
3147 ** method of a VFS implementation.  The zParam argument is the name of the
3148 ** query parameter we seek.  This routine returns the value of the zParam
3149 ** parameter if it exists.  If the parameter does not exist, this routine
3150 ** returns a NULL pointer.
3151 **
3152 ** If the zFilename argument to this function is not a pointer that SQLite
3153 ** passed into the xOpen VFS method, then the behavior of this routine
3154 ** is undefined and probably undesirable.
3155 */
3156 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3157 
3158 
3159 /*
3160 ** CAPI3REF: Error Codes And Messages
3161 **
3162 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3163 ** [extended result code] for the most recent failed sqlite3_* API call
3164 ** associated with a [database connection]. If a prior API call failed
3165 ** but the most recent API call succeeded, the return value from
3166 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3167 ** interface is the same except that it always returns the
3168 ** [extended result code] even when extended result codes are
3169 ** disabled.
3170 **
3171 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3172 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3173 ** ^(Memory to hold the error message string is managed internally.
3174 ** The application does not need to worry about freeing the result.
3175 ** However, the error string might be overwritten or deallocated by
3176 ** subsequent calls to other SQLite interface functions.)^
3177 **
3178 ** When the serialized [threading mode] is in use, it might be the
3179 ** case that a second error occurs on a separate thread in between
3180 ** the time of the first error and the call to these interfaces.
3181 ** When that happens, the second error will be reported since these
3182 ** interfaces always report the most recent result.  To avoid
3183 ** this, each thread can obtain exclusive use of the [database connection] D
3184 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3185 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3186 ** all calls to the interfaces listed here are completed.
3187 **
3188 ** If an interface fails with SQLITE_MISUSE, that means the interface
3189 ** was invoked incorrectly by the application.  In that case, the
3190 ** error code and message may or may not be set.
3191 */
3192 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3193 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3194 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3195 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3196 
3197 /*
3198 ** CAPI3REF: SQL Statement Object
3199 ** KEYWORDS: {prepared statement} {prepared statements}
3200 **
3201 ** An instance of this object represents a single SQL statement.
3202 ** This object is variously known as a "prepared statement" or a
3203 ** "compiled SQL statement" or simply as a "statement".
3204 **
3205 ** The life of a statement object goes something like this:
3206 **
3207 ** <ol>
3208 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3209 **      function.
3210 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3211 **      interfaces.
3212 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3213 ** <li> Reset the statement using [sqlite3_reset()] then go back
3214 **      to step 2.  Do this zero or more times.
3215 ** <li> Destroy the object using [sqlite3_finalize()].
3216 ** </ol>
3217 **
3218 ** Refer to documentation on individual methods above for additional
3219 ** information.
3220 */
3221 typedef struct sqlite3_stmt sqlite3_stmt;
3222 
3223 /*
3224 ** CAPI3REF: Run-time Limits
3225 **
3226 ** ^(This interface allows the size of various constructs to be limited
3227 ** on a connection by connection basis.  The first parameter is the
3228 ** [database connection] whose limit is to be set or queried.  The
3229 ** second parameter is one of the [limit categories] that define a
3230 ** class of constructs to be size limited.  The third parameter is the
3231 ** new limit for that construct.)^
3232 **
3233 ** ^If the new limit is a negative number, the limit is unchanged.
3234 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3235 ** [limits | hard upper bound]
3236 ** set at compile-time by a C preprocessor macro called
3237 ** [limits | SQLITE_MAX_<i>NAME</i>].
3238 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3239 ** ^Attempts to increase a limit above its hard upper bound are
3240 ** silently truncated to the hard upper bound.
3241 **
3242 ** ^Regardless of whether or not the limit was changed, the
3243 ** [sqlite3_limit()] interface returns the prior value of the limit.
3244 ** ^Hence, to find the current value of a limit without changing it,
3245 ** simply invoke this interface with the third parameter set to -1.
3246 **
3247 ** Run-time limits are intended for use in applications that manage
3248 ** both their own internal database and also databases that are controlled
3249 ** by untrusted external sources.  An example application might be a
3250 ** web browser that has its own databases for storing history and
3251 ** separate databases controlled by JavaScript applications downloaded
3252 ** off the Internet.  The internal databases can be given the
3253 ** large, default limits.  Databases managed by external sources can
3254 ** be given much smaller limits designed to prevent a denial of service
3255 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3256 ** interface to further control untrusted SQL.  The size of the database
3257 ** created by an untrusted script can be contained using the
3258 ** [max_page_count] [PRAGMA].
3259 **
3260 ** New run-time limit categories may be added in future releases.
3261 */
3262 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3263 
3264 /*
3265 ** CAPI3REF: Run-Time Limit Categories
3266 ** KEYWORDS: {limit category} {*limit categories}
3267 **
3268 ** These constants define various performance limits
3269 ** that can be lowered at run-time using [sqlite3_limit()].
3270 ** The synopsis of the meanings of the various limits is shown below.
3271 ** Additional information is available at [limits | Limits in SQLite].
3272 **
3273 ** <dl>
3274 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3275 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3276 **
3277 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3278 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3279 **
3280 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3281 ** <dd>The maximum number of columns in a table definition or in the
3282 ** result set of a [SELECT] or the maximum number of columns in an index
3283 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3284 **
3285 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3286 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3287 **
3288 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3289 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3290 **
3291 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3292 ** <dd>The maximum number of instructions in a virtual machine program
3293 ** used to implement an SQL statement.  This limit is not currently
3294 ** enforced, though that might be added in some future release of
3295 ** SQLite.</dd>)^
3296 **
3297 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3298 ** <dd>The maximum number of arguments on a function.</dd>)^
3299 **
3300 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3301 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3302 **
3303 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3304 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3305 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3306 ** [GLOB] operators.</dd>)^
3307 **
3308 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3309 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3310 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3311 **
3312 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3313 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3314 ** </dl>
3315 */
3316 #define SQLITE_LIMIT_LENGTH                    0
3317 #define SQLITE_LIMIT_SQL_LENGTH                1
3318 #define SQLITE_LIMIT_COLUMN                    2
3319 #define SQLITE_LIMIT_EXPR_DEPTH                3
3320 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3321 #define SQLITE_LIMIT_VDBE_OP                   5
3322 #define SQLITE_LIMIT_FUNCTION_ARG              6
3323 #define SQLITE_LIMIT_ATTACHED                  7
3324 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3325 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3326 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3327 
3328 /*
3329 ** CAPI3REF: Compiling An SQL Statement
3330 ** KEYWORDS: {SQL statement compiler}
3331 **
3332 ** To execute an SQL query, it must first be compiled into a byte-code
3333 ** program using one of these routines.
3334 **
3335 ** The first argument, "db", is a [database connection] obtained from a
3336 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3337 ** [sqlite3_open16()].  The database connection must not have been closed.
3338 **
3339 ** The second argument, "zSql", is the statement to be compiled, encoded
3340 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3341 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3342 ** use UTF-16.
3343 **
3344 ** ^If the nByte argument is less than zero, then zSql is read up to the
3345 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3346 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3347 ** zSql string ends at either the first '\000' or '\u0000' character or
3348 ** the nByte-th byte, whichever comes first. If the caller knows
3349 ** that the supplied string is nul-terminated, then there is a small
3350 ** performance advantage to be gained by passing an nByte parameter that
3351 ** is equal to the number of bytes in the input string <i>including</i>
3352 ** the nul-terminator bytes.
3353 **
3354 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3355 ** past the end of the first SQL statement in zSql.  These routines only
3356 ** compile the first statement in zSql, so *pzTail is left pointing to
3357 ** what remains uncompiled.
3358 **
3359 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3360 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3361 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3362 ** string or a comment) then *ppStmt is set to NULL.
3363 ** The calling procedure is responsible for deleting the compiled
3364 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3365 ** ppStmt may not be NULL.
3366 **
3367 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3368 ** otherwise an [error code] is returned.
3369 **
3370 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3371 ** recommended for all new programs. The two older interfaces are retained
3372 ** for backwards compatibility, but their use is discouraged.
3373 ** ^In the "v2" interfaces, the prepared statement
3374 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3375 ** original SQL text. This causes the [sqlite3_step()] interface to
3376 ** behave differently in three ways:
3377 **
3378 ** <ol>
3379 ** <li>
3380 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3381 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3382 ** statement and try to run it again.
3383 ** </li>
3384 **
3385 ** <li>
3386 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3387 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3388 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3389 ** and the application would have to make a second call to [sqlite3_reset()]
3390 ** in order to find the underlying cause of the problem. With the "v2" prepare
3391 ** interfaces, the underlying reason for the error is returned immediately.
3392 ** </li>
3393 **
3394 ** <li>
3395 ** ^If the specific value bound to [parameter | host parameter] in the
3396 ** WHERE clause might influence the choice of query plan for a statement,
3397 ** then the statement will be automatically recompiled, as if there had been
3398 ** a schema change, on the first  [sqlite3_step()] call following any change
3399 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3400 ** ^The specific value of WHERE-clause [parameter] might influence the
3401 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3402 ** or [GLOB] operator or if the parameter is compared to an indexed column
3403 ** and the [SQLITE_ENABLE_STAT2] compile-time option is enabled.
3404 ** the
3405 ** </li>
3406 ** </ol>
3407 */
3408 SQLITE_API int sqlite3_prepare(
3409   sqlite3 *db,            /* Database handle */
3410   const char *zSql,       /* SQL statement, UTF-8 encoded */
3411   int nByte,              /* Maximum length of zSql in bytes. */
3412   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3413   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3414 );
3415 SQLITE_API int sqlite3_prepare_v2(
3416   sqlite3 *db,            /* Database handle */
3417   const char *zSql,       /* SQL statement, UTF-8 encoded */
3418   int nByte,              /* Maximum length of zSql in bytes. */
3419   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3420   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3421 );
3422 SQLITE_API int sqlite3_prepare16(
3423   sqlite3 *db,            /* Database handle */
3424   const void *zSql,       /* SQL statement, UTF-16 encoded */
3425   int nByte,              /* Maximum length of zSql in bytes. */
3426   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3427   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3428 );
3429 SQLITE_API int sqlite3_prepare16_v2(
3430   sqlite3 *db,            /* Database handle */
3431   const void *zSql,       /* SQL statement, UTF-16 encoded */
3432   int nByte,              /* Maximum length of zSql in bytes. */
3433   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3434   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3435 );
3436 
3437 /*
3438 ** CAPI3REF: Retrieving Statement SQL
3439 **
3440 ** ^This interface can be used to retrieve a saved copy of the original
3441 ** SQL text used to create a [prepared statement] if that statement was
3442 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3443 */
3444 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3445 
3446 /*
3447 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3448 **
3449 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3450 ** and only if the [prepared statement] X makes no direct changes to
3451 ** the content of the database file.
3452 **
3453 ** Note that [application-defined SQL functions] or
3454 ** [virtual tables] might change the database indirectly as a side effect.
3455 ** ^(For example, if an application defines a function "eval()" that
3456 ** calls [sqlite3_exec()], then the following SQL statement would
3457 ** change the database file through side-effects:
3458 **
3459 ** <blockquote><pre>
3460 **    SELECT eval('DELETE FROM t1') FROM t2;
3461 ** </pre></blockquote>
3462 **
3463 ** But because the [SELECT] statement does not change the database file
3464 ** directly, sqlite3_stmt_readonly() would still return true.)^
3465 **
3466 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3467 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3468 ** since the statements themselves do not actually modify the database but
3469 ** rather they control the timing of when other statements modify the
3470 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3471 ** sqlite3_stmt_readonly() to return true since, while those statements
3472 ** change the configuration of a database connection, they do not make
3473 ** changes to the content of the database files on disk.
3474 */
3475 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3476 
3477 /*
3478 ** CAPI3REF: Dynamically Typed Value Object
3479 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3480 **
3481 ** SQLite uses the sqlite3_value object to represent all values
3482 ** that can be stored in a database table. SQLite uses dynamic typing
3483 ** for the values it stores.  ^Values stored in sqlite3_value objects
3484 ** can be integers, floating point values, strings, BLOBs, or NULL.
3485 **
3486 ** An sqlite3_value object may be either "protected" or "unprotected".
3487 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3488 ** will accept either a protected or an unprotected sqlite3_value.
3489 ** Every interface that accepts sqlite3_value arguments specifies
3490 ** whether or not it requires a protected sqlite3_value.
3491 **
3492 ** The terms "protected" and "unprotected" refer to whether or not
3493 ** a mutex is held.  An internal mutex is held for a protected
3494 ** sqlite3_value object but no mutex is held for an unprotected
3495 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3496 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3497 ** or if SQLite is run in one of reduced mutex modes
3498 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3499 ** then there is no distinction between protected and unprotected
3500 ** sqlite3_value objects and they can be used interchangeably.  However,
3501 ** for maximum code portability it is recommended that applications
3502 ** still make the distinction between protected and unprotected
3503 ** sqlite3_value objects even when not strictly required.
3504 **
3505 ** ^The sqlite3_value objects that are passed as parameters into the
3506 ** implementation of [application-defined SQL functions] are protected.
3507 ** ^The sqlite3_value object returned by
3508 ** [sqlite3_column_value()] is unprotected.
3509 ** Unprotected sqlite3_value objects may only be used with
3510 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3511 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3512 ** interfaces require protected sqlite3_value objects.
3513 */
3514 typedef struct Mem sqlite3_value;
3515 
3516 /*
3517 ** CAPI3REF: SQL Function Context Object
3518 **
3519 ** The context in which an SQL function executes is stored in an
3520 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3521 ** is always first parameter to [application-defined SQL functions].
3522 ** The application-defined SQL function implementation will pass this
3523 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3524 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3525 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3526 ** and/or [sqlite3_set_auxdata()].
3527 */
3528 typedef struct sqlite3_context sqlite3_context;
3529 
3530 /*
3531 ** CAPI3REF: Binding Values To Prepared Statements
3532 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3533 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3534 **
3535 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3536 ** literals may be replaced by a [parameter] that matches one of following
3537 ** templates:
3538 **
3539 ** <ul>
3540 ** <li>  ?
3541 ** <li>  ?NNN
3542 ** <li>  :VVV
3543 ** <li>  @VVV
3544 ** <li>  $VVV
3545 ** </ul>
3546 **
3547 ** In the templates above, NNN represents an integer literal,
3548 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3549 ** parameters (also called "host parameter names" or "SQL parameters")
3550 ** can be set using the sqlite3_bind_*() routines defined here.
3551 **
3552 ** ^The first argument to the sqlite3_bind_*() routines is always
3553 ** a pointer to the [sqlite3_stmt] object returned from
3554 ** [sqlite3_prepare_v2()] or its variants.
3555 **
3556 ** ^The second argument is the index of the SQL parameter to be set.
3557 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3558 ** SQL parameter is used more than once, second and subsequent
3559 ** occurrences have the same index as the first occurrence.
3560 ** ^The index for named parameters can be looked up using the
3561 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3562 ** for "?NNN" parameters is the value of NNN.
3563 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3564 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3565 **
3566 ** ^The third argument is the value to bind to the parameter.
3567 **
3568 ** ^(In those routines that have a fourth argument, its value is the
3569 ** number of bytes in the parameter.  To be clear: the value is the
3570 ** number of <u>bytes</u> in the value, not the number of characters.)^
3571 ** ^If the fourth parameter is negative, the length of the string is
3572 ** the number of bytes up to the first zero terminator.
3573 **
3574 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3575 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3576 ** string after SQLite has finished with it.  ^The destructor is called
3577 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3578 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3579 ** ^If the fifth argument is
3580 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3581 ** information is in static, unmanaged space and does not need to be freed.
3582 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3583 ** SQLite makes its own private copy of the data immediately, before
3584 ** the sqlite3_bind_*() routine returns.
3585 **
3586 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3587 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3588 ** (just an integer to hold its size) while it is being processed.
3589 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3590 ** content is later written using
3591 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3592 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3593 **
3594 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3595 ** for the [prepared statement] or with a prepared statement for which
3596 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3597 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3598 ** routine is passed a [prepared statement] that has been finalized, the
3599 ** result is undefined and probably harmful.
3600 **
3601 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3602 ** ^Unbound parameters are interpreted as NULL.
3603 **
3604 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3605 ** [error code] if anything goes wrong.
3606 ** ^[SQLITE_RANGE] is returned if the parameter
3607 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3608 **
3609 ** See also: [sqlite3_bind_parameter_count()],
3610 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3611 */
3612 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3613 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3614 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3615 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3616 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3617 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3618 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3619 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3620 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3621 
3622 /*
3623 ** CAPI3REF: Number Of SQL Parameters
3624 **
3625 ** ^This routine can be used to find the number of [SQL parameters]
3626 ** in a [prepared statement].  SQL parameters are tokens of the
3627 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3628 ** placeholders for values that are [sqlite3_bind_blob | bound]
3629 ** to the parameters at a later time.
3630 **
3631 ** ^(This routine actually returns the index of the largest (rightmost)
3632 ** parameter. For all forms except ?NNN, this will correspond to the
3633 ** number of unique parameters.  If parameters of the ?NNN form are used,
3634 ** there may be gaps in the list.)^
3635 **
3636 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3637 ** [sqlite3_bind_parameter_name()], and
3638 ** [sqlite3_bind_parameter_index()].
3639 */
3640 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3641 
3642 /*
3643 ** CAPI3REF: Name Of A Host Parameter
3644 **
3645 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3646 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3647 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3648 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3649 ** respectively.
3650 ** In other words, the initial ":" or "$" or "@" or "?"
3651 ** is included as part of the name.)^
3652 ** ^Parameters of the form "?" without a following integer have no name
3653 ** and are referred to as "nameless" or "anonymous parameters".
3654 **
3655 ** ^The first host parameter has an index of 1, not 0.
3656 **
3657 ** ^If the value N is out of range or if the N-th parameter is
3658 ** nameless, then NULL is returned.  ^The returned string is
3659 ** always in UTF-8 encoding even if the named parameter was
3660 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3661 ** [sqlite3_prepare16_v2()].
3662 **
3663 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3664 ** [sqlite3_bind_parameter_count()], and
3665 ** [sqlite3_bind_parameter_index()].
3666 */
3667 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3668 
3669 /*
3670 ** CAPI3REF: Index Of A Parameter With A Given Name
3671 **
3672 ** ^Return the index of an SQL parameter given its name.  ^The
3673 ** index value returned is suitable for use as the second
3674 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3675 ** is returned if no matching parameter is found.  ^The parameter
3676 ** name must be given in UTF-8 even if the original statement
3677 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3678 **
3679 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3680 ** [sqlite3_bind_parameter_count()], and
3681 ** [sqlite3_bind_parameter_index()].
3682 */
3683 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3684 
3685 /*
3686 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3687 **
3688 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3689 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3690 ** ^Use this routine to reset all host parameters to NULL.
3691 */
3692 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3693 
3694 /*
3695 ** CAPI3REF: Number Of Columns In A Result Set
3696 **
3697 ** ^Return the number of columns in the result set returned by the
3698 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3699 ** statement that does not return data (for example an [UPDATE]).
3700 **
3701 ** See also: [sqlite3_data_count()]
3702 */
3703 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3704 
3705 /*
3706 ** CAPI3REF: Column Names In A Result Set
3707 **
3708 ** ^These routines return the name assigned to a particular column
3709 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3710 ** interface returns a pointer to a zero-terminated UTF-8 string
3711 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3712 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3713 ** that implements the [SELECT] statement. ^The second parameter is the
3714 ** column number.  ^The leftmost column is number 0.
3715 **
3716 ** ^The returned string pointer is valid until either the [prepared statement]
3717 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3718 ** reprepared by the first call to [sqlite3_step()] for a particular run
3719 ** or until the next call to
3720 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3721 **
3722 ** ^If sqlite3_malloc() fails during the processing of either routine
3723 ** (for example during a conversion from UTF-8 to UTF-16) then a
3724 ** NULL pointer is returned.
3725 **
3726 ** ^The name of a result column is the value of the "AS" clause for
3727 ** that column, if there is an AS clause.  If there is no AS clause
3728 ** then the name of the column is unspecified and may change from
3729 ** one release of SQLite to the next.
3730 */
3731 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3732 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3733 
3734 /*
3735 ** CAPI3REF: Source Of Data In A Query Result
3736 **
3737 ** ^These routines provide a means to determine the database, table, and
3738 ** table column that is the origin of a particular result column in
3739 ** [SELECT] statement.
3740 ** ^The name of the database or table or column can be returned as
3741 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3742 ** the database name, the _table_ routines return the table name, and
3743 ** the origin_ routines return the column name.
3744 ** ^The returned string is valid until the [prepared statement] is destroyed
3745 ** using [sqlite3_finalize()] or until the statement is automatically
3746 ** reprepared by the first call to [sqlite3_step()] for a particular run
3747 ** or until the same information is requested
3748 ** again in a different encoding.
3749 **
3750 ** ^The names returned are the original un-aliased names of the
3751 ** database, table, and column.
3752 **
3753 ** ^The first argument to these interfaces is a [prepared statement].
3754 ** ^These functions return information about the Nth result column returned by
3755 ** the statement, where N is the second function argument.
3756 ** ^The left-most column is column 0 for these routines.
3757 **
3758 ** ^If the Nth column returned by the statement is an expression or
3759 ** subquery and is not a column value, then all of these functions return
3760 ** NULL.  ^These routine might also return NULL if a memory allocation error
3761 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3762 ** or column that query result column was extracted from.
3763 **
3764 ** ^As with all other SQLite APIs, those whose names end with "16" return
3765 ** UTF-16 encoded strings and the other functions return UTF-8.
3766 **
3767 ** ^These APIs are only available if the library was compiled with the
3768 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3769 **
3770 ** If two or more threads call one or more of these routines against the same
3771 ** prepared statement and column at the same time then the results are
3772 ** undefined.
3773 **
3774 ** If two or more threads call one or more
3775 ** [sqlite3_column_database_name | column metadata interfaces]
3776 ** for the same [prepared statement] and result column
3777 ** at the same time then the results are undefined.
3778 */
3779 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3780 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3781 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3782 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3783 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3784 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3785 
3786 /*
3787 ** CAPI3REF: Declared Datatype Of A Query Result
3788 **
3789 ** ^(The first parameter is a [prepared statement].
3790 ** If this statement is a [SELECT] statement and the Nth column of the
3791 ** returned result set of that [SELECT] is a table column (not an
3792 ** expression or subquery) then the declared type of the table
3793 ** column is returned.)^  ^If the Nth column of the result set is an
3794 ** expression or subquery, then a NULL pointer is returned.
3795 ** ^The returned string is always UTF-8 encoded.
3796 **
3797 ** ^(For example, given the database schema:
3798 **
3799 ** CREATE TABLE t1(c1 VARIANT);
3800 **
3801 ** and the following statement to be compiled:
3802 **
3803 ** SELECT c1 + 1, c1 FROM t1;
3804 **
3805 ** this routine would return the string "VARIANT" for the second result
3806 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3807 **
3808 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3809 ** is declared to contain a particular type does not mean that the
3810 ** data stored in that column is of the declared type.  SQLite is
3811 ** strongly typed, but the typing is dynamic not static.  ^Type
3812 ** is associated with individual values, not with the containers
3813 ** used to hold those values.
3814 */
3815 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3816 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3817 
3818 /*
3819 ** CAPI3REF: Evaluate An SQL Statement
3820 **
3821 ** After a [prepared statement] has been prepared using either
3822 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3823 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3824 ** must be called one or more times to evaluate the statement.
3825 **
3826 ** The details of the behavior of the sqlite3_step() interface depend
3827 ** on whether the statement was prepared using the newer "v2" interface
3828 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3829 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3830 ** new "v2" interface is recommended for new applications but the legacy
3831 ** interface will continue to be supported.
3832 **
3833 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3834 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3835 ** ^With the "v2" interface, any of the other [result codes] or
3836 ** [extended result codes] might be returned as well.
3837 **
3838 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3839 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3840 ** or occurs outside of an explicit transaction, then you can retry the
3841 ** statement.  If the statement is not a [COMMIT] and occurs within an
3842 ** explicit transaction then you should rollback the transaction before
3843 ** continuing.
3844 **
3845 ** ^[SQLITE_DONE] means that the statement has finished executing
3846 ** successfully.  sqlite3_step() should not be called again on this virtual
3847 ** machine without first calling [sqlite3_reset()] to reset the virtual
3848 ** machine back to its initial state.
3849 **
3850 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3851 ** is returned each time a new row of data is ready for processing by the
3852 ** caller. The values may be accessed using the [column access functions].
3853 ** sqlite3_step() is called again to retrieve the next row of data.
3854 **
3855 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3856 ** violation) has occurred.  sqlite3_step() should not be called again on
3857 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3858 ** ^With the legacy interface, a more specific error code (for example,
3859 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3860 ** can be obtained by calling [sqlite3_reset()] on the
3861 ** [prepared statement].  ^In the "v2" interface,
3862 ** the more specific error code is returned directly by sqlite3_step().
3863 **
3864 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3865 ** Perhaps it was called on a [prepared statement] that has
3866 ** already been [sqlite3_finalize | finalized] or on one that had
3867 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3868 ** be the case that the same database connection is being used by two or
3869 ** more threads at the same moment in time.
3870 **
3871 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3872 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3873 ** other than [SQLITE_ROW] before any subsequent invocation of
3874 ** sqlite3_step().  Failure to reset the prepared statement using
3875 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3876 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3877 ** calling [sqlite3_reset()] automatically in this circumstance rather
3878 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3879 ** break because any application that ever receives an SQLITE_MISUSE error
3880 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3881 ** can be used to restore the legacy behavior.
3882 **
3883 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3884 ** API always returns a generic error code, [SQLITE_ERROR], following any
3885 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3886 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3887 ** specific [error codes] that better describes the error.
3888 ** We admit that this is a goofy design.  The problem has been fixed
3889 ** with the "v2" interface.  If you prepare all of your SQL statements
3890 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3891 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3892 ** then the more specific [error codes] are returned directly
3893 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3894 */
3895 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3896 
3897 /*
3898 ** CAPI3REF: Number of columns in a result set
3899 **
3900 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
3901 ** current row of the result set of [prepared statement] P.
3902 ** ^If prepared statement P does not have results ready to return
3903 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
3904 ** interfaces) then sqlite3_data_count(P) returns 0.
3905 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
3906 **
3907 ** See also: [sqlite3_column_count()]
3908 */
3909 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3910 
3911 /*
3912 ** CAPI3REF: Fundamental Datatypes
3913 ** KEYWORDS: SQLITE_TEXT
3914 **
3915 ** ^(Every value in SQLite has one of five fundamental datatypes:
3916 **
3917 ** <ul>
3918 ** <li> 64-bit signed integer
3919 ** <li> 64-bit IEEE floating point number
3920 ** <li> string
3921 ** <li> BLOB
3922 ** <li> NULL
3923 ** </ul>)^
3924 **
3925 ** These constants are codes for each of those types.
3926 **
3927 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3928 ** for a completely different meaning.  Software that links against both
3929 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3930 ** SQLITE_TEXT.
3931 */
3932 #define SQLITE_INTEGER  1
3933 #define SQLITE_FLOAT    2
3934 #define SQLITE_BLOB     4
3935 #define SQLITE_NULL     5
3936 #ifdef SQLITE_TEXT
3937 # undef SQLITE_TEXT
3938 #else
3939 # define SQLITE_TEXT     3
3940 #endif
3941 #define SQLITE3_TEXT     3
3942 
3943 /*
3944 ** CAPI3REF: Result Values From A Query
3945 ** KEYWORDS: {column access functions}
3946 **
3947 ** These routines form the "result set" interface.
3948 **
3949 ** ^These routines return information about a single column of the current
3950 ** result row of a query.  ^In every case the first argument is a pointer
3951 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3952 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3953 ** and the second argument is the index of the column for which information
3954 ** should be returned. ^The leftmost column of the result set has the index 0.
3955 ** ^The number of columns in the result can be determined using
3956 ** [sqlite3_column_count()].
3957 **
3958 ** If the SQL statement does not currently point to a valid row, or if the
3959 ** column index is out of range, the result is undefined.
3960 ** These routines may only be called when the most recent call to
3961 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3962 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3963 ** If any of these routines are called after [sqlite3_reset()] or
3964 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3965 ** something other than [SQLITE_ROW], the results are undefined.
3966 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3967 ** are called from a different thread while any of these routines
3968 ** are pending, then the results are undefined.
3969 **
3970 ** ^The sqlite3_column_type() routine returns the
3971 ** [SQLITE_INTEGER | datatype code] for the initial data type
3972 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3973 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3974 ** returned by sqlite3_column_type() is only meaningful if no type
3975 ** conversions have occurred as described below.  After a type conversion,
3976 ** the value returned by sqlite3_column_type() is undefined.  Future
3977 ** versions of SQLite may change the behavior of sqlite3_column_type()
3978 ** following a type conversion.
3979 **
3980 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3981 ** routine returns the number of bytes in that BLOB or string.
3982 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3983 ** the string to UTF-8 and then returns the number of bytes.
3984 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3985 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3986 ** the number of bytes in that string.
3987 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
3988 **
3989 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
3990 ** routine returns the number of bytes in that BLOB or string.
3991 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
3992 ** the string to UTF-16 and then returns the number of bytes.
3993 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
3994 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
3995 ** the number of bytes in that string.
3996 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
3997 **
3998 ** ^The values returned by [sqlite3_column_bytes()] and
3999 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4000 ** of the string.  ^For clarity: the values returned by
4001 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4002 ** bytes in the string, not the number of characters.
4003 **
4004 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4005 ** even empty strings, are always zero terminated.  ^The return
4006 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4007 **
4008 ** ^The object returned by [sqlite3_column_value()] is an
4009 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4010 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4011 ** If the [unprotected sqlite3_value] object returned by
4012 ** [sqlite3_column_value()] is used in any other way, including calls
4013 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4014 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4015 **
4016 ** These routines attempt to convert the value where appropriate.  ^For
4017 ** example, if the internal representation is FLOAT and a text result
4018 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4019 ** conversion automatically.  ^(The following table details the conversions
4020 ** that are applied:
4021 **
4022 ** <blockquote>
4023 ** <table border="1">
4024 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4025 **
4026 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4027 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4028 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4029 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4030 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4031 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4032 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4033 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4034 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4035 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4036 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4037 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4038 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4039 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4040 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4041 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4042 ** </table>
4043 ** </blockquote>)^
4044 **
4045 ** The table above makes reference to standard C library functions atoi()
4046 ** and atof().  SQLite does not really use these functions.  It has its
4047 ** own equivalent internal routines.  The atoi() and atof() names are
4048 ** used in the table for brevity and because they are familiar to most
4049 ** C programmers.
4050 **
4051 ** Note that when type conversions occur, pointers returned by prior
4052 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4053 ** sqlite3_column_text16() may be invalidated.
4054 ** Type conversions and pointer invalidations might occur
4055 ** in the following cases:
4056 **
4057 ** <ul>
4058 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4059 **      sqlite3_column_text16() is called.  A zero-terminator might
4060 **      need to be added to the string.</li>
4061 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4062 **      sqlite3_column_text16() is called.  The content must be converted
4063 **      to UTF-16.</li>
4064 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4065 **      sqlite3_column_text() is called.  The content must be converted
4066 **      to UTF-8.</li>
4067 ** </ul>
4068 **
4069 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4070 ** not invalidate a prior pointer, though of course the content of the buffer
4071 ** that the prior pointer references will have been modified.  Other kinds
4072 ** of conversion are done in place when it is possible, but sometimes they
4073 ** are not possible and in those cases prior pointers are invalidated.
4074 **
4075 ** The safest and easiest to remember policy is to invoke these routines
4076 ** in one of the following ways:
4077 **
4078 ** <ul>
4079 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4080 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4081 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4082 ** </ul>
4083 **
4084 ** In other words, you should call sqlite3_column_text(),
4085 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4086 ** into the desired format, then invoke sqlite3_column_bytes() or
4087 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4088 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4089 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4090 ** with calls to sqlite3_column_bytes().
4091 **
4092 ** ^The pointers returned are valid until a type conversion occurs as
4093 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4094 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4095 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4096 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4097 ** [sqlite3_free()].
4098 **
4099 ** ^(If a memory allocation error occurs during the evaluation of any
4100 ** of these routines, a default value is returned.  The default value
4101 ** is either the integer 0, the floating point number 0.0, or a NULL
4102 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4103 ** [SQLITE_NOMEM].)^
4104 */
4105 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4106 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4107 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4108 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4109 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4110 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4111 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4112 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4113 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4114 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4115 
4116 /*
4117 ** CAPI3REF: Destroy A Prepared Statement Object
4118 **
4119 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4120 ** ^If the most recent evaluation of the statement encountered no errors
4121 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4122 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4123 ** sqlite3_finalize(S) returns the appropriate [error code] or
4124 ** [extended error code].
4125 **
4126 ** ^The sqlite3_finalize(S) routine can be called at any point during
4127 ** the life cycle of [prepared statement] S:
4128 ** before statement S is ever evaluated, after
4129 ** one or more calls to [sqlite3_reset()], or after any call
4130 ** to [sqlite3_step()] regardless of whether or not the statement has
4131 ** completed execution.
4132 **
4133 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4134 **
4135 ** The application must finalize every [prepared statement] in order to avoid
4136 ** resource leaks.  It is a grievous error for the application to try to use
4137 ** a prepared statement after it has been finalized.  Any use of a prepared
4138 ** statement after it has been finalized can result in undefined and
4139 ** undesirable behavior such as segfaults and heap corruption.
4140 */
4141 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4142 
4143 /*
4144 ** CAPI3REF: Reset A Prepared Statement Object
4145 **
4146 ** The sqlite3_reset() function is called to reset a [prepared statement]
4147 ** object back to its initial state, ready to be re-executed.
4148 ** ^Any SQL statement variables that had values bound to them using
4149 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4150 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4151 **
4152 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4153 ** back to the beginning of its program.
4154 **
4155 ** ^If the most recent call to [sqlite3_step(S)] for the
4156 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4157 ** or if [sqlite3_step(S)] has never before been called on S,
4158 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4159 **
4160 ** ^If the most recent call to [sqlite3_step(S)] for the
4161 ** [prepared statement] S indicated an error, then
4162 ** [sqlite3_reset(S)] returns an appropriate [error code].
4163 **
4164 ** ^The [sqlite3_reset(S)] interface does not change the values
4165 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4166 */
4167 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4168 
4169 /*
4170 ** CAPI3REF: Create Or Redefine SQL Functions
4171 ** KEYWORDS: {function creation routines}
4172 ** KEYWORDS: {application-defined SQL function}
4173 ** KEYWORDS: {application-defined SQL functions}
4174 **
4175 ** ^These functions (collectively known as "function creation routines")
4176 ** are used to add SQL functions or aggregates or to redefine the behavior
4177 ** of existing SQL functions or aggregates.  The only differences between
4178 ** these routines are the text encoding expected for
4179 ** the second parameter (the name of the function being created)
4180 ** and the presence or absence of a destructor callback for
4181 ** the application data pointer.
4182 **
4183 ** ^The first parameter is the [database connection] to which the SQL
4184 ** function is to be added.  ^If an application uses more than one database
4185 ** connection then application-defined SQL functions must be added
4186 ** to each database connection separately.
4187 **
4188 ** ^The second parameter is the name of the SQL function to be created or
4189 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4190 ** representation, exclusive of the zero-terminator.  ^Note that the name
4191 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4192 ** ^Any attempt to create a function with a longer name
4193 ** will result in [SQLITE_MISUSE] being returned.
4194 **
4195 ** ^The third parameter (nArg)
4196 ** is the number of arguments that the SQL function or
4197 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4198 ** aggregate may take any number of arguments between 0 and the limit
4199 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4200 ** parameter is less than -1 or greater than 127 then the behavior is
4201 ** undefined.
4202 **
4203 ** ^The fourth parameter, eTextRep, specifies what
4204 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4205 ** its parameters.  Every SQL function implementation must be able to work
4206 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4207 ** more efficient with one encoding than another.  ^An application may
4208 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4209 ** times with the same function but with different values of eTextRep.
4210 ** ^When multiple implementations of the same function are available, SQLite
4211 ** will pick the one that involves the least amount of data conversion.
4212 ** If there is only a single implementation which does not care what text
4213 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4214 **
4215 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4216 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4217 **
4218 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4219 ** pointers to C-language functions that implement the SQL function or
4220 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4221 ** callback only; NULL pointers must be passed as the xStep and xFinal
4222 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4223 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4224 ** SQL function or aggregate, pass NULL pointers for all three function
4225 ** callbacks.
4226 **
4227 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4228 ** then it is destructor for the application data pointer.
4229 ** The destructor is invoked when the function is deleted, either by being
4230 ** overloaded or when the database connection closes.)^
4231 ** ^The destructor is also invoked if the call to
4232 ** sqlite3_create_function_v2() fails.
4233 ** ^When the destructor callback of the tenth parameter is invoked, it
4234 ** is passed a single argument which is a copy of the application data
4235 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4236 **
4237 ** ^It is permitted to register multiple implementations of the same
4238 ** functions with the same name but with either differing numbers of
4239 ** arguments or differing preferred text encodings.  ^SQLite will use
4240 ** the implementation that most closely matches the way in which the
4241 ** SQL function is used.  ^A function implementation with a non-negative
4242 ** nArg parameter is a better match than a function implementation with
4243 ** a negative nArg.  ^A function where the preferred text encoding
4244 ** matches the database encoding is a better
4245 ** match than a function where the encoding is different.
4246 ** ^A function where the encoding difference is between UTF16le and UTF16be
4247 ** is a closer match than a function where the encoding difference is
4248 ** between UTF8 and UTF16.
4249 **
4250 ** ^Built-in functions may be overloaded by new application-defined functions.
4251 **
4252 ** ^An application-defined function is permitted to call other
4253 ** SQLite interfaces.  However, such calls must not
4254 ** close the database connection nor finalize or reset the prepared
4255 ** statement in which the function is running.
4256 */
4257 SQLITE_API int sqlite3_create_function(
4258   sqlite3 *db,
4259   const char *zFunctionName,
4260   int nArg,
4261   int eTextRep,
4262   void *pApp,
4263   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4264   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4265   void (*xFinal)(sqlite3_context*)
4266 );
4267 SQLITE_API int sqlite3_create_function16(
4268   sqlite3 *db,
4269   const void *zFunctionName,
4270   int nArg,
4271   int eTextRep,
4272   void *pApp,
4273   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4274   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4275   void (*xFinal)(sqlite3_context*)
4276 );
4277 SQLITE_API int sqlite3_create_function_v2(
4278   sqlite3 *db,
4279   const char *zFunctionName,
4280   int nArg,
4281   int eTextRep,
4282   void *pApp,
4283   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4284   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4285   void (*xFinal)(sqlite3_context*),
4286   void(*xDestroy)(void*)
4287 );
4288 
4289 /*
4290 ** CAPI3REF: Text Encodings
4291 **
4292 ** These constant define integer codes that represent the various
4293 ** text encodings supported by SQLite.
4294 */
4295 #define SQLITE_UTF8           1
4296 #define SQLITE_UTF16LE        2
4297 #define SQLITE_UTF16BE        3
4298 #define SQLITE_UTF16          4    /* Use native byte order */
4299 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4300 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4301 
4302 /*
4303 ** CAPI3REF: Deprecated Functions
4304 ** DEPRECATED
4305 **
4306 ** These functions are [deprecated].  In order to maintain
4307 ** backwards compatibility with older code, these functions continue
4308 ** to be supported.  However, new applications should avoid
4309 ** the use of these functions.  To help encourage people to avoid
4310 ** using these functions, we are not going to tell you what they do.
4311 */
4312 #ifndef SQLITE_OMIT_DEPRECATED
4313 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4314 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4315 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4316 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4317 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4318 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4319 #endif
4320 
4321 /*
4322 ** CAPI3REF: Obtaining SQL Function Parameter Values
4323 **
4324 ** The C-language implementation of SQL functions and aggregates uses
4325 ** this set of interface routines to access the parameter values on
4326 ** the function or aggregate.
4327 **
4328 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4329 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4330 ** define callbacks that implement the SQL functions and aggregates.
4331 ** The 3rd parameter to these callbacks is an array of pointers to
4332 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4333 ** each parameter to the SQL function.  These routines are used to
4334 ** extract values from the [sqlite3_value] objects.
4335 **
4336 ** These routines work only with [protected sqlite3_value] objects.
4337 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4338 ** object results in undefined behavior.
4339 **
4340 ** ^These routines work just like the corresponding [column access functions]
4341 ** except that  these routines take a single [protected sqlite3_value] object
4342 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4343 **
4344 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4345 ** in the native byte-order of the host machine.  ^The
4346 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4347 ** extract UTF-16 strings as big-endian and little-endian respectively.
4348 **
4349 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4350 ** numeric affinity to the value.  This means that an attempt is
4351 ** made to convert the value to an integer or floating point.  If
4352 ** such a conversion is possible without loss of information (in other
4353 ** words, if the value is a string that looks like a number)
4354 ** then the conversion is performed.  Otherwise no conversion occurs.
4355 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4356 **
4357 ** Please pay particular attention to the fact that the pointer returned
4358 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4359 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4360 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4361 ** or [sqlite3_value_text16()].
4362 **
4363 ** These routines must be called from the same thread as
4364 ** the SQL function that supplied the [sqlite3_value*] parameters.
4365 */
4366 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4367 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4368 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4369 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4370 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4371 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4372 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4373 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4374 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4375 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4376 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4377 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4378 
4379 /*
4380 ** CAPI3REF: Obtain Aggregate Function Context
4381 **
4382 ** Implementations of aggregate SQL functions use this
4383 ** routine to allocate memory for storing their state.
4384 **
4385 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4386 ** for a particular aggregate function, SQLite
4387 ** allocates N of memory, zeroes out that memory, and returns a pointer
4388 ** to the new memory. ^On second and subsequent calls to
4389 ** sqlite3_aggregate_context() for the same aggregate function instance,
4390 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4391 ** called once for each invocation of the xStep callback and then one
4392 ** last time when the xFinal callback is invoked.  ^(When no rows match
4393 ** an aggregate query, the xStep() callback of the aggregate function
4394 ** implementation is never called and xFinal() is called exactly once.
4395 ** In those cases, sqlite3_aggregate_context() might be called for the
4396 ** first time from within xFinal().)^
4397 **
4398 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4399 ** less than or equal to zero or if a memory allocate error occurs.
4400 **
4401 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4402 ** determined by the N parameter on first successful call.  Changing the
4403 ** value of N in subsequent call to sqlite3_aggregate_context() within
4404 ** the same aggregate function instance will not resize the memory
4405 ** allocation.)^
4406 **
4407 ** ^SQLite automatically frees the memory allocated by
4408 ** sqlite3_aggregate_context() when the aggregate query concludes.
4409 **
4410 ** The first parameter must be a copy of the
4411 ** [sqlite3_context | SQL function context] that is the first parameter
4412 ** to the xStep or xFinal callback routine that implements the aggregate
4413 ** function.
4414 **
4415 ** This routine must be called from the same thread in which
4416 ** the aggregate SQL function is running.
4417 */
4418 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4419 
4420 /*
4421 ** CAPI3REF: User Data For Functions
4422 **
4423 ** ^The sqlite3_user_data() interface returns a copy of
4424 ** the pointer that was the pUserData parameter (the 5th parameter)
4425 ** of the [sqlite3_create_function()]
4426 ** and [sqlite3_create_function16()] routines that originally
4427 ** registered the application defined function.
4428 **
4429 ** This routine must be called from the same thread in which
4430 ** the application-defined function is running.
4431 */
4432 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4433 
4434 /*
4435 ** CAPI3REF: Database Connection For Functions
4436 **
4437 ** ^The sqlite3_context_db_handle() interface returns a copy of
4438 ** the pointer to the [database connection] (the 1st parameter)
4439 ** of the [sqlite3_create_function()]
4440 ** and [sqlite3_create_function16()] routines that originally
4441 ** registered the application defined function.
4442 */
4443 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4444 
4445 /*
4446 ** CAPI3REF: Function Auxiliary Data
4447 **
4448 ** The following two functions may be used by scalar SQL functions to
4449 ** associate metadata with argument values. If the same value is passed to
4450 ** multiple invocations of the same SQL function during query execution, under
4451 ** some circumstances the associated metadata may be preserved. This may
4452 ** be used, for example, to add a regular-expression matching scalar
4453 ** function. The compiled version of the regular expression is stored as
4454 ** metadata associated with the SQL value passed as the regular expression
4455 ** pattern.  The compiled regular expression can be reused on multiple
4456 ** invocations of the same function so that the original pattern string
4457 ** does not need to be recompiled on each invocation.
4458 **
4459 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4460 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4461 ** value to the application-defined function. ^If no metadata has been ever
4462 ** been set for the Nth argument of the function, or if the corresponding
4463 ** function parameter has changed since the meta-data was set,
4464 ** then sqlite3_get_auxdata() returns a NULL pointer.
4465 **
4466 ** ^The sqlite3_set_auxdata() interface saves the metadata
4467 ** pointed to by its 3rd parameter as the metadata for the N-th
4468 ** argument of the application-defined function.  Subsequent
4469 ** calls to sqlite3_get_auxdata() might return this data, if it has
4470 ** not been destroyed.
4471 ** ^If it is not NULL, SQLite will invoke the destructor
4472 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4473 ** the metadata when the corresponding function parameter changes
4474 ** or when the SQL statement completes, whichever comes first.
4475 **
4476 ** SQLite is free to call the destructor and drop metadata on any
4477 ** parameter of any function at any time.  ^The only guarantee is that
4478 ** the destructor will be called before the metadata is dropped.
4479 **
4480 ** ^(In practice, metadata is preserved between function calls for
4481 ** expressions that are constant at compile time. This includes literal
4482 ** values and [parameters].)^
4483 **
4484 ** These routines must be called from the same thread in which
4485 ** the SQL function is running.
4486 */
4487 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4488 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4489 
4490 
4491 /*
4492 ** CAPI3REF: Constants Defining Special Destructor Behavior
4493 **
4494 ** These are special values for the destructor that is passed in as the
4495 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4496 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4497 ** and will never change.  It does not need to be destroyed.  ^The
4498 ** SQLITE_TRANSIENT value means that the content will likely change in
4499 ** the near future and that SQLite should make its own private copy of
4500 ** the content before returning.
4501 **
4502 ** The typedef is necessary to work around problems in certain
4503 ** C++ compilers.  See ticket #2191.
4504 */
4505 typedef void (*sqlite3_destructor_type)(void*);
4506 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4507 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4508 
4509 /*
4510 ** CAPI3REF: Setting The Result Of An SQL Function
4511 **
4512 ** These routines are used by the xFunc or xFinal callbacks that
4513 ** implement SQL functions and aggregates.  See
4514 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4515 ** for additional information.
4516 **
4517 ** These functions work very much like the [parameter binding] family of
4518 ** functions used to bind values to host parameters in prepared statements.
4519 ** Refer to the [SQL parameter] documentation for additional information.
4520 **
4521 ** ^The sqlite3_result_blob() interface sets the result from
4522 ** an application-defined function to be the BLOB whose content is pointed
4523 ** to by the second parameter and which is N bytes long where N is the
4524 ** third parameter.
4525 **
4526 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4527 ** the application-defined function to be a BLOB containing all zero
4528 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4529 **
4530 ** ^The sqlite3_result_double() interface sets the result from
4531 ** an application-defined function to be a floating point value specified
4532 ** by its 2nd argument.
4533 **
4534 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4535 ** cause the implemented SQL function to throw an exception.
4536 ** ^SQLite uses the string pointed to by the
4537 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4538 ** as the text of an error message.  ^SQLite interprets the error
4539 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4540 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4541 ** byte order.  ^If the third parameter to sqlite3_result_error()
4542 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4543 ** message all text up through the first zero character.
4544 ** ^If the third parameter to sqlite3_result_error() or
4545 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4546 ** bytes (not characters) from the 2nd parameter as the error message.
4547 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4548 ** routines make a private copy of the error message text before
4549 ** they return.  Hence, the calling function can deallocate or
4550 ** modify the text after they return without harm.
4551 ** ^The sqlite3_result_error_code() function changes the error code
4552 ** returned by SQLite as a result of an error in a function.  ^By default,
4553 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4554 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4555 **
4556 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4557 ** indicating that a string or BLOB is too long to represent.
4558 **
4559 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4560 ** indicating that a memory allocation failed.
4561 **
4562 ** ^The sqlite3_result_int() interface sets the return value
4563 ** of the application-defined function to be the 32-bit signed integer
4564 ** value given in the 2nd argument.
4565 ** ^The sqlite3_result_int64() interface sets the return value
4566 ** of the application-defined function to be the 64-bit signed integer
4567 ** value given in the 2nd argument.
4568 **
4569 ** ^The sqlite3_result_null() interface sets the return value
4570 ** of the application-defined function to be NULL.
4571 **
4572 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4573 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4574 ** set the return value of the application-defined function to be
4575 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4576 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4577 ** ^SQLite takes the text result from the application from
4578 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4579 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4580 ** is negative, then SQLite takes result text from the 2nd parameter
4581 ** through the first zero character.
4582 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4583 ** is non-negative, then as many bytes (not characters) of the text
4584 ** pointed to by the 2nd parameter are taken as the application-defined
4585 ** function result.
4586 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4587 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4588 ** function as the destructor on the text or BLOB result when it has
4589 ** finished using that result.
4590 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4591 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4592 ** assumes that the text or BLOB result is in constant space and does not
4593 ** copy the content of the parameter nor call a destructor on the content
4594 ** when it has finished using that result.
4595 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4596 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4597 ** then SQLite makes a copy of the result into space obtained from
4598 ** from [sqlite3_malloc()] before it returns.
4599 **
4600 ** ^The sqlite3_result_value() interface sets the result of
4601 ** the application-defined function to be a copy the
4602 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4603 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4604 ** so that the [sqlite3_value] specified in the parameter may change or
4605 ** be deallocated after sqlite3_result_value() returns without harm.
4606 ** ^A [protected sqlite3_value] object may always be used where an
4607 ** [unprotected sqlite3_value] object is required, so either
4608 ** kind of [sqlite3_value] object can be used with this interface.
4609 **
4610 ** If these routines are called from within the different thread
4611 ** than the one containing the application-defined function that received
4612 ** the [sqlite3_context] pointer, the results are undefined.
4613 */
4614 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4615 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4616 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4617 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4618 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4619 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4620 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4621 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4622 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4623 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4624 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4625 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4626 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4627 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4628 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4629 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4630 
4631 /*
4632 ** CAPI3REF: Define New Collating Sequences
4633 **
4634 ** ^These functions add, remove, or modify a [collation] associated
4635 ** with the [database connection] specified as the first argument.
4636 **
4637 ** ^The name of the collation is a UTF-8 string
4638 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4639 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4640 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4641 ** considered to be the same name.
4642 **
4643 ** ^(The third argument (eTextRep) must be one of the constants:
4644 ** <ul>
4645 ** <li> [SQLITE_UTF8],
4646 ** <li> [SQLITE_UTF16LE],
4647 ** <li> [SQLITE_UTF16BE],
4648 ** <li> [SQLITE_UTF16], or
4649 ** <li> [SQLITE_UTF16_ALIGNED].
4650 ** </ul>)^
4651 ** ^The eTextRep argument determines the encoding of strings passed
4652 ** to the collating function callback, xCallback.
4653 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4654 ** force strings to be UTF16 with native byte order.
4655 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4656 ** on an even byte address.
4657 **
4658 ** ^The fourth argument, pArg, is an application data pointer that is passed
4659 ** through as the first argument to the collating function callback.
4660 **
4661 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4662 ** ^Multiple collating functions can be registered using the same name but
4663 ** with different eTextRep parameters and SQLite will use whichever
4664 ** function requires the least amount of data transformation.
4665 ** ^If the xCallback argument is NULL then the collating function is
4666 ** deleted.  ^When all collating functions having the same name are deleted,
4667 ** that collation is no longer usable.
4668 **
4669 ** ^The collating function callback is invoked with a copy of the pArg
4670 ** application data pointer and with two strings in the encoding specified
4671 ** by the eTextRep argument.  The collating function must return an
4672 ** integer that is negative, zero, or positive
4673 ** if the first string is less than, equal to, or greater than the second,
4674 ** respectively.  A collating function must always return the same answer
4675 ** given the same inputs.  If two or more collating functions are registered
4676 ** to the same collation name (using different eTextRep values) then all
4677 ** must give an equivalent answer when invoked with equivalent strings.
4678 ** The collating function must obey the following properties for all
4679 ** strings A, B, and C:
4680 **
4681 ** <ol>
4682 ** <li> If A==B then B==A.
4683 ** <li> If A==B and B==C then A==C.
4684 ** <li> If A&lt;B THEN B&gt;A.
4685 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4686 ** </ol>
4687 **
4688 ** If a collating function fails any of the above constraints and that
4689 ** collating function is  registered and used, then the behavior of SQLite
4690 ** is undefined.
4691 **
4692 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4693 ** with the addition that the xDestroy callback is invoked on pArg when
4694 ** the collating function is deleted.
4695 ** ^Collating functions are deleted when they are overridden by later
4696 ** calls to the collation creation functions or when the
4697 ** [database connection] is closed using [sqlite3_close()].
4698 **
4699 ** ^The xDestroy callback is <u>not</u> called if the
4700 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4701 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4702 ** check the return code and dispose of the application data pointer
4703 ** themselves rather than expecting SQLite to deal with it for them.
4704 ** This is different from every other SQLite interface.  The inconsistency
4705 ** is unfortunate but cannot be changed without breaking backwards
4706 ** compatibility.
4707 **
4708 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4709 */
4710 SQLITE_API int sqlite3_create_collation(
4711   sqlite3*,
4712   const char *zName,
4713   int eTextRep,
4714   void *pArg,
4715   int(*xCompare)(void*,int,const void*,int,const void*)
4716 );
4717 SQLITE_API int sqlite3_create_collation_v2(
4718   sqlite3*,
4719   const char *zName,
4720   int eTextRep,
4721   void *pArg,
4722   int(*xCompare)(void*,int,const void*,int,const void*),
4723   void(*xDestroy)(void*)
4724 );
4725 SQLITE_API int sqlite3_create_collation16(
4726   sqlite3*,
4727   const void *zName,
4728   int eTextRep,
4729   void *pArg,
4730   int(*xCompare)(void*,int,const void*,int,const void*)
4731 );
4732 
4733 /*
4734 ** CAPI3REF: Collation Needed Callbacks
4735 **
4736 ** ^To avoid having to register all collation sequences before a database
4737 ** can be used, a single callback function may be registered with the
4738 ** [database connection] to be invoked whenever an undefined collation
4739 ** sequence is required.
4740 **
4741 ** ^If the function is registered using the sqlite3_collation_needed() API,
4742 ** then it is passed the names of undefined collation sequences as strings
4743 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4744 ** the names are passed as UTF-16 in machine native byte order.
4745 ** ^A call to either function replaces the existing collation-needed callback.
4746 **
4747 ** ^(When the callback is invoked, the first argument passed is a copy
4748 ** of the second argument to sqlite3_collation_needed() or
4749 ** sqlite3_collation_needed16().  The second argument is the database
4750 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4751 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4752 ** sequence function required.  The fourth parameter is the name of the
4753 ** required collation sequence.)^
4754 **
4755 ** The callback function should register the desired collation using
4756 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4757 ** [sqlite3_create_collation_v2()].
4758 */
4759 SQLITE_API int sqlite3_collation_needed(
4760   sqlite3*,
4761   void*,
4762   void(*)(void*,sqlite3*,int eTextRep,const char*)
4763 );
4764 SQLITE_API int sqlite3_collation_needed16(
4765   sqlite3*,
4766   void*,
4767   void(*)(void*,sqlite3*,int eTextRep,const void*)
4768 );
4769 
4770 #ifdef SQLITE_HAS_CODEC
4771 /*
4772 ** Specify the key for an encrypted database.  This routine should be
4773 ** called right after sqlite3_open().
4774 **
4775 ** The code to implement this API is not available in the public release
4776 ** of SQLite.
4777 */
4778 SQLITE_API int sqlite3_key(
4779   sqlite3 *db,                   /* Database to be rekeyed */
4780   const void *pKey, int nKey     /* The key */
4781 );
4782 
4783 /*
4784 ** Change the key on an open database.  If the current database is not
4785 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4786 ** database is decrypted.
4787 **
4788 ** The code to implement this API is not available in the public release
4789 ** of SQLite.
4790 */
4791 SQLITE_API int sqlite3_rekey(
4792   sqlite3 *db,                   /* Database to be rekeyed */
4793   const void *pKey, int nKey     /* The new key */
4794 );
4795 
4796 /*
4797 ** Specify the activation key for a SEE database.  Unless
4798 ** activated, none of the SEE routines will work.
4799 */
4800 SQLITE_API void sqlite3_activate_see(
4801   const char *zPassPhrase        /* Activation phrase */
4802 );
4803 #endif
4804 
4805 #ifdef SQLITE_ENABLE_CEROD
4806 /*
4807 ** Specify the activation key for a CEROD database.  Unless
4808 ** activated, none of the CEROD routines will work.
4809 */
4810 SQLITE_API void sqlite3_activate_cerod(
4811   const char *zPassPhrase        /* Activation phrase */
4812 );
4813 #endif
4814 
4815 /*
4816 ** CAPI3REF: Suspend Execution For A Short Time
4817 **
4818 ** The sqlite3_sleep() function causes the current thread to suspend execution
4819 ** for at least a number of milliseconds specified in its parameter.
4820 **
4821 ** If the operating system does not support sleep requests with
4822 ** millisecond time resolution, then the time will be rounded up to
4823 ** the nearest second. The number of milliseconds of sleep actually
4824 ** requested from the operating system is returned.
4825 **
4826 ** ^SQLite implements this interface by calling the xSleep()
4827 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
4828 ** of the default VFS is not implemented correctly, or not implemented at
4829 ** all, then the behavior of sqlite3_sleep() may deviate from the description
4830 ** in the previous paragraphs.
4831 */
4832 SQLITE_API int sqlite3_sleep(int);
4833 
4834 /*
4835 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4836 **
4837 ** ^(If this global variable is made to point to a string which is
4838 ** the name of a folder (a.k.a. directory), then all temporary files
4839 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4840 ** will be placed in that directory.)^  ^If this variable
4841 ** is a NULL pointer, then SQLite performs a search for an appropriate
4842 ** temporary file directory.
4843 **
4844 ** It is not safe to read or modify this variable in more than one
4845 ** thread at a time.  It is not safe to read or modify this variable
4846 ** if a [database connection] is being used at the same time in a separate
4847 ** thread.
4848 ** It is intended that this variable be set once
4849 ** as part of process initialization and before any SQLite interface
4850 ** routines have been called and that this variable remain unchanged
4851 ** thereafter.
4852 **
4853 ** ^The [temp_store_directory pragma] may modify this variable and cause
4854 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4855 ** the [temp_store_directory pragma] always assumes that any string
4856 ** that this variable points to is held in memory obtained from
4857 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4858 ** using [sqlite3_free].
4859 ** Hence, if this variable is modified directly, either it should be
4860 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4861 ** or else the use of the [temp_store_directory pragma] should be avoided.
4862 */
4863 SQLITE_API char *sqlite3_temp_directory;
4864 
4865 /*
4866 ** CAPI3REF: Test For Auto-Commit Mode
4867 ** KEYWORDS: {autocommit mode}
4868 **
4869 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4870 ** zero if the given database connection is or is not in autocommit mode,
4871 ** respectively.  ^Autocommit mode is on by default.
4872 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4873 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4874 **
4875 ** If certain kinds of errors occur on a statement within a multi-statement
4876 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4877 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4878 ** transaction might be rolled back automatically.  The only way to
4879 ** find out whether SQLite automatically rolled back the transaction after
4880 ** an error is to use this function.
4881 **
4882 ** If another thread changes the autocommit status of the database
4883 ** connection while this routine is running, then the return value
4884 ** is undefined.
4885 */
4886 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4887 
4888 /*
4889 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4890 **
4891 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4892 ** to which a [prepared statement] belongs.  ^The [database connection]
4893 ** returned by sqlite3_db_handle is the same [database connection]
4894 ** that was the first argument
4895 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4896 ** create the statement in the first place.
4897 */
4898 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4899 
4900 /*
4901 ** CAPI3REF: Find the next prepared statement
4902 **
4903 ** ^This interface returns a pointer to the next [prepared statement] after
4904 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4905 ** then this interface returns a pointer to the first prepared statement
4906 ** associated with the database connection pDb.  ^If no prepared statement
4907 ** satisfies the conditions of this routine, it returns NULL.
4908 **
4909 ** The [database connection] pointer D in a call to
4910 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4911 ** connection and in particular must not be a NULL pointer.
4912 */
4913 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4914 
4915 /*
4916 ** CAPI3REF: Commit And Rollback Notification Callbacks
4917 **
4918 ** ^The sqlite3_commit_hook() interface registers a callback
4919 ** function to be invoked whenever a transaction is [COMMIT | committed].
4920 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4921 ** for the same database connection is overridden.
4922 ** ^The sqlite3_rollback_hook() interface registers a callback
4923 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4924 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4925 ** for the same database connection is overridden.
4926 ** ^The pArg argument is passed through to the callback.
4927 ** ^If the callback on a commit hook function returns non-zero,
4928 ** then the commit is converted into a rollback.
4929 **
4930 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4931 ** return the P argument from the previous call of the same function
4932 ** on the same [database connection] D, or NULL for
4933 ** the first call for each function on D.
4934 **
4935 ** The callback implementation must not do anything that will modify
4936 ** the database connection that invoked the callback.  Any actions
4937 ** to modify the database connection must be deferred until after the
4938 ** completion of the [sqlite3_step()] call that triggered the commit
4939 ** or rollback hook in the first place.
4940 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4941 ** database connections for the meaning of "modify" in this paragraph.
4942 **
4943 ** ^Registering a NULL function disables the callback.
4944 **
4945 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4946 ** operation is allowed to continue normally.  ^If the commit hook
4947 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4948 ** ^The rollback hook is invoked on a rollback that results from a commit
4949 ** hook returning non-zero, just as it would be with any other rollback.
4950 **
4951 ** ^For the purposes of this API, a transaction is said to have been
4952 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4953 ** an error or constraint causes an implicit rollback to occur.
4954 ** ^The rollback callback is not invoked if a transaction is
4955 ** automatically rolled back because the database connection is closed.
4956 **
4957 ** See also the [sqlite3_update_hook()] interface.
4958 */
4959 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4960 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4961 
4962 /*
4963 ** CAPI3REF: Data Change Notification Callbacks
4964 **
4965 ** ^The sqlite3_update_hook() interface registers a callback function
4966 ** with the [database connection] identified by the first argument
4967 ** to be invoked whenever a row is updated, inserted or deleted.
4968 ** ^Any callback set by a previous call to this function
4969 ** for the same database connection is overridden.
4970 **
4971 ** ^The second argument is a pointer to the function to invoke when a
4972 ** row is updated, inserted or deleted.
4973 ** ^The first argument to the callback is a copy of the third argument
4974 ** to sqlite3_update_hook().
4975 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4976 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4977 ** to be invoked.
4978 ** ^The third and fourth arguments to the callback contain pointers to the
4979 ** database and table name containing the affected row.
4980 ** ^The final callback parameter is the [rowid] of the row.
4981 ** ^In the case of an update, this is the [rowid] after the update takes place.
4982 **
4983 ** ^(The update hook is not invoked when internal system tables are
4984 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4985 **
4986 ** ^In the current implementation, the update hook
4987 ** is not invoked when duplication rows are deleted because of an
4988 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4989 ** invoked when rows are deleted using the [truncate optimization].
4990 ** The exceptions defined in this paragraph might change in a future
4991 ** release of SQLite.
4992 **
4993 ** The update hook implementation must not do anything that will modify
4994 ** the database connection that invoked the update hook.  Any actions
4995 ** to modify the database connection must be deferred until after the
4996 ** completion of the [sqlite3_step()] call that triggered the update hook.
4997 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4998 ** database connections for the meaning of "modify" in this paragraph.
4999 **
5000 ** ^The sqlite3_update_hook(D,C,P) function
5001 ** returns the P argument from the previous call
5002 ** on the same [database connection] D, or NULL for
5003 ** the first call on D.
5004 **
5005 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5006 ** interfaces.
5007 */
5008 SQLITE_API void *sqlite3_update_hook(
5009   sqlite3*,
5010   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5011   void*
5012 );
5013 
5014 /*
5015 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5016 ** KEYWORDS: {shared cache}
5017 **
5018 ** ^(This routine enables or disables the sharing of the database cache
5019 ** and schema data structures between [database connection | connections]
5020 ** to the same database. Sharing is enabled if the argument is true
5021 ** and disabled if the argument is false.)^
5022 **
5023 ** ^Cache sharing is enabled and disabled for an entire process.
5024 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5025 ** sharing was enabled or disabled for each thread separately.
5026 **
5027 ** ^(The cache sharing mode set by this interface effects all subsequent
5028 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5029 ** Existing database connections continue use the sharing mode
5030 ** that was in effect at the time they were opened.)^
5031 **
5032 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5033 ** successfully.  An [error code] is returned otherwise.)^
5034 **
5035 ** ^Shared cache is disabled by default. But this might change in
5036 ** future releases of SQLite.  Applications that care about shared
5037 ** cache setting should set it explicitly.
5038 **
5039 ** See Also:  [SQLite Shared-Cache Mode]
5040 */
5041 SQLITE_API int sqlite3_enable_shared_cache(int);
5042 
5043 /*
5044 ** CAPI3REF: Attempt To Free Heap Memory
5045 **
5046 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5047 ** of heap memory by deallocating non-essential memory allocations
5048 ** held by the database library.   Memory used to cache database
5049 ** pages to improve performance is an example of non-essential memory.
5050 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5051 ** which might be more or less than the amount requested.
5052 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5053 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5054 */
5055 SQLITE_API int sqlite3_release_memory(int);
5056 
5057 /*
5058 ** CAPI3REF: Impose A Limit On Heap Size
5059 **
5060 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5061 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5062 ** ^SQLite strives to keep heap memory utilization below the soft heap
5063 ** limit by reducing the number of pages held in the page cache
5064 ** as heap memory usages approaches the limit.
5065 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5066 ** below the limit, it will exceed the limit rather than generate
5067 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5068 ** is advisory only.
5069 **
5070 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5071 ** the soft heap limit prior to the call.  ^If the argument N is negative
5072 ** then no change is made to the soft heap limit.  Hence, the current
5073 ** size of the soft heap limit can be determined by invoking
5074 ** sqlite3_soft_heap_limit64() with a negative argument.
5075 **
5076 ** ^If the argument N is zero then the soft heap limit is disabled.
5077 **
5078 ** ^(The soft heap limit is not enforced in the current implementation
5079 ** if one or more of following conditions are true:
5080 **
5081 ** <ul>
5082 ** <li> The soft heap limit is set to zero.
5083 ** <li> Memory accounting is disabled using a combination of the
5084 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5085 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5086 ** <li> An alternative page cache implementation is specified using
5087 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE],...).
5088 ** <li> The page cache allocates from its own memory pool supplied
5089 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5090 **      from the heap.
5091 ** </ul>)^
5092 **
5093 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5094 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5095 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5096 ** the soft heap limit is enforced on every memory allocation.  Without
5097 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5098 ** when memory is allocated by the page cache.  Testing suggests that because
5099 ** the page cache is the predominate memory user in SQLite, most
5100 ** applications will achieve adequate soft heap limit enforcement without
5101 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5102 **
5103 ** The circumstances under which SQLite will enforce the soft heap limit may
5104 ** changes in future releases of SQLite.
5105 */
5106 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5107 
5108 /*
5109 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5110 ** DEPRECATED
5111 **
5112 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5113 ** interface.  This routine is provided for historical compatibility
5114 ** only.  All new applications should use the
5115 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5116 */
5117 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5118 
5119 
5120 /*
5121 ** CAPI3REF: Extract Metadata About A Column Of A Table
5122 **
5123 ** ^This routine returns metadata about a specific column of a specific
5124 ** database table accessible using the [database connection] handle
5125 ** passed as the first function argument.
5126 **
5127 ** ^The column is identified by the second, third and fourth parameters to
5128 ** this function. ^The second parameter is either the name of the database
5129 ** (i.e. "main", "temp", or an attached database) containing the specified
5130 ** table or NULL. ^If it is NULL, then all attached databases are searched
5131 ** for the table using the same algorithm used by the database engine to
5132 ** resolve unqualified table references.
5133 **
5134 ** ^The third and fourth parameters to this function are the table and column
5135 ** name of the desired column, respectively. Neither of these parameters
5136 ** may be NULL.
5137 **
5138 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5139 ** and subsequent parameters to this function. ^Any of these arguments may be
5140 ** NULL, in which case the corresponding element of metadata is omitted.
5141 **
5142 ** ^(<blockquote>
5143 ** <table border="1">
5144 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5145 **
5146 ** <tr><td> 5th <td> const char* <td> Data type
5147 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5148 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5149 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5150 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5151 ** </table>
5152 ** </blockquote>)^
5153 **
5154 ** ^The memory pointed to by the character pointers returned for the
5155 ** declaration type and collation sequence is valid only until the next
5156 ** call to any SQLite API function.
5157 **
5158 ** ^If the specified table is actually a view, an [error code] is returned.
5159 **
5160 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5161 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5162 ** parameters are set for the explicitly declared column. ^(If there is no
5163 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5164 ** parameters are set as follows:
5165 **
5166 ** <pre>
5167 **     data type: "INTEGER"
5168 **     collation sequence: "BINARY"
5169 **     not null: 0
5170 **     primary key: 1
5171 **     auto increment: 0
5172 ** </pre>)^
5173 **
5174 ** ^(This function may load one or more schemas from database files. If an
5175 ** error occurs during this process, or if the requested table or column
5176 ** cannot be found, an [error code] is returned and an error message left
5177 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5178 **
5179 ** ^This API is only available if the library was compiled with the
5180 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5181 */
5182 SQLITE_API int sqlite3_table_column_metadata(
5183   sqlite3 *db,                /* Connection handle */
5184   const char *zDbName,        /* Database name or NULL */
5185   const char *zTableName,     /* Table name */
5186   const char *zColumnName,    /* Column name */
5187   char const **pzDataType,    /* OUTPUT: Declared data type */
5188   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5189   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5190   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5191   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5192 );
5193 
5194 /*
5195 ** CAPI3REF: Load An Extension
5196 **
5197 ** ^This interface loads an SQLite extension library from the named file.
5198 **
5199 ** ^The sqlite3_load_extension() interface attempts to load an
5200 ** SQLite extension library contained in the file zFile.
5201 **
5202 ** ^The entry point is zProc.
5203 ** ^zProc may be 0, in which case the name of the entry point
5204 ** defaults to "sqlite3_extension_init".
5205 ** ^The sqlite3_load_extension() interface returns
5206 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5207 ** ^If an error occurs and pzErrMsg is not 0, then the
5208 ** [sqlite3_load_extension()] interface shall attempt to
5209 ** fill *pzErrMsg with error message text stored in memory
5210 ** obtained from [sqlite3_malloc()]. The calling function
5211 ** should free this memory by calling [sqlite3_free()].
5212 **
5213 ** ^Extension loading must be enabled using
5214 ** [sqlite3_enable_load_extension()] prior to calling this API,
5215 ** otherwise an error will be returned.
5216 **
5217 ** See also the [load_extension() SQL function].
5218 */
5219 SQLITE_API int sqlite3_load_extension(
5220   sqlite3 *db,          /* Load the extension into this database connection */
5221   const char *zFile,    /* Name of the shared library containing extension */
5222   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5223   char **pzErrMsg       /* Put error message here if not 0 */
5224 );
5225 
5226 /*
5227 ** CAPI3REF: Enable Or Disable Extension Loading
5228 **
5229 ** ^So as not to open security holes in older applications that are
5230 ** unprepared to deal with extension loading, and as a means of disabling
5231 ** extension loading while evaluating user-entered SQL, the following API
5232 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5233 **
5234 ** ^Extension loading is off by default. See ticket #1863.
5235 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5236 ** to turn extension loading on and call it with onoff==0 to turn
5237 ** it back off again.
5238 */
5239 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5240 
5241 /*
5242 ** CAPI3REF: Automatically Load Statically Linked Extensions
5243 **
5244 ** ^This interface causes the xEntryPoint() function to be invoked for
5245 ** each new [database connection] that is created.  The idea here is that
5246 ** xEntryPoint() is the entry point for a statically linked SQLite extension
5247 ** that is to be automatically loaded into all new database connections.
5248 **
5249 ** ^(Even though the function prototype shows that xEntryPoint() takes
5250 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5251 ** arguments and expects and integer result as if the signature of the
5252 ** entry point where as follows:
5253 **
5254 ** <blockquote><pre>
5255 ** &nbsp;  int xEntryPoint(
5256 ** &nbsp;    sqlite3 *db,
5257 ** &nbsp;    const char **pzErrMsg,
5258 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5259 ** &nbsp;  );
5260 ** </pre></blockquote>)^
5261 **
5262 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5263 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5264 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5265 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5266 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5267 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5268 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5269 **
5270 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5271 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5272 ** will be called more than once for each database connection that is opened.
5273 **
5274 ** See also: [sqlite3_reset_auto_extension()].
5275 */
5276 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5277 
5278 /*
5279 ** CAPI3REF: Reset Automatic Extension Loading
5280 **
5281 ** ^This interface disables all automatic extensions previously
5282 ** registered using [sqlite3_auto_extension()].
5283 */
5284 SQLITE_API void sqlite3_reset_auto_extension(void);
5285 
5286 /*
5287 ** The interface to the virtual-table mechanism is currently considered
5288 ** to be experimental.  The interface might change in incompatible ways.
5289 ** If this is a problem for you, do not use the interface at this time.
5290 **
5291 ** When the virtual-table mechanism stabilizes, we will declare the
5292 ** interface fixed, support it indefinitely, and remove this comment.
5293 */
5294 
5295 /*
5296 ** Structures used by the virtual table interface
5297 */
5298 typedef struct sqlite3_vtab sqlite3_vtab;
5299 typedef struct sqlite3_index_info sqlite3_index_info;
5300 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5301 typedef struct sqlite3_module sqlite3_module;
5302 
5303 /*
5304 ** CAPI3REF: Virtual Table Object
5305 ** KEYWORDS: sqlite3_module {virtual table module}
5306 **
5307 ** This structure, sometimes called a "virtual table module",
5308 ** defines the implementation of a [virtual tables].
5309 ** This structure consists mostly of methods for the module.
5310 **
5311 ** ^A virtual table module is created by filling in a persistent
5312 ** instance of this structure and passing a pointer to that instance
5313 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5314 ** ^The registration remains valid until it is replaced by a different
5315 ** module or until the [database connection] closes.  The content
5316 ** of this structure must not change while it is registered with
5317 ** any database connection.
5318 */
5319 struct sqlite3_module {
5320   int iVersion;
5321   int (*xCreate)(sqlite3*, void *pAux,
5322                int argc, const char *const*argv,
5323                sqlite3_vtab **ppVTab, char**);
5324   int (*xConnect)(sqlite3*, void *pAux,
5325                int argc, const char *const*argv,
5326                sqlite3_vtab **ppVTab, char**);
5327   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5328   int (*xDisconnect)(sqlite3_vtab *pVTab);
5329   int (*xDestroy)(sqlite3_vtab *pVTab);
5330   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5331   int (*xClose)(sqlite3_vtab_cursor*);
5332   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5333                 int argc, sqlite3_value **argv);
5334   int (*xNext)(sqlite3_vtab_cursor*);
5335   int (*xEof)(sqlite3_vtab_cursor*);
5336   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5337   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5338   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5339   int (*xBegin)(sqlite3_vtab *pVTab);
5340   int (*xSync)(sqlite3_vtab *pVTab);
5341   int (*xCommit)(sqlite3_vtab *pVTab);
5342   int (*xRollback)(sqlite3_vtab *pVTab);
5343   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5344                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5345                        void **ppArg);
5346   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5347   /* The methods above are in version 1 of the sqlite_module object. Those
5348   ** below are for version 2 and greater. */
5349   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5350   int (*xRelease)(sqlite3_vtab *pVTab, int);
5351   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5352 };
5353 
5354 /*
5355 ** CAPI3REF: Virtual Table Indexing Information
5356 ** KEYWORDS: sqlite3_index_info
5357 **
5358 ** The sqlite3_index_info structure and its substructures is used as part
5359 ** of the [virtual table] interface to
5360 ** pass information into and receive the reply from the [xBestIndex]
5361 ** method of a [virtual table module].  The fields under **Inputs** are the
5362 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5363 ** results into the **Outputs** fields.
5364 **
5365 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5366 **
5367 ** <blockquote>column OP expr</blockquote>
5368 **
5369 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5370 ** stored in aConstraint[].op using one of the
5371 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5372 ** ^(The index of the column is stored in
5373 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5374 ** expr on the right-hand side can be evaluated (and thus the constraint
5375 ** is usable) and false if it cannot.)^
5376 **
5377 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5378 ** and makes other simplifications to the WHERE clause in an attempt to
5379 ** get as many WHERE clause terms into the form shown above as possible.
5380 ** ^The aConstraint[] array only reports WHERE clause terms that are
5381 ** relevant to the particular virtual table being queried.
5382 **
5383 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5384 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5385 **
5386 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5387 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5388 ** the right-hand side of the corresponding aConstraint[] is evaluated
5389 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5390 ** is true, then the constraint is assumed to be fully handled by the
5391 ** virtual table and is not checked again by SQLite.)^
5392 **
5393 ** ^The idxNum and idxPtr values are recorded and passed into the
5394 ** [xFilter] method.
5395 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5396 ** needToFreeIdxPtr is true.
5397 **
5398 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5399 ** the correct order to satisfy the ORDER BY clause so that no separate
5400 ** sorting step is required.
5401 **
5402 ** ^The estimatedCost value is an estimate of the cost of doing the
5403 ** particular lookup.  A full scan of a table with N entries should have
5404 ** a cost of N.  A binary search of a table of N entries should have a
5405 ** cost of approximately log(N).
5406 */
5407 struct sqlite3_index_info {
5408   /* Inputs */
5409   int nConstraint;           /* Number of entries in aConstraint */
5410   struct sqlite3_index_constraint {
5411      int iColumn;              /* Column on left-hand side of constraint */
5412      unsigned char op;         /* Constraint operator */
5413      unsigned char usable;     /* True if this constraint is usable */
5414      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5415   } *aConstraint;            /* Table of WHERE clause constraints */
5416   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5417   struct sqlite3_index_orderby {
5418      int iColumn;              /* Column number */
5419      unsigned char desc;       /* True for DESC.  False for ASC. */
5420   } *aOrderBy;               /* The ORDER BY clause */
5421   /* Outputs */
5422   struct sqlite3_index_constraint_usage {
5423     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5424     unsigned char omit;      /* Do not code a test for this constraint */
5425   } *aConstraintUsage;
5426   int idxNum;                /* Number used to identify the index */
5427   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5428   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5429   int orderByConsumed;       /* True if output is already ordered */
5430   double estimatedCost;      /* Estimated cost of using this index */
5431 };
5432 
5433 /*
5434 ** CAPI3REF: Virtual Table Constraint Operator Codes
5435 **
5436 ** These macros defined the allowed values for the
5437 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5438 ** an operator that is part of a constraint term in the wHERE clause of
5439 ** a query that uses a [virtual table].
5440 */
5441 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5442 #define SQLITE_INDEX_CONSTRAINT_GT    4
5443 #define SQLITE_INDEX_CONSTRAINT_LE    8
5444 #define SQLITE_INDEX_CONSTRAINT_LT    16
5445 #define SQLITE_INDEX_CONSTRAINT_GE    32
5446 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5447 
5448 /*
5449 ** CAPI3REF: Register A Virtual Table Implementation
5450 **
5451 ** ^These routines are used to register a new [virtual table module] name.
5452 ** ^Module names must be registered before
5453 ** creating a new [virtual table] using the module and before using a
5454 ** preexisting [virtual table] for the module.
5455 **
5456 ** ^The module name is registered on the [database connection] specified
5457 ** by the first parameter.  ^The name of the module is given by the
5458 ** second parameter.  ^The third parameter is a pointer to
5459 ** the implementation of the [virtual table module].   ^The fourth
5460 ** parameter is an arbitrary client data pointer that is passed through
5461 ** into the [xCreate] and [xConnect] methods of the virtual table module
5462 ** when a new virtual table is be being created or reinitialized.
5463 **
5464 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5465 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5466 ** invoke the destructor function (if it is not NULL) when SQLite
5467 ** no longer needs the pClientData pointer.  ^The destructor will also
5468 ** be invoked if the call to sqlite3_create_module_v2() fails.
5469 ** ^The sqlite3_create_module()
5470 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5471 ** destructor.
5472 */
5473 SQLITE_API int sqlite3_create_module(
5474   sqlite3 *db,               /* SQLite connection to register module with */
5475   const char *zName,         /* Name of the module */
5476   const sqlite3_module *p,   /* Methods for the module */
5477   void *pClientData          /* Client data for xCreate/xConnect */
5478 );
5479 SQLITE_API int sqlite3_create_module_v2(
5480   sqlite3 *db,               /* SQLite connection to register module with */
5481   const char *zName,         /* Name of the module */
5482   const sqlite3_module *p,   /* Methods for the module */
5483   void *pClientData,         /* Client data for xCreate/xConnect */
5484   void(*xDestroy)(void*)     /* Module destructor function */
5485 );
5486 
5487 /*
5488 ** CAPI3REF: Virtual Table Instance Object
5489 ** KEYWORDS: sqlite3_vtab
5490 **
5491 ** Every [virtual table module] implementation uses a subclass
5492 ** of this object to describe a particular instance
5493 ** of the [virtual table].  Each subclass will
5494 ** be tailored to the specific needs of the module implementation.
5495 ** The purpose of this superclass is to define certain fields that are
5496 ** common to all module implementations.
5497 **
5498 ** ^Virtual tables methods can set an error message by assigning a
5499 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5500 ** take care that any prior string is freed by a call to [sqlite3_free()]
5501 ** prior to assigning a new string to zErrMsg.  ^After the error message
5502 ** is delivered up to the client application, the string will be automatically
5503 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5504 */
5505 struct sqlite3_vtab {
5506   const sqlite3_module *pModule;  /* The module for this virtual table */
5507   int nRef;                       /* NO LONGER USED */
5508   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5509   /* Virtual table implementations will typically add additional fields */
5510 };
5511 
5512 /*
5513 ** CAPI3REF: Virtual Table Cursor Object
5514 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5515 **
5516 ** Every [virtual table module] implementation uses a subclass of the
5517 ** following structure to describe cursors that point into the
5518 ** [virtual table] and are used
5519 ** to loop through the virtual table.  Cursors are created using the
5520 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5521 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5522 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5523 ** of the module.  Each module implementation will define
5524 ** the content of a cursor structure to suit its own needs.
5525 **
5526 ** This superclass exists in order to define fields of the cursor that
5527 ** are common to all implementations.
5528 */
5529 struct sqlite3_vtab_cursor {
5530   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5531   /* Virtual table implementations will typically add additional fields */
5532 };
5533 
5534 /*
5535 ** CAPI3REF: Declare The Schema Of A Virtual Table
5536 **
5537 ** ^The [xCreate] and [xConnect] methods of a
5538 ** [virtual table module] call this interface
5539 ** to declare the format (the names and datatypes of the columns) of
5540 ** the virtual tables they implement.
5541 */
5542 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5543 
5544 /*
5545 ** CAPI3REF: Overload A Function For A Virtual Table
5546 **
5547 ** ^(Virtual tables can provide alternative implementations of functions
5548 ** using the [xFindFunction] method of the [virtual table module].
5549 ** But global versions of those functions
5550 ** must exist in order to be overloaded.)^
5551 **
5552 ** ^(This API makes sure a global version of a function with a particular
5553 ** name and number of parameters exists.  If no such function exists
5554 ** before this API is called, a new function is created.)^  ^The implementation
5555 ** of the new function always causes an exception to be thrown.  So
5556 ** the new function is not good for anything by itself.  Its only
5557 ** purpose is to be a placeholder function that can be overloaded
5558 ** by a [virtual table].
5559 */
5560 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5561 
5562 /*
5563 ** The interface to the virtual-table mechanism defined above (back up
5564 ** to a comment remarkably similar to this one) is currently considered
5565 ** to be experimental.  The interface might change in incompatible ways.
5566 ** If this is a problem for you, do not use the interface at this time.
5567 **
5568 ** When the virtual-table mechanism stabilizes, we will declare the
5569 ** interface fixed, support it indefinitely, and remove this comment.
5570 */
5571 
5572 /*
5573 ** CAPI3REF: A Handle To An Open BLOB
5574 ** KEYWORDS: {BLOB handle} {BLOB handles}
5575 **
5576 ** An instance of this object represents an open BLOB on which
5577 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5578 ** ^Objects of this type are created by [sqlite3_blob_open()]
5579 ** and destroyed by [sqlite3_blob_close()].
5580 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5581 ** can be used to read or write small subsections of the BLOB.
5582 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5583 */
5584 typedef struct sqlite3_blob sqlite3_blob;
5585 
5586 /*
5587 ** CAPI3REF: Open A BLOB For Incremental I/O
5588 **
5589 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5590 ** in row iRow, column zColumn, table zTable in database zDb;
5591 ** in other words, the same BLOB that would be selected by:
5592 **
5593 ** <pre>
5594 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5595 ** </pre>)^
5596 **
5597 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5598 ** and write access. ^If it is zero, the BLOB is opened for read access.
5599 ** ^It is not possible to open a column that is part of an index or primary
5600 ** key for writing. ^If [foreign key constraints] are enabled, it is
5601 ** not possible to open a column that is part of a [child key] for writing.
5602 **
5603 ** ^Note that the database name is not the filename that contains
5604 ** the database but rather the symbolic name of the database that
5605 ** appears after the AS keyword when the database is connected using [ATTACH].
5606 ** ^For the main database file, the database name is "main".
5607 ** ^For TEMP tables, the database name is "temp".
5608 **
5609 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5610 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5611 ** to be a null pointer.)^
5612 ** ^This function sets the [database connection] error code and message
5613 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5614 ** functions. ^Note that the *ppBlob variable is always initialized in a
5615 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5616 ** regardless of the success or failure of this routine.
5617 **
5618 ** ^(If the row that a BLOB handle points to is modified by an
5619 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5620 ** then the BLOB handle is marked as "expired".
5621 ** This is true if any column of the row is changed, even a column
5622 ** other than the one the BLOB handle is open on.)^
5623 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5624 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5625 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5626 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5627 ** commit if the transaction continues to completion.)^
5628 **
5629 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5630 ** the opened blob.  ^The size of a blob may not be changed by this
5631 ** interface.  Use the [UPDATE] SQL command to change the size of a
5632 ** blob.
5633 **
5634 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5635 ** and the built-in [zeroblob] SQL function can be used, if desired,
5636 ** to create an empty, zero-filled blob in which to read or write using
5637 ** this interface.
5638 **
5639 ** To avoid a resource leak, every open [BLOB handle] should eventually
5640 ** be released by a call to [sqlite3_blob_close()].
5641 */
5642 SQLITE_API int sqlite3_blob_open(
5643   sqlite3*,
5644   const char *zDb,
5645   const char *zTable,
5646   const char *zColumn,
5647   sqlite3_int64 iRow,
5648   int flags,
5649   sqlite3_blob **ppBlob
5650 );
5651 
5652 /*
5653 ** CAPI3REF: Move a BLOB Handle to a New Row
5654 **
5655 ** ^This function is used to move an existing blob handle so that it points
5656 ** to a different row of the same database table. ^The new row is identified
5657 ** by the rowid value passed as the second argument. Only the row can be
5658 ** changed. ^The database, table and column on which the blob handle is open
5659 ** remain the same. Moving an existing blob handle to a new row can be
5660 ** faster than closing the existing handle and opening a new one.
5661 **
5662 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5663 ** it must exist and there must be either a blob or text value stored in
5664 ** the nominated column.)^ ^If the new row is not present in the table, or if
5665 ** it does not contain a blob or text value, or if another error occurs, an
5666 ** SQLite error code is returned and the blob handle is considered aborted.
5667 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5668 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5669 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5670 ** always returns zero.
5671 **
5672 ** ^This function sets the database handle error code and message.
5673 */
5674 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5675 
5676 /*
5677 ** CAPI3REF: Close A BLOB Handle
5678 **
5679 ** ^Closes an open [BLOB handle].
5680 **
5681 ** ^Closing a BLOB shall cause the current transaction to commit
5682 ** if there are no other BLOBs, no pending prepared statements, and the
5683 ** database connection is in [autocommit mode].
5684 ** ^If any writes were made to the BLOB, they might be held in cache
5685 ** until the close operation if they will fit.
5686 **
5687 ** ^(Closing the BLOB often forces the changes
5688 ** out to disk and so if any I/O errors occur, they will likely occur
5689 ** at the time when the BLOB is closed.  Any errors that occur during
5690 ** closing are reported as a non-zero return value.)^
5691 **
5692 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5693 ** an error code, the BLOB is still closed.)^
5694 **
5695 ** ^Calling this routine with a null pointer (such as would be returned
5696 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5697 */
5698 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5699 
5700 /*
5701 ** CAPI3REF: Return The Size Of An Open BLOB
5702 **
5703 ** ^Returns the size in bytes of the BLOB accessible via the
5704 ** successfully opened [BLOB handle] in its only argument.  ^The
5705 ** incremental blob I/O routines can only read or overwriting existing
5706 ** blob content; they cannot change the size of a blob.
5707 **
5708 ** This routine only works on a [BLOB handle] which has been created
5709 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5710 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5711 ** to this routine results in undefined and probably undesirable behavior.
5712 */
5713 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5714 
5715 /*
5716 ** CAPI3REF: Read Data From A BLOB Incrementally
5717 **
5718 ** ^(This function is used to read data from an open [BLOB handle] into a
5719 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5720 ** from the open BLOB, starting at offset iOffset.)^
5721 **
5722 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5723 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5724 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5725 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5726 ** can be determined using the [sqlite3_blob_bytes()] interface.
5727 **
5728 ** ^An attempt to read from an expired [BLOB handle] fails with an
5729 ** error code of [SQLITE_ABORT].
5730 **
5731 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5732 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5733 **
5734 ** This routine only works on a [BLOB handle] which has been created
5735 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5736 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5737 ** to this routine results in undefined and probably undesirable behavior.
5738 **
5739 ** See also: [sqlite3_blob_write()].
5740 */
5741 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5742 
5743 /*
5744 ** CAPI3REF: Write Data Into A BLOB Incrementally
5745 **
5746 ** ^This function is used to write data into an open [BLOB handle] from a
5747 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5748 ** into the open BLOB, starting at offset iOffset.
5749 **
5750 ** ^If the [BLOB handle] passed as the first argument was not opened for
5751 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5752 ** this function returns [SQLITE_READONLY].
5753 **
5754 ** ^This function may only modify the contents of the BLOB; it is
5755 ** not possible to increase the size of a BLOB using this API.
5756 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5757 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5758 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5759 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5760 ** can be determined using the [sqlite3_blob_bytes()] interface.
5761 **
5762 ** ^An attempt to write to an expired [BLOB handle] fails with an
5763 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5764 ** before the [BLOB handle] expired are not rolled back by the
5765 ** expiration of the handle, though of course those changes might
5766 ** have been overwritten by the statement that expired the BLOB handle
5767 ** or by other independent statements.
5768 **
5769 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5770 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5771 **
5772 ** This routine only works on a [BLOB handle] which has been created
5773 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5774 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5775 ** to this routine results in undefined and probably undesirable behavior.
5776 **
5777 ** See also: [sqlite3_blob_read()].
5778 */
5779 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5780 
5781 /*
5782 ** CAPI3REF: Virtual File System Objects
5783 **
5784 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5785 ** that SQLite uses to interact
5786 ** with the underlying operating system.  Most SQLite builds come with a
5787 ** single default VFS that is appropriate for the host computer.
5788 ** New VFSes can be registered and existing VFSes can be unregistered.
5789 ** The following interfaces are provided.
5790 **
5791 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5792 ** ^Names are case sensitive.
5793 ** ^Names are zero-terminated UTF-8 strings.
5794 ** ^If there is no match, a NULL pointer is returned.
5795 ** ^If zVfsName is NULL then the default VFS is returned.
5796 **
5797 ** ^New VFSes are registered with sqlite3_vfs_register().
5798 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5799 ** ^The same VFS can be registered multiple times without injury.
5800 ** ^To make an existing VFS into the default VFS, register it again
5801 ** with the makeDflt flag set.  If two different VFSes with the
5802 ** same name are registered, the behavior is undefined.  If a
5803 ** VFS is registered with a name that is NULL or an empty string,
5804 ** then the behavior is undefined.
5805 **
5806 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5807 ** ^(If the default VFS is unregistered, another VFS is chosen as
5808 ** the default.  The choice for the new VFS is arbitrary.)^
5809 */
5810 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5811 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5812 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5813 
5814 /*
5815 ** CAPI3REF: Mutexes
5816 **
5817 ** The SQLite core uses these routines for thread
5818 ** synchronization. Though they are intended for internal
5819 ** use by SQLite, code that links against SQLite is
5820 ** permitted to use any of these routines.
5821 **
5822 ** The SQLite source code contains multiple implementations
5823 ** of these mutex routines.  An appropriate implementation
5824 ** is selected automatically at compile-time.  ^(The following
5825 ** implementations are available in the SQLite core:
5826 **
5827 ** <ul>
5828 ** <li>   SQLITE_MUTEX_OS2
5829 ** <li>   SQLITE_MUTEX_PTHREAD
5830 ** <li>   SQLITE_MUTEX_W32
5831 ** <li>   SQLITE_MUTEX_NOOP
5832 ** </ul>)^
5833 **
5834 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5835 ** that does no real locking and is appropriate for use in
5836 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5837 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5838 ** are appropriate for use on OS/2, Unix, and Windows.
5839 **
5840 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5841 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5842 ** implementation is included with the library. In this case the
5843 ** application must supply a custom mutex implementation using the
5844 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5845 ** before calling sqlite3_initialize() or any other public sqlite3_
5846 ** function that calls sqlite3_initialize().)^
5847 **
5848 ** ^The sqlite3_mutex_alloc() routine allocates a new
5849 ** mutex and returns a pointer to it. ^If it returns NULL
5850 ** that means that a mutex could not be allocated.  ^SQLite
5851 ** will unwind its stack and return an error.  ^(The argument
5852 ** to sqlite3_mutex_alloc() is one of these integer constants:
5853 **
5854 ** <ul>
5855 ** <li>  SQLITE_MUTEX_FAST
5856 ** <li>  SQLITE_MUTEX_RECURSIVE
5857 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5858 ** <li>  SQLITE_MUTEX_STATIC_MEM
5859 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5860 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5861 ** <li>  SQLITE_MUTEX_STATIC_LRU
5862 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5863 ** </ul>)^
5864 **
5865 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5866 ** cause sqlite3_mutex_alloc() to create
5867 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5868 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5869 ** The mutex implementation does not need to make a distinction
5870 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5871 ** not want to.  ^SQLite will only request a recursive mutex in
5872 ** cases where it really needs one.  ^If a faster non-recursive mutex
5873 ** implementation is available on the host platform, the mutex subsystem
5874 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5875 **
5876 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5877 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5878 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5879 ** used by the current version of SQLite.  Future versions of SQLite
5880 ** may add additional static mutexes.  Static mutexes are for internal
5881 ** use by SQLite only.  Applications that use SQLite mutexes should
5882 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5883 ** SQLITE_MUTEX_RECURSIVE.
5884 **
5885 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5886 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5887 ** returns a different mutex on every call.  ^But for the static
5888 ** mutex types, the same mutex is returned on every call that has
5889 ** the same type number.
5890 **
5891 ** ^The sqlite3_mutex_free() routine deallocates a previously
5892 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5893 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5894 ** use when they are deallocated.  Attempting to deallocate a static
5895 ** mutex results in undefined behavior.  ^SQLite never deallocates
5896 ** a static mutex.
5897 **
5898 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5899 ** to enter a mutex.  ^If another thread is already within the mutex,
5900 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5901 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5902 ** upon successful entry.  ^(Mutexes created using
5903 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5904 ** In such cases the,
5905 ** mutex must be exited an equal number of times before another thread
5906 ** can enter.)^  ^(If the same thread tries to enter any other
5907 ** kind of mutex more than once, the behavior is undefined.
5908 ** SQLite will never exhibit
5909 ** such behavior in its own use of mutexes.)^
5910 **
5911 ** ^(Some systems (for example, Windows 95) do not support the operation
5912 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5913 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5914 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5915 **
5916 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5917 ** previously entered by the same thread.   ^(The behavior
5918 ** is undefined if the mutex is not currently entered by the
5919 ** calling thread or is not currently allocated.  SQLite will
5920 ** never do either.)^
5921 **
5922 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5923 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5924 ** behave as no-ops.
5925 **
5926 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5927 */
5928 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5929 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5930 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5931 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5932 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5933 
5934 /*
5935 ** CAPI3REF: Mutex Methods Object
5936 **
5937 ** An instance of this structure defines the low-level routines
5938 ** used to allocate and use mutexes.
5939 **
5940 ** Usually, the default mutex implementations provided by SQLite are
5941 ** sufficient, however the user has the option of substituting a custom
5942 ** implementation for specialized deployments or systems for which SQLite
5943 ** does not provide a suitable implementation. In this case, the user
5944 ** creates and populates an instance of this structure to pass
5945 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5946 ** Additionally, an instance of this structure can be used as an
5947 ** output variable when querying the system for the current mutex
5948 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5949 **
5950 ** ^The xMutexInit method defined by this structure is invoked as
5951 ** part of system initialization by the sqlite3_initialize() function.
5952 ** ^The xMutexInit routine is called by SQLite exactly once for each
5953 ** effective call to [sqlite3_initialize()].
5954 **
5955 ** ^The xMutexEnd method defined by this structure is invoked as
5956 ** part of system shutdown by the sqlite3_shutdown() function. The
5957 ** implementation of this method is expected to release all outstanding
5958 ** resources obtained by the mutex methods implementation, especially
5959 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5960 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5961 **
5962 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5963 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5964 ** xMutexNotheld) implement the following interfaces (respectively):
5965 **
5966 ** <ul>
5967 **   <li>  [sqlite3_mutex_alloc()] </li>
5968 **   <li>  [sqlite3_mutex_free()] </li>
5969 **   <li>  [sqlite3_mutex_enter()] </li>
5970 **   <li>  [sqlite3_mutex_try()] </li>
5971 **   <li>  [sqlite3_mutex_leave()] </li>
5972 **   <li>  [sqlite3_mutex_held()] </li>
5973 **   <li>  [sqlite3_mutex_notheld()] </li>
5974 ** </ul>)^
5975 **
5976 ** The only difference is that the public sqlite3_XXX functions enumerated
5977 ** above silently ignore any invocations that pass a NULL pointer instead
5978 ** of a valid mutex handle. The implementations of the methods defined
5979 ** by this structure are not required to handle this case, the results
5980 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5981 ** (i.e. it is acceptable to provide an implementation that segfaults if
5982 ** it is passed a NULL pointer).
5983 **
5984 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5985 ** invoke xMutexInit() multiple times within the same process and without
5986 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5987 ** xMutexInit() must be no-ops.
5988 **
5989 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5990 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5991 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5992 ** memory allocation for a fast or recursive mutex.
5993 **
5994 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5995 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5996 ** If xMutexInit fails in any way, it is expected to clean up after itself
5997 ** prior to returning.
5998 */
5999 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6000 struct sqlite3_mutex_methods {
6001   int (*xMutexInit)(void);
6002   int (*xMutexEnd)(void);
6003   sqlite3_mutex *(*xMutexAlloc)(int);
6004   void (*xMutexFree)(sqlite3_mutex *);
6005   void (*xMutexEnter)(sqlite3_mutex *);
6006   int (*xMutexTry)(sqlite3_mutex *);
6007   void (*xMutexLeave)(sqlite3_mutex *);
6008   int (*xMutexHeld)(sqlite3_mutex *);
6009   int (*xMutexNotheld)(sqlite3_mutex *);
6010 };
6011 
6012 /*
6013 ** CAPI3REF: Mutex Verification Routines
6014 **
6015 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6016 ** are intended for use inside assert() statements.  ^The SQLite core
6017 ** never uses these routines except inside an assert() and applications
6018 ** are advised to follow the lead of the core.  ^The SQLite core only
6019 ** provides implementations for these routines when it is compiled
6020 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6021 ** are only required to provide these routines if SQLITE_DEBUG is
6022 ** defined and if NDEBUG is not defined.
6023 **
6024 ** ^These routines should return true if the mutex in their argument
6025 ** is held or not held, respectively, by the calling thread.
6026 **
6027 ** ^The implementation is not required to provided versions of these
6028 ** routines that actually work. If the implementation does not provide working
6029 ** versions of these routines, it should at least provide stubs that always
6030 ** return true so that one does not get spurious assertion failures.
6031 **
6032 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6033 ** the routine should return 1.   This seems counter-intuitive since
6034 ** clearly the mutex cannot be held if it does not exist.  But
6035 ** the reason the mutex does not exist is because the build is not
6036 ** using mutexes.  And we do not want the assert() containing the
6037 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6038 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6039 ** interface should also return 1 when given a NULL pointer.
6040 */
6041 #ifndef NDEBUG
6042 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6043 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6044 #endif
6045 
6046 /*
6047 ** CAPI3REF: Mutex Types
6048 **
6049 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6050 ** which is one of these integer constants.
6051 **
6052 ** The set of static mutexes may change from one SQLite release to the
6053 ** next.  Applications that override the built-in mutex logic must be
6054 ** prepared to accommodate additional static mutexes.
6055 */
6056 #define SQLITE_MUTEX_FAST             0
6057 #define SQLITE_MUTEX_RECURSIVE        1
6058 #define SQLITE_MUTEX_STATIC_MASTER    2
6059 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6060 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6061 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6062 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6063 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6064 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6065 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6066 
6067 /*
6068 ** CAPI3REF: Retrieve the mutex for a database connection
6069 **
6070 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6071 ** serializes access to the [database connection] given in the argument
6072 ** when the [threading mode] is Serialized.
6073 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6074 ** routine returns a NULL pointer.
6075 */
6076 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6077 
6078 /*
6079 ** CAPI3REF: Low-Level Control Of Database Files
6080 **
6081 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6082 ** xFileControl method for the [sqlite3_io_methods] object associated
6083 ** with a particular database identified by the second argument. ^The
6084 ** name of the database is "main" for the main database or "temp" for the
6085 ** TEMP database, or the name that appears after the AS keyword for
6086 ** databases that are added using the [ATTACH] SQL command.
6087 ** ^A NULL pointer can be used in place of "main" to refer to the
6088 ** main database file.
6089 ** ^The third and fourth parameters to this routine
6090 ** are passed directly through to the second and third parameters of
6091 ** the xFileControl method.  ^The return value of the xFileControl
6092 ** method becomes the return value of this routine.
6093 **
6094 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6095 ** a pointer to the underlying [sqlite3_file] object to be written into
6096 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6097 ** case is a short-circuit path which does not actually invoke the
6098 ** underlying sqlite3_io_methods.xFileControl method.
6099 **
6100 ** ^If the second parameter (zDbName) does not match the name of any
6101 ** open database file, then SQLITE_ERROR is returned.  ^This error
6102 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6103 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6104 ** also return SQLITE_ERROR.  There is no way to distinguish between
6105 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6106 ** xFileControl method.
6107 **
6108 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6109 */
6110 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6111 
6112 /*
6113 ** CAPI3REF: Testing Interface
6114 **
6115 ** ^The sqlite3_test_control() interface is used to read out internal
6116 ** state of SQLite and to inject faults into SQLite for testing
6117 ** purposes.  ^The first parameter is an operation code that determines
6118 ** the number, meaning, and operation of all subsequent parameters.
6119 **
6120 ** This interface is not for use by applications.  It exists solely
6121 ** for verifying the correct operation of the SQLite library.  Depending
6122 ** on how the SQLite library is compiled, this interface might not exist.
6123 **
6124 ** The details of the operation codes, their meanings, the parameters
6125 ** they take, and what they do are all subject to change without notice.
6126 ** Unlike most of the SQLite API, this function is not guaranteed to
6127 ** operate consistently from one release to the next.
6128 */
6129 SQLITE_API int sqlite3_test_control(int op, ...);
6130 
6131 /*
6132 ** CAPI3REF: Testing Interface Operation Codes
6133 **
6134 ** These constants are the valid operation code parameters used
6135 ** as the first argument to [sqlite3_test_control()].
6136 **
6137 ** These parameters and their meanings are subject to change
6138 ** without notice.  These values are for testing purposes only.
6139 ** Applications should not use any of these parameters or the
6140 ** [sqlite3_test_control()] interface.
6141 */
6142 #define SQLITE_TESTCTRL_FIRST                    5
6143 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6144 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6145 #define SQLITE_TESTCTRL_PRNG_RESET               7
6146 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6147 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6148 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6149 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6150 #define SQLITE_TESTCTRL_ASSERT                  12
6151 #define SQLITE_TESTCTRL_ALWAYS                  13
6152 #define SQLITE_TESTCTRL_RESERVE                 14
6153 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6154 #define SQLITE_TESTCTRL_ISKEYWORD               16
6155 #define SQLITE_TESTCTRL_PGHDRSZ                 17
6156 #define SQLITE_TESTCTRL_SCRATCHMALLOC           18
6157 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         19
6158 #define SQLITE_TESTCTRL_LAST                    19
6159 
6160 /*
6161 ** CAPI3REF: SQLite Runtime Status
6162 **
6163 ** ^This interface is used to retrieve runtime status information
6164 ** about the performance of SQLite, and optionally to reset various
6165 ** highwater marks.  ^The first argument is an integer code for
6166 ** the specific parameter to measure.  ^(Recognized integer codes
6167 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6168 ** ^The current value of the parameter is returned into *pCurrent.
6169 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6170 ** resetFlag is true, then the highest record value is reset after
6171 ** *pHighwater is written.  ^(Some parameters do not record the highest
6172 ** value.  For those parameters
6173 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6174 ** ^(Other parameters record only the highwater mark and not the current
6175 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6176 **
6177 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6178 ** non-zero [error code] on failure.
6179 **
6180 ** This routine is threadsafe but is not atomic.  This routine can be
6181 ** called while other threads are running the same or different SQLite
6182 ** interfaces.  However the values returned in *pCurrent and
6183 ** *pHighwater reflect the status of SQLite at different points in time
6184 ** and it is possible that another thread might change the parameter
6185 ** in between the times when *pCurrent and *pHighwater are written.
6186 **
6187 ** See also: [sqlite3_db_status()]
6188 */
6189 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6190 
6191 
6192 /*
6193 ** CAPI3REF: Status Parameters
6194 ** KEYWORDS: {status parameters}
6195 **
6196 ** These integer constants designate various run-time status parameters
6197 ** that can be returned by [sqlite3_status()].
6198 **
6199 ** <dl>
6200 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6201 ** <dd>This parameter is the current amount of memory checked out
6202 ** using [sqlite3_malloc()], either directly or indirectly.  The
6203 ** figure includes calls made to [sqlite3_malloc()] by the application
6204 ** and internal memory usage by the SQLite library.  Scratch memory
6205 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6206 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6207 ** this parameter.  The amount returned is the sum of the allocation
6208 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6209 **
6210 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6211 ** <dd>This parameter records the largest memory allocation request
6212 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6213 ** internal equivalents).  Only the value returned in the
6214 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6215 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6216 **
6217 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6218 ** <dd>This parameter records the number of separate memory allocations
6219 ** currently checked out.</dd>)^
6220 **
6221 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6222 ** <dd>This parameter returns the number of pages used out of the
6223 ** [pagecache memory allocator] that was configured using
6224 ** [SQLITE_CONFIG_PAGECACHE].  The
6225 ** value returned is in pages, not in bytes.</dd>)^
6226 **
6227 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6228 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6229 ** <dd>This parameter returns the number of bytes of page cache
6230 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6231 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6232 ** returned value includes allocations that overflowed because they
6233 ** where too large (they were larger than the "sz" parameter to
6234 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6235 ** no space was left in the page cache.</dd>)^
6236 **
6237 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6238 ** <dd>This parameter records the largest memory allocation request
6239 ** handed to [pagecache memory allocator].  Only the value returned in the
6240 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6241 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6242 **
6243 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6244 ** <dd>This parameter returns the number of allocations used out of the
6245 ** [scratch memory allocator] configured using
6246 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6247 ** in bytes.  Since a single thread may only have one scratch allocation
6248 ** outstanding at time, this parameter also reports the number of threads
6249 ** using scratch memory at the same time.</dd>)^
6250 **
6251 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6252 ** <dd>This parameter returns the number of bytes of scratch memory
6253 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6254 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6255 ** returned include overflows because the requested allocation was too
6256 ** larger (that is, because the requested allocation was larger than the
6257 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6258 ** slots were available.
6259 ** </dd>)^
6260 **
6261 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6262 ** <dd>This parameter records the largest memory allocation request
6263 ** handed to [scratch memory allocator].  Only the value returned in the
6264 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6265 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6266 **
6267 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6268 ** <dd>This parameter records the deepest parser stack.  It is only
6269 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6270 ** </dl>
6271 **
6272 ** New status parameters may be added from time to time.
6273 */
6274 #define SQLITE_STATUS_MEMORY_USED          0
6275 #define SQLITE_STATUS_PAGECACHE_USED       1
6276 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6277 #define SQLITE_STATUS_SCRATCH_USED         3
6278 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6279 #define SQLITE_STATUS_MALLOC_SIZE          5
6280 #define SQLITE_STATUS_PARSER_STACK         6
6281 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6282 #define SQLITE_STATUS_SCRATCH_SIZE         8
6283 #define SQLITE_STATUS_MALLOC_COUNT         9
6284 
6285 /*
6286 ** CAPI3REF: Database Connection Status
6287 **
6288 ** ^This interface is used to retrieve runtime status information
6289 ** about a single [database connection].  ^The first argument is the
6290 ** database connection object to be interrogated.  ^The second argument
6291 ** is an integer constant, taken from the set of
6292 ** [SQLITE_DBSTATUS options], that
6293 ** determines the parameter to interrogate.  The set of
6294 ** [SQLITE_DBSTATUS options] is likely
6295 ** to grow in future releases of SQLite.
6296 **
6297 ** ^The current value of the requested parameter is written into *pCur
6298 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6299 ** the resetFlg is true, then the highest instantaneous value is
6300 ** reset back down to the current value.
6301 **
6302 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6303 ** non-zero [error code] on failure.
6304 **
6305 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6306 */
6307 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6308 
6309 /*
6310 ** CAPI3REF: Status Parameters for database connections
6311 ** KEYWORDS: {SQLITE_DBSTATUS options}
6312 **
6313 ** These constants are the available integer "verbs" that can be passed as
6314 ** the second argument to the [sqlite3_db_status()] interface.
6315 **
6316 ** New verbs may be added in future releases of SQLite. Existing verbs
6317 ** might be discontinued. Applications should check the return code from
6318 ** [sqlite3_db_status()] to make sure that the call worked.
6319 ** The [sqlite3_db_status()] interface will return a non-zero error code
6320 ** if a discontinued or unsupported verb is invoked.
6321 **
6322 ** <dl>
6323 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6324 ** <dd>This parameter returns the number of lookaside memory slots currently
6325 ** checked out.</dd>)^
6326 **
6327 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6328 ** <dd>This parameter returns the number malloc attempts that were
6329 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6330 ** the current value is always zero.)^
6331 **
6332 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6333 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6334 ** <dd>This parameter returns the number malloc attempts that might have
6335 ** been satisfied using lookaside memory but failed due to the amount of
6336 ** memory requested being larger than the lookaside slot size.
6337 ** Only the high-water value is meaningful;
6338 ** the current value is always zero.)^
6339 **
6340 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6341 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6342 ** <dd>This parameter returns the number malloc attempts that might have
6343 ** been satisfied using lookaside memory but failed due to all lookaside
6344 ** memory already being in use.
6345 ** Only the high-water value is meaningful;
6346 ** the current value is always zero.)^
6347 **
6348 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6349 ** <dd>This parameter returns the approximate number of of bytes of heap
6350 ** memory used by all pager caches associated with the database connection.)^
6351 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6352 **
6353 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6354 ** <dd>This parameter returns the approximate number of of bytes of heap
6355 ** memory used to store the schema for all databases associated
6356 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6357 ** ^The full amount of memory used by the schemas is reported, even if the
6358 ** schema memory is shared with other database connections due to
6359 ** [shared cache mode] being enabled.
6360 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6361 **
6362 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6363 ** <dd>This parameter returns the approximate number of of bytes of heap
6364 ** and lookaside memory used by all prepared statements associated with
6365 ** the database connection.)^
6366 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6367 ** </dd>
6368 ** </dl>
6369 */
6370 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6371 #define SQLITE_DBSTATUS_CACHE_USED           1
6372 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6373 #define SQLITE_DBSTATUS_STMT_USED            3
6374 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6375 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6376 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6377 #define SQLITE_DBSTATUS_MAX                  6   /* Largest defined DBSTATUS */
6378 
6379 
6380 /*
6381 ** CAPI3REF: Prepared Statement Status
6382 **
6383 ** ^(Each prepared statement maintains various
6384 ** [SQLITE_STMTSTATUS counters] that measure the number
6385 ** of times it has performed specific operations.)^  These counters can
6386 ** be used to monitor the performance characteristics of the prepared
6387 ** statements.  For example, if the number of table steps greatly exceeds
6388 ** the number of table searches or result rows, that would tend to indicate
6389 ** that the prepared statement is using a full table scan rather than
6390 ** an index.
6391 **
6392 ** ^(This interface is used to retrieve and reset counter values from
6393 ** a [prepared statement].  The first argument is the prepared statement
6394 ** object to be interrogated.  The second argument
6395 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6396 ** to be interrogated.)^
6397 ** ^The current value of the requested counter is returned.
6398 ** ^If the resetFlg is true, then the counter is reset to zero after this
6399 ** interface call returns.
6400 **
6401 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6402 */
6403 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6404 
6405 /*
6406 ** CAPI3REF: Status Parameters for prepared statements
6407 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6408 **
6409 ** These preprocessor macros define integer codes that name counter
6410 ** values associated with the [sqlite3_stmt_status()] interface.
6411 ** The meanings of the various counters are as follows:
6412 **
6413 ** <dl>
6414 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6415 ** <dd>^This is the number of times that SQLite has stepped forward in
6416 ** a table as part of a full table scan.  Large numbers for this counter
6417 ** may indicate opportunities for performance improvement through
6418 ** careful use of indices.</dd>
6419 **
6420 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6421 ** <dd>^This is the number of sort operations that have occurred.
6422 ** A non-zero value in this counter may indicate an opportunity to
6423 ** improvement performance through careful use of indices.</dd>
6424 **
6425 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6426 ** <dd>^This is the number of rows inserted into transient indices that
6427 ** were created automatically in order to help joins run faster.
6428 ** A non-zero value in this counter may indicate an opportunity to
6429 ** improvement performance by adding permanent indices that do not
6430 ** need to be reinitialized each time the statement is run.</dd>
6431 **
6432 ** </dl>
6433 */
6434 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6435 #define SQLITE_STMTSTATUS_SORT              2
6436 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6437 
6438 /*
6439 ** CAPI3REF: Custom Page Cache Object
6440 **
6441 ** The sqlite3_pcache type is opaque.  It is implemented by
6442 ** the pluggable module.  The SQLite core has no knowledge of
6443 ** its size or internal structure and never deals with the
6444 ** sqlite3_pcache object except by holding and passing pointers
6445 ** to the object.
6446 **
6447 ** See [sqlite3_pcache_methods] for additional information.
6448 */
6449 typedef struct sqlite3_pcache sqlite3_pcache;
6450 
6451 /*
6452 ** CAPI3REF: Application Defined Page Cache.
6453 ** KEYWORDS: {page cache}
6454 **
6455 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
6456 ** register an alternative page cache implementation by passing in an
6457 ** instance of the sqlite3_pcache_methods structure.)^
6458 ** In many applications, most of the heap memory allocated by
6459 ** SQLite is used for the page cache.
6460 ** By implementing a
6461 ** custom page cache using this API, an application can better control
6462 ** the amount of memory consumed by SQLite, the way in which
6463 ** that memory is allocated and released, and the policies used to
6464 ** determine exactly which parts of a database file are cached and for
6465 ** how long.
6466 **
6467 ** The alternative page cache mechanism is an
6468 ** extreme measure that is only needed by the most demanding applications.
6469 ** The built-in page cache is recommended for most uses.
6470 **
6471 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
6472 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6473 ** the application may discard the parameter after the call to
6474 ** [sqlite3_config()] returns.)^
6475 **
6476 ** [[the xInit() page cache method]]
6477 ** ^(The xInit() method is called once for each effective
6478 ** call to [sqlite3_initialize()])^
6479 ** (usually only once during the lifetime of the process). ^(The xInit()
6480 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
6481 ** The intent of the xInit() method is to set up global data structures
6482 ** required by the custom page cache implementation.
6483 ** ^(If the xInit() method is NULL, then the
6484 ** built-in default page cache is used instead of the application defined
6485 ** page cache.)^
6486 **
6487 ** [[the xShutdown() page cache method]]
6488 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6489 ** It can be used to clean up
6490 ** any outstanding resources before process shutdown, if required.
6491 ** ^The xShutdown() method may be NULL.
6492 **
6493 ** ^SQLite automatically serializes calls to the xInit method,
6494 ** so the xInit method need not be threadsafe.  ^The
6495 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6496 ** not need to be threadsafe either.  All other methods must be threadsafe
6497 ** in multithreaded applications.
6498 **
6499 ** ^SQLite will never invoke xInit() more than once without an intervening
6500 ** call to xShutdown().
6501 **
6502 ** [[the xCreate() page cache methods]]
6503 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6504 ** SQLite will typically create one cache instance for each open database file,
6505 ** though this is not guaranteed. ^The
6506 ** first parameter, szPage, is the size in bytes of the pages that must
6507 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
6508 ** will the page size of the database file that is to be cached plus an
6509 ** increment (here called "R") of less than 250.  SQLite will use the
6510 ** extra R bytes on each page to store metadata about the underlying
6511 ** database page on disk.  The value of R depends
6512 ** on the SQLite version, the target platform, and how SQLite was compiled.
6513 ** ^(R is constant for a particular build of SQLite. Except, there are two
6514 ** distinct values of R when SQLite is compiled with the proprietary
6515 ** ZIPVFS extension.)^  ^The second argument to
6516 ** xCreate(), bPurgeable, is true if the cache being created will
6517 ** be used to cache database pages of a file stored on disk, or
6518 ** false if it is used for an in-memory database. The cache implementation
6519 ** does not have to do anything special based with the value of bPurgeable;
6520 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6521 ** never invoke xUnpin() except to deliberately delete a page.
6522 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6523 ** false will always have the "discard" flag set to true.
6524 ** ^Hence, a cache created with bPurgeable false will
6525 ** never contain any unpinned pages.
6526 **
6527 ** [[the xCachesize() page cache method]]
6528 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6529 ** suggested maximum cache-size (number of pages stored by) the cache
6530 ** instance passed as the first argument. This is the value configured using
6531 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6532 ** parameter, the implementation is not required to do anything with this
6533 ** value; it is advisory only.
6534 **
6535 ** [[the xPagecount() page cache methods]]
6536 ** The xPagecount() method must return the number of pages currently
6537 ** stored in the cache, both pinned and unpinned.
6538 **
6539 ** [[the xFetch() page cache methods]]
6540 ** The xFetch() method locates a page in the cache and returns a pointer to
6541 ** the page, or a NULL pointer.
6542 ** A "page", in this context, means a buffer of szPage bytes aligned at an
6543 ** 8-byte boundary. The page to be fetched is determined by the key. ^The
6544 ** minimum key value is 1.  After it has been retrieved using xFetch, the page
6545 ** is considered to be "pinned".
6546 **
6547 ** If the requested page is already in the page cache, then the page cache
6548 ** implementation must return a pointer to the page buffer with its content
6549 ** intact.  If the requested page is not already in the cache, then the
6550 ** cache implementation should use the value of the createFlag
6551 ** parameter to help it determined what action to take:
6552 **
6553 ** <table border=1 width=85% align=center>
6554 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
6555 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6556 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6557 **                 Otherwise return NULL.
6558 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6559 **                 NULL if allocating a new page is effectively impossible.
6560 ** </table>
6561 **
6562 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6563 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6564 ** failed.)^  In between the to xFetch() calls, SQLite may
6565 ** attempt to unpin one or more cache pages by spilling the content of
6566 ** pinned pages to disk and synching the operating system disk cache.
6567 **
6568 ** [[the xUnpin() page cache method]]
6569 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6570 ** as its second argument.  If the third parameter, discard, is non-zero,
6571 ** then the page must be evicted from the cache.
6572 ** ^If the discard parameter is
6573 ** zero, then the page may be discarded or retained at the discretion of
6574 ** page cache implementation. ^The page cache implementation
6575 ** may choose to evict unpinned pages at any time.
6576 **
6577 ** The cache must not perform any reference counting. A single
6578 ** call to xUnpin() unpins the page regardless of the number of prior calls
6579 ** to xFetch().
6580 **
6581 ** [[the xRekey() page cache methods]]
6582 ** The xRekey() method is used to change the key value associated with the
6583 ** page passed as the second argument. If the cache
6584 ** previously contains an entry associated with newKey, it must be
6585 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6586 ** to be pinned.
6587 **
6588 ** When SQLite calls the xTruncate() method, the cache must discard all
6589 ** existing cache entries with page numbers (keys) greater than or equal
6590 ** to the value of the iLimit parameter passed to xTruncate(). If any
6591 ** of these pages are pinned, they are implicitly unpinned, meaning that
6592 ** they can be safely discarded.
6593 **
6594 ** [[the xDestroy() page cache method]]
6595 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6596 ** All resources associated with the specified cache should be freed. ^After
6597 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6598 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
6599 ** functions.
6600 */
6601 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6602 struct sqlite3_pcache_methods {
6603   void *pArg;
6604   int (*xInit)(void*);
6605   void (*xShutdown)(void*);
6606   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6607   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6608   int (*xPagecount)(sqlite3_pcache*);
6609   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6610   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6611   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6612   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6613   void (*xDestroy)(sqlite3_pcache*);
6614 };
6615 
6616 /*
6617 ** CAPI3REF: Online Backup Object
6618 **
6619 ** The sqlite3_backup object records state information about an ongoing
6620 ** online backup operation.  ^The sqlite3_backup object is created by
6621 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
6622 ** [sqlite3_backup_finish()].
6623 **
6624 ** See Also: [Using the SQLite Online Backup API]
6625 */
6626 typedef struct sqlite3_backup sqlite3_backup;
6627 
6628 /*
6629 ** CAPI3REF: Online Backup API.
6630 **
6631 ** The backup API copies the content of one database into another.
6632 ** It is useful either for creating backups of databases or
6633 ** for copying in-memory databases to or from persistent files.
6634 **
6635 ** See Also: [Using the SQLite Online Backup API]
6636 **
6637 ** ^SQLite holds a write transaction open on the destination database file
6638 ** for the duration of the backup operation.
6639 ** ^The source database is read-locked only while it is being read;
6640 ** it is not locked continuously for the entire backup operation.
6641 ** ^Thus, the backup may be performed on a live source database without
6642 ** preventing other database connections from
6643 ** reading or writing to the source database while the backup is underway.
6644 **
6645 ** ^(To perform a backup operation:
6646 **   <ol>
6647 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6648 **         backup,
6649 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6650 **         the data between the two databases, and finally
6651 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6652 **         associated with the backup operation.
6653 **   </ol>)^
6654 ** There should be exactly one call to sqlite3_backup_finish() for each
6655 ** successful call to sqlite3_backup_init().
6656 **
6657 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6658 **
6659 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6660 ** [database connection] associated with the destination database
6661 ** and the database name, respectively.
6662 ** ^The database name is "main" for the main database, "temp" for the
6663 ** temporary database, or the name specified after the AS keyword in
6664 ** an [ATTACH] statement for an attached database.
6665 ** ^The S and M arguments passed to
6666 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6667 ** and database name of the source database, respectively.
6668 ** ^The source and destination [database connections] (parameters S and D)
6669 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6670 ** an error.
6671 **
6672 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6673 ** returned and an error code and error message are stored in the
6674 ** destination [database connection] D.
6675 ** ^The error code and message for the failed call to sqlite3_backup_init()
6676 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6677 ** [sqlite3_errmsg16()] functions.
6678 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
6679 ** [sqlite3_backup] object.
6680 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6681 ** sqlite3_backup_finish() functions to perform the specified backup
6682 ** operation.
6683 **
6684 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6685 **
6686 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6687 ** the source and destination databases specified by [sqlite3_backup] object B.
6688 ** ^If N is negative, all remaining source pages are copied.
6689 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6690 ** are still more pages to be copied, then the function returns [SQLITE_OK].
6691 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6692 ** from source to destination, then it returns [SQLITE_DONE].
6693 ** ^If an error occurs while running sqlite3_backup_step(B,N),
6694 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
6695 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6696 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6697 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6698 **
6699 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6700 ** <ol>
6701 ** <li> the destination database was opened read-only, or
6702 ** <li> the destination database is using write-ahead-log journaling
6703 ** and the destination and source page sizes differ, or
6704 ** <li> the destination database is an in-memory database and the
6705 ** destination and source page sizes differ.
6706 ** </ol>)^
6707 **
6708 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6709 ** the [sqlite3_busy_handler | busy-handler function]
6710 ** is invoked (if one is specified). ^If the
6711 ** busy-handler returns non-zero before the lock is available, then
6712 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6713 ** sqlite3_backup_step() can be retried later. ^If the source
6714 ** [database connection]
6715 ** is being used to write to the source database when sqlite3_backup_step()
6716 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6717 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
6718 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6719 ** [SQLITE_READONLY] is returned, then
6720 ** there is no point in retrying the call to sqlite3_backup_step(). These
6721 ** errors are considered fatal.)^  The application must accept
6722 ** that the backup operation has failed and pass the backup operation handle
6723 ** to the sqlite3_backup_finish() to release associated resources.
6724 **
6725 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6726 ** on the destination file. ^The exclusive lock is not released until either
6727 ** sqlite3_backup_finish() is called or the backup operation is complete
6728 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6729 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
6730 ** lasts for the duration of the sqlite3_backup_step() call.
6731 ** ^Because the source database is not locked between calls to
6732 ** sqlite3_backup_step(), the source database may be modified mid-way
6733 ** through the backup process.  ^If the source database is modified by an
6734 ** external process or via a database connection other than the one being
6735 ** used by the backup operation, then the backup will be automatically
6736 ** restarted by the next call to sqlite3_backup_step(). ^If the source
6737 ** database is modified by the using the same database connection as is used
6738 ** by the backup operation, then the backup database is automatically
6739 ** updated at the same time.
6740 **
6741 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6742 **
6743 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6744 ** application wishes to abandon the backup operation, the application
6745 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6746 ** ^The sqlite3_backup_finish() interfaces releases all
6747 ** resources associated with the [sqlite3_backup] object.
6748 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6749 ** active write-transaction on the destination database is rolled back.
6750 ** The [sqlite3_backup] object is invalid
6751 ** and may not be used following a call to sqlite3_backup_finish().
6752 **
6753 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6754 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6755 ** sqlite3_backup_step() completed.
6756 ** ^If an out-of-memory condition or IO error occurred during any prior
6757 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6758 ** sqlite3_backup_finish() returns the corresponding [error code].
6759 **
6760 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6761 ** is not a permanent error and does not affect the return value of
6762 ** sqlite3_backup_finish().
6763 **
6764 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
6765 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
6766 **
6767 ** ^Each call to sqlite3_backup_step() sets two values inside
6768 ** the [sqlite3_backup] object: the number of pages still to be backed
6769 ** up and the total number of pages in the source database file.
6770 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6771 ** retrieve these two values, respectively.
6772 **
6773 ** ^The values returned by these functions are only updated by
6774 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6775 ** operation, then the values are not updated to account for any extra
6776 ** pages that need to be updated or the size of the source database file
6777 ** changing.
6778 **
6779 ** <b>Concurrent Usage of Database Handles</b>
6780 **
6781 ** ^The source [database connection] may be used by the application for other
6782 ** purposes while a backup operation is underway or being initialized.
6783 ** ^If SQLite is compiled and configured to support threadsafe database
6784 ** connections, then the source database connection may be used concurrently
6785 ** from within other threads.
6786 **
6787 ** However, the application must guarantee that the destination
6788 ** [database connection] is not passed to any other API (by any thread) after
6789 ** sqlite3_backup_init() is called and before the corresponding call to
6790 ** sqlite3_backup_finish().  SQLite does not currently check to see
6791 ** if the application incorrectly accesses the destination [database connection]
6792 ** and so no error code is reported, but the operations may malfunction
6793 ** nevertheless.  Use of the destination database connection while a
6794 ** backup is in progress might also also cause a mutex deadlock.
6795 **
6796 ** If running in [shared cache mode], the application must
6797 ** guarantee that the shared cache used by the destination database
6798 ** is not accessed while the backup is running. In practice this means
6799 ** that the application must guarantee that the disk file being
6800 ** backed up to is not accessed by any connection within the process,
6801 ** not just the specific connection that was passed to sqlite3_backup_init().
6802 **
6803 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6804 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6805 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6806 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6807 ** same time as another thread is invoking sqlite3_backup_step() it is
6808 ** possible that they return invalid values.
6809 */
6810 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6811   sqlite3 *pDest,                        /* Destination database handle */
6812   const char *zDestName,                 /* Destination database name */
6813   sqlite3 *pSource,                      /* Source database handle */
6814   const char *zSourceName                /* Source database name */
6815 );
6816 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6817 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6818 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6819 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6820 
6821 /*
6822 ** CAPI3REF: Unlock Notification
6823 **
6824 ** ^When running in shared-cache mode, a database operation may fail with
6825 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6826 ** individual tables within the shared-cache cannot be obtained. See
6827 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6828 ** ^This API may be used to register a callback that SQLite will invoke
6829 ** when the connection currently holding the required lock relinquishes it.
6830 ** ^This API is only available if the library was compiled with the
6831 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6832 **
6833 ** See Also: [Using the SQLite Unlock Notification Feature].
6834 **
6835 ** ^Shared-cache locks are released when a database connection concludes
6836 ** its current transaction, either by committing it or rolling it back.
6837 **
6838 ** ^When a connection (known as the blocked connection) fails to obtain a
6839 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6840 ** identity of the database connection (the blocking connection) that
6841 ** has locked the required resource is stored internally. ^After an
6842 ** application receives an SQLITE_LOCKED error, it may call the
6843 ** sqlite3_unlock_notify() method with the blocked connection handle as
6844 ** the first argument to register for a callback that will be invoked
6845 ** when the blocking connections current transaction is concluded. ^The
6846 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6847 ** call that concludes the blocking connections transaction.
6848 **
6849 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6850 ** there is a chance that the blocking connection will have already
6851 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6852 ** If this happens, then the specified callback is invoked immediately,
6853 ** from within the call to sqlite3_unlock_notify().)^
6854 **
6855 ** ^If the blocked connection is attempting to obtain a write-lock on a
6856 ** shared-cache table, and more than one other connection currently holds
6857 ** a read-lock on the same table, then SQLite arbitrarily selects one of
6858 ** the other connections to use as the blocking connection.
6859 **
6860 ** ^(There may be at most one unlock-notify callback registered by a
6861 ** blocked connection. If sqlite3_unlock_notify() is called when the
6862 ** blocked connection already has a registered unlock-notify callback,
6863 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6864 ** called with a NULL pointer as its second argument, then any existing
6865 ** unlock-notify callback is canceled. ^The blocked connections
6866 ** unlock-notify callback may also be canceled by closing the blocked
6867 ** connection using [sqlite3_close()].
6868 **
6869 ** The unlock-notify callback is not reentrant. If an application invokes
6870 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6871 ** crash or deadlock may be the result.
6872 **
6873 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6874 ** returns SQLITE_OK.
6875 **
6876 ** <b>Callback Invocation Details</b>
6877 **
6878 ** When an unlock-notify callback is registered, the application provides a
6879 ** single void* pointer that is passed to the callback when it is invoked.
6880 ** However, the signature of the callback function allows SQLite to pass
6881 ** it an array of void* context pointers. The first argument passed to
6882 ** an unlock-notify callback is a pointer to an array of void* pointers,
6883 ** and the second is the number of entries in the array.
6884 **
6885 ** When a blocking connections transaction is concluded, there may be
6886 ** more than one blocked connection that has registered for an unlock-notify
6887 ** callback. ^If two or more such blocked connections have specified the
6888 ** same callback function, then instead of invoking the callback function
6889 ** multiple times, it is invoked once with the set of void* context pointers
6890 ** specified by the blocked connections bundled together into an array.
6891 ** This gives the application an opportunity to prioritize any actions
6892 ** related to the set of unblocked database connections.
6893 **
6894 ** <b>Deadlock Detection</b>
6895 **
6896 ** Assuming that after registering for an unlock-notify callback a
6897 ** database waits for the callback to be issued before taking any further
6898 ** action (a reasonable assumption), then using this API may cause the
6899 ** application to deadlock. For example, if connection X is waiting for
6900 ** connection Y's transaction to be concluded, and similarly connection
6901 ** Y is waiting on connection X's transaction, then neither connection
6902 ** will proceed and the system may remain deadlocked indefinitely.
6903 **
6904 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6905 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6906 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6907 ** unlock-notify callback is registered. The system is said to be in
6908 ** a deadlocked state if connection A has registered for an unlock-notify
6909 ** callback on the conclusion of connection B's transaction, and connection
6910 ** B has itself registered for an unlock-notify callback when connection
6911 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6912 ** the system is also considered to be deadlocked if connection B has
6913 ** registered for an unlock-notify callback on the conclusion of connection
6914 ** C's transaction, where connection C is waiting on connection A. ^Any
6915 ** number of levels of indirection are allowed.
6916 **
6917 ** <b>The "DROP TABLE" Exception</b>
6918 **
6919 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6920 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6921 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6922 ** SQLite checks if there are any currently executing SELECT statements
6923 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6924 ** returned. In this case there is no "blocking connection", so invoking
6925 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6926 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6927 ** or "DROP INDEX" query, an infinite loop might be the result.
6928 **
6929 ** One way around this problem is to check the extended error code returned
6930 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6931 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6932 ** the special "DROP TABLE/INDEX" case, the extended error code is just
6933 ** SQLITE_LOCKED.)^
6934 */
6935 SQLITE_API int sqlite3_unlock_notify(
6936   sqlite3 *pBlocked,                          /* Waiting connection */
6937   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6938   void *pNotifyArg                            /* Argument to pass to xNotify */
6939 );
6940 
6941 
6942 /*
6943 ** CAPI3REF: String Comparison
6944 **
6945 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6946 ** compare the contents of two buffers containing UTF-8 strings in a
6947 ** case-independent fashion, using the same definition of case independence
6948 ** that SQLite uses internally when comparing identifiers.
6949 */
6950 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6951 
6952 /*
6953 ** CAPI3REF: Error Logging Interface
6954 **
6955 ** ^The [sqlite3_log()] interface writes a message into the error log
6956 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6957 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6958 ** used with [sqlite3_snprintf()] to generate the final output string.
6959 **
6960 ** The sqlite3_log() interface is intended for use by extensions such as
6961 ** virtual tables, collating functions, and SQL functions.  While there is
6962 ** nothing to prevent an application from calling sqlite3_log(), doing so
6963 ** is considered bad form.
6964 **
6965 ** The zFormat string must not be NULL.
6966 **
6967 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6968 ** will not use dynamically allocated memory.  The log message is stored in
6969 ** a fixed-length buffer on the stack.  If the log message is longer than
6970 ** a few hundred characters, it will be truncated to the length of the
6971 ** buffer.
6972 */
6973 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6974 
6975 /*
6976 ** CAPI3REF: Write-Ahead Log Commit Hook
6977 **
6978 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
6979 ** will be invoked each time a database connection commits data to a
6980 ** [write-ahead log] (i.e. whenever a transaction is committed in
6981 ** [journal_mode | journal_mode=WAL mode]).
6982 **
6983 ** ^The callback is invoked by SQLite after the commit has taken place and
6984 ** the associated write-lock on the database released, so the implementation
6985 ** may read, write or [checkpoint] the database as required.
6986 **
6987 ** ^The first parameter passed to the callback function when it is invoked
6988 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
6989 ** registering the callback. ^The second is a copy of the database handle.
6990 ** ^The third parameter is the name of the database that was written to -
6991 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
6992 ** is the number of pages currently in the write-ahead log file,
6993 ** including those that were just committed.
6994 **
6995 ** The callback function should normally return [SQLITE_OK].  ^If an error
6996 ** code is returned, that error will propagate back up through the
6997 ** SQLite code base to cause the statement that provoked the callback
6998 ** to report an error, though the commit will have still occurred. If the
6999 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7000 ** that does not correspond to any valid SQLite error code, the results
7001 ** are undefined.
7002 **
7003 ** A single database handle may have at most a single write-ahead log callback
7004 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7005 ** previously registered write-ahead log callback. ^Note that the
7006 ** [sqlite3_wal_autocheckpoint()] interface and the
7007 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7008 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7009 */
7010 SQLITE_API void *sqlite3_wal_hook(
7011   sqlite3*,
7012   int(*)(void *,sqlite3*,const char*,int),
7013   void*
7014 );
7015 
7016 /*
7017 ** CAPI3REF: Configure an auto-checkpoint
7018 **
7019 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7020 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7021 ** to automatically [checkpoint]
7022 ** after committing a transaction if there are N or
7023 ** more frames in the [write-ahead log] file.  ^Passing zero or
7024 ** a negative value as the nFrame parameter disables automatic
7025 ** checkpoints entirely.
7026 **
7027 ** ^The callback registered by this function replaces any existing callback
7028 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7029 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7030 ** configured by this function.
7031 **
7032 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7033 ** from SQL.
7034 **
7035 ** ^Every new [database connection] defaults to having the auto-checkpoint
7036 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7037 ** pages.  The use of this interface
7038 ** is only necessary if the default setting is found to be suboptimal
7039 ** for a particular application.
7040 */
7041 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7042 
7043 /*
7044 ** CAPI3REF: Checkpoint a database
7045 **
7046 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7047 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7048 ** empty string, then a checkpoint is run on all databases of
7049 ** connection D.  ^If the database connection D is not in
7050 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7051 **
7052 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7053 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7054 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7055 ** run whenever the WAL reaches a certain size threshold.
7056 **
7057 ** See also: [sqlite3_wal_checkpoint_v2()]
7058 */
7059 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7060 
7061 /*
7062 ** CAPI3REF: Checkpoint a database
7063 **
7064 ** Run a checkpoint operation on WAL database zDb attached to database
7065 ** handle db. The specific operation is determined by the value of the
7066 ** eMode parameter:
7067 **
7068 ** <dl>
7069 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7070 **   Checkpoint as many frames as possible without waiting for any database
7071 **   readers or writers to finish. Sync the db file if all frames in the log
7072 **   are checkpointed. This mode is the same as calling
7073 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7074 **
7075 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7076 **   This mode blocks (calls the busy-handler callback) until there is no
7077 **   database writer and all readers are reading from the most recent database
7078 **   snapshot. It then checkpoints all frames in the log file and syncs the
7079 **   database file. This call blocks database writers while it is running,
7080 **   but not database readers.
7081 **
7082 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7083 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7084 **   checkpointing the log file it blocks (calls the busy-handler callback)
7085 **   until all readers are reading from the database file only. This ensures
7086 **   that the next client to write to the database file restarts the log file
7087 **   from the beginning. This call blocks database writers while it is running,
7088 **   but not database readers.
7089 ** </dl>
7090 **
7091 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7092 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7093 ** the total number of checkpointed frames (including any that were already
7094 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7095 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7096 ** If no values are available because of an error, they are both set to -1
7097 ** before returning to communicate this to the caller.
7098 **
7099 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7100 ** any other process is running a checkpoint operation at the same time, the
7101 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7102 ** busy-handler configured, it will not be invoked in this case.
7103 **
7104 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7105 ** "writer" lock on the database file. If the writer lock cannot be obtained
7106 ** immediately, and a busy-handler is configured, it is invoked and the writer
7107 ** lock retried until either the busy-handler returns 0 or the lock is
7108 ** successfully obtained. The busy-handler is also invoked while waiting for
7109 ** database readers as described above. If the busy-handler returns 0 before
7110 ** the writer lock is obtained or while waiting for database readers, the
7111 ** checkpoint operation proceeds from that point in the same way as
7112 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7113 ** without blocking any further. SQLITE_BUSY is returned in this case.
7114 **
7115 ** If parameter zDb is NULL or points to a zero length string, then the
7116 ** specified operation is attempted on all WAL databases. In this case the
7117 ** values written to output parameters *pnLog and *pnCkpt are undefined. If
7118 ** an SQLITE_BUSY error is encountered when processing one or more of the
7119 ** attached WAL databases, the operation is still attempted on any remaining
7120 ** attached databases and SQLITE_BUSY is returned to the caller. If any other
7121 ** error occurs while processing an attached database, processing is abandoned
7122 ** and the error code returned to the caller immediately. If no error
7123 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7124 ** databases, SQLITE_OK is returned.
7125 **
7126 ** If database zDb is the name of an attached database that is not in WAL
7127 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7128 ** zDb is not NULL (or a zero length string) and is not the name of any
7129 ** attached database, SQLITE_ERROR is returned to the caller.
7130 */
7131 SQLITE_API int sqlite3_wal_checkpoint_v2(
7132   sqlite3 *db,                    /* Database handle */
7133   const char *zDb,                /* Name of attached database (or NULL) */
7134   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7135   int *pnLog,                     /* OUT: Size of WAL log in frames */
7136   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7137 );
7138 
7139 /*
7140 ** CAPI3REF: Checkpoint operation parameters
7141 **
7142 ** These constants can be used as the 3rd parameter to
7143 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7144 ** documentation for additional information about the meaning and use of
7145 ** each of these values.
7146 */
7147 #define SQLITE_CHECKPOINT_PASSIVE 0
7148 #define SQLITE_CHECKPOINT_FULL    1
7149 #define SQLITE_CHECKPOINT_RESTART 2
7150 
7151 /*
7152 ** CAPI3REF: Virtual Table Interface Configuration
7153 **
7154 ** This function may be called by either the [xConnect] or [xCreate] method
7155 ** of a [virtual table] implementation to configure
7156 ** various facets of the virtual table interface.
7157 **
7158 ** If this interface is invoked outside the context of an xConnect or
7159 ** xCreate virtual table method then the behavior is undefined.
7160 **
7161 ** At present, there is only one option that may be configured using
7162 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7163 ** may be added in the future.
7164 */
7165 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7166 
7167 /*
7168 ** CAPI3REF: Virtual Table Configuration Options
7169 **
7170 ** These macros define the various options to the
7171 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7172 ** can use to customize and optimize their behavior.
7173 **
7174 ** <dl>
7175 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7176 ** <dd>Calls of the form
7177 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7178 ** where X is an integer.  If X is zero, then the [virtual table] whose
7179 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7180 ** support constraints.  In this configuration (which is the default) if
7181 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7182 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7183 ** specified as part of the users SQL statement, regardless of the actual
7184 ** ON CONFLICT mode specified.
7185 **
7186 ** If X is non-zero, then the virtual table implementation guarantees
7187 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7188 ** any modifications to internal or persistent data structures have been made.
7189 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7190 ** is able to roll back a statement or database transaction, and abandon
7191 ** or continue processing the current SQL statement as appropriate.
7192 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7193 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7194 ** had been ABORT.
7195 **
7196 ** Virtual table implementations that are required to handle OR REPLACE
7197 ** must do so within the [xUpdate] method. If a call to the
7198 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7199 ** CONFLICT policy is REPLACE, the virtual table implementation should
7200 ** silently replace the appropriate rows within the xUpdate callback and
7201 ** return SQLITE_OK. Or, if this is not possible, it may return
7202 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7203 ** constraint handling.
7204 ** </dl>
7205 */
7206 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7207 
7208 /*
7209 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7210 **
7211 ** This function may only be called from within a call to the [xUpdate] method
7212 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7213 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7214 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7215 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7216 ** [virtual table].
7217 */
7218 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7219 
7220 /*
7221 ** CAPI3REF: Conflict resolution modes
7222 **
7223 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7224 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7225 ** is for the SQL statement being evaluated.
7226 **
7227 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7228 ** return value from the [sqlite3_set_authorizer()] callback and that
7229 ** [SQLITE_ABORT] is also a [result code].
7230 */
7231 #define SQLITE_ROLLBACK 1
7232 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7233 #define SQLITE_FAIL     3
7234 /* #define SQLITE_ABORT 4  // Also an error code */
7235 #define SQLITE_REPLACE  5
7236 
7237 
7238 
7239 /*
7240 ** Undo the hack that converts floating point types to integer for
7241 ** builds on processors without floating point support.
7242 */
7243 #ifdef SQLITE_OMIT_FLOATING_POINT
7244 # undef double
7245 #endif
7246 
7247 #if 0
7248 }  /* End of the 'extern "C"' block */
7249 #endif
7250 #endif
7251 
7252 /*
7253 ** 2010 August 30
7254 **
7255 ** The author disclaims copyright to this source code.  In place of
7256 ** a legal notice, here is a blessing:
7257 **
7258 **    May you do good and not evil.
7259 **    May you find forgiveness for yourself and forgive others.
7260 **    May you share freely, never taking more than you give.
7261 **
7262 *************************************************************************
7263 */
7264 
7265 #ifndef _SQLITE3RTREE_H_
7266 #define _SQLITE3RTREE_H_
7267 
7268 
7269 #if 0
7270 extern "C" {
7271 #endif
7272 
7273 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7274 
7275 /*
7276 ** Register a geometry callback named zGeom that can be used as part of an
7277 ** R-Tree geometry query as follows:
7278 **
7279 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7280 */
7281 SQLITE_API int sqlite3_rtree_geometry_callback(
7282   sqlite3 *db,
7283   const char *zGeom,
7284   int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7285   void *pContext
7286 );
7287 
7288 
7289 /*
7290 ** A pointer to a structure of the following type is passed as the first
7291 ** argument to callbacks registered using rtree_geometry_callback().
7292 */
7293 struct sqlite3_rtree_geometry {
7294   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7295   int nParam;                     /* Size of array aParam[] */
7296   double *aParam;                 /* Parameters passed to SQL geom function */
7297   void *pUser;                    /* Callback implementation user data */
7298   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7299 };
7300 
7301 
7302 #if 0
7303 }  /* end of the 'extern "C"' block */
7304 #endif
7305 
7306 #endif  /* ifndef _SQLITE3RTREE_H_ */
7307 
7308 
7309 /************** End of sqlite3.h *********************************************/
7310 /************** Continuing where we left off in sqliteInt.h ******************/
7311 /************** Include hash.h in the middle of sqliteInt.h ******************/
7312 /************** Begin file hash.h ********************************************/
7313 /*
7314 ** 2001 September 22
7315 **
7316 ** The author disclaims copyright to this source code.  In place of
7317 ** a legal notice, here is a blessing:
7318 **
7319 **    May you do good and not evil.
7320 **    May you find forgiveness for yourself and forgive others.
7321 **    May you share freely, never taking more than you give.
7322 **
7323 *************************************************************************
7324 ** This is the header file for the generic hash-table implemenation
7325 ** used in SQLite.
7326 */
7327 #ifndef _SQLITE_HASH_H_
7328 #define _SQLITE_HASH_H_
7329 
7330 /* Forward declarations of structures. */
7331 typedef struct Hash Hash;
7332 typedef struct HashElem HashElem;
7333 
7334 /* A complete hash table is an instance of the following structure.
7335 ** The internals of this structure are intended to be opaque -- client
7336 ** code should not attempt to access or modify the fields of this structure
7337 ** directly.  Change this structure only by using the routines below.
7338 ** However, some of the "procedures" and "functions" for modifying and
7339 ** accessing this structure are really macros, so we can't really make
7340 ** this structure opaque.
7341 **
7342 ** All elements of the hash table are on a single doubly-linked list.
7343 ** Hash.first points to the head of this list.
7344 **
7345 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7346 ** the global doubly-linked list.  The contents of the bucket are the
7347 ** element pointed to plus the next _ht.count-1 elements in the list.
7348 **
7349 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7350 ** by a linear search of the global list.  For small tables, the
7351 ** Hash.ht table is never allocated because if there are few elements
7352 ** in the table, it is faster to do a linear search than to manage
7353 ** the hash table.
7354 */
7355 struct Hash {
7356   unsigned int htsize;      /* Number of buckets in the hash table */
7357   unsigned int count;       /* Number of entries in this table */
7358   HashElem *first;          /* The first element of the array */
7359   struct _ht {              /* the hash table */
7360     int count;                 /* Number of entries with this hash */
7361     HashElem *chain;           /* Pointer to first entry with this hash */
7362   } *ht;
7363 };
7364 
7365 /* Each element in the hash table is an instance of the following
7366 ** structure.  All elements are stored on a single doubly-linked list.
7367 **
7368 ** Again, this structure is intended to be opaque, but it can't really
7369 ** be opaque because it is used by macros.
7370 */
7371 struct HashElem {
7372   HashElem *next, *prev;       /* Next and previous elements in the table */
7373   void *data;                  /* Data associated with this element */
7374   const char *pKey; int nKey;  /* Key associated with this element */
7375 };
7376 
7377 /*
7378 ** Access routines.  To delete, insert a NULL pointer.
7379 */
7380 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7381 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7382 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7383 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7384 
7385 /*
7386 ** Macros for looping over all elements of a hash table.  The idiom is
7387 ** like this:
7388 **
7389 **   Hash h;
7390 **   HashElem *p;
7391 **   ...
7392 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7393 **     SomeStructure *pData = sqliteHashData(p);
7394 **     // do something with pData
7395 **   }
7396 */
7397 #define sqliteHashFirst(H)  ((H)->first)
7398 #define sqliteHashNext(E)   ((E)->next)
7399 #define sqliteHashData(E)   ((E)->data)
7400 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7401 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7402 
7403 /*
7404 ** Number of entries in a hash table
7405 */
7406 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7407 
7408 #endif /* _SQLITE_HASH_H_ */
7409 
7410 /************** End of hash.h ************************************************/
7411 /************** Continuing where we left off in sqliteInt.h ******************/
7412 /************** Include parse.h in the middle of sqliteInt.h *****************/
7413 /************** Begin file parse.h *******************************************/
7414 #define TK_SEMI                            1
7415 #define TK_EXPLAIN                         2
7416 #define TK_QUERY                           3
7417 #define TK_PLAN                            4
7418 #define TK_BEGIN                           5
7419 #define TK_TRANSACTION                     6
7420 #define TK_DEFERRED                        7
7421 #define TK_IMMEDIATE                       8
7422 #define TK_EXCLUSIVE                       9
7423 #define TK_COMMIT                         10
7424 #define TK_END                            11
7425 #define TK_ROLLBACK                       12
7426 #define TK_SAVEPOINT                      13
7427 #define TK_RELEASE                        14
7428 #define TK_TO                             15
7429 #define TK_TABLE                          16
7430 #define TK_CREATE                         17
7431 #define TK_IF                             18
7432 #define TK_NOT                            19
7433 #define TK_EXISTS                         20
7434 #define TK_TEMP                           21
7435 #define TK_LP                             22
7436 #define TK_RP                             23
7437 #define TK_AS                             24
7438 #define TK_COMMA                          25
7439 #define TK_ID                             26
7440 #define TK_INDEXED                        27
7441 #define TK_ABORT                          28
7442 #define TK_ACTION                         29
7443 #define TK_AFTER                          30
7444 #define TK_ANALYZE                        31
7445 #define TK_ASC                            32
7446 #define TK_ATTACH                         33
7447 #define TK_BEFORE                         34
7448 #define TK_BY                             35
7449 #define TK_CASCADE                        36
7450 #define TK_CAST                           37
7451 #define TK_COLUMNKW                       38
7452 #define TK_CONFLICT                       39
7453 #define TK_DATABASE                       40
7454 #define TK_DESC                           41
7455 #define TK_DETACH                         42
7456 #define TK_EACH                           43
7457 #define TK_FAIL                           44
7458 #define TK_FOR                            45
7459 #define TK_IGNORE                         46
7460 #define TK_INITIALLY                      47
7461 #define TK_INSTEAD                        48
7462 #define TK_LIKE_KW                        49
7463 #define TK_MATCH                          50
7464 #define TK_NO                             51
7465 #define TK_KEY                            52
7466 #define TK_OF                             53
7467 #define TK_OFFSET                         54
7468 #define TK_PRAGMA                         55
7469 #define TK_RAISE                          56
7470 #define TK_REPLACE                        57
7471 #define TK_RESTRICT                       58
7472 #define TK_ROW                            59
7473 #define TK_TRIGGER                        60
7474 #define TK_VACUUM                         61
7475 #define TK_VIEW                           62
7476 #define TK_VIRTUAL                        63
7477 #define TK_REINDEX                        64
7478 #define TK_RENAME                         65
7479 #define TK_CTIME_KW                       66
7480 #define TK_ANY                            67
7481 #define TK_OR                             68
7482 #define TK_AND                            69
7483 #define TK_IS                             70
7484 #define TK_BETWEEN                        71
7485 #define TK_IN                             72
7486 #define TK_ISNULL                         73
7487 #define TK_NOTNULL                        74
7488 #define TK_NE                             75
7489 #define TK_EQ                             76
7490 #define TK_GT                             77
7491 #define TK_LE                             78
7492 #define TK_LT                             79
7493 #define TK_GE                             80
7494 #define TK_ESCAPE                         81
7495 #define TK_BITAND                         82
7496 #define TK_BITOR                          83
7497 #define TK_LSHIFT                         84
7498 #define TK_RSHIFT                         85
7499 #define TK_PLUS                           86
7500 #define TK_MINUS                          87
7501 #define TK_STAR                           88
7502 #define TK_SLASH                          89
7503 #define TK_REM                            90
7504 #define TK_CONCAT                         91
7505 #define TK_COLLATE                        92
7506 #define TK_BITNOT                         93
7507 #define TK_STRING                         94
7508 #define TK_JOIN_KW                        95
7509 #define TK_CONSTRAINT                     96
7510 #define TK_DEFAULT                        97
7511 #define TK_NULL                           98
7512 #define TK_PRIMARY                        99
7513 #define TK_UNIQUE                         100
7514 #define TK_CHECK                          101
7515 #define TK_REFERENCES                     102
7516 #define TK_AUTOINCR                       103
7517 #define TK_ON                             104
7518 #define TK_INSERT                         105
7519 #define TK_DELETE                         106
7520 #define TK_UPDATE                         107
7521 #define TK_SET                            108
7522 #define TK_DEFERRABLE                     109
7523 #define TK_FOREIGN                        110
7524 #define TK_DROP                           111
7525 #define TK_UNION                          112
7526 #define TK_ALL                            113
7527 #define TK_EXCEPT                         114
7528 #define TK_INTERSECT                      115
7529 #define TK_SELECT                         116
7530 #define TK_DISTINCT                       117
7531 #define TK_DOT                            118
7532 #define TK_FROM                           119
7533 #define TK_JOIN                           120
7534 #define TK_USING                          121
7535 #define TK_ORDER                          122
7536 #define TK_GROUP                          123
7537 #define TK_HAVING                         124
7538 #define TK_LIMIT                          125
7539 #define TK_WHERE                          126
7540 #define TK_INTO                           127
7541 #define TK_VALUES                         128
7542 #define TK_INTEGER                        129
7543 #define TK_FLOAT                          130
7544 #define TK_BLOB                           131
7545 #define TK_REGISTER                       132
7546 #define TK_VARIABLE                       133
7547 #define TK_CASE                           134
7548 #define TK_WHEN                           135
7549 #define TK_THEN                           136
7550 #define TK_ELSE                           137
7551 #define TK_INDEX                          138
7552 #define TK_ALTER                          139
7553 #define TK_ADD                            140
7554 #define TK_TO_TEXT                        141
7555 #define TK_TO_BLOB                        142
7556 #define TK_TO_NUMERIC                     143
7557 #define TK_TO_INT                         144
7558 #define TK_TO_REAL                        145
7559 #define TK_ISNOT                          146
7560 #define TK_END_OF_FILE                    147
7561 #define TK_ILLEGAL                        148
7562 #define TK_SPACE                          149
7563 #define TK_UNCLOSED_STRING                150
7564 #define TK_FUNCTION                       151
7565 #define TK_COLUMN                         152
7566 #define TK_AGG_FUNCTION                   153
7567 #define TK_AGG_COLUMN                     154
7568 #define TK_CONST_FUNC                     155
7569 #define TK_UMINUS                         156
7570 #define TK_UPLUS                          157
7571 
7572 /************** End of parse.h ***********************************************/
7573 /************** Continuing where we left off in sqliteInt.h ******************/
7574 #include <stdio.h>
7575 #include <stdlib.h>
7576 #include <string.h>
7577 #include <assert.h>
7578 #include <stddef.h>
7579 
7580 /*
7581 ** If compiling for a processor that lacks floating point support,
7582 ** substitute integer for floating-point
7583 */
7584 #ifdef SQLITE_OMIT_FLOATING_POINT
7585 # define double sqlite_int64
7586 # define float sqlite_int64
7587 # define LONGDOUBLE_TYPE sqlite_int64
7588 # ifndef SQLITE_BIG_DBL
7589 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7590 # endif
7591 # define SQLITE_OMIT_DATETIME_FUNCS 1
7592 # define SQLITE_OMIT_TRACE 1
7593 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7594 # undef SQLITE_HAVE_ISNAN
7595 #endif
7596 #ifndef SQLITE_BIG_DBL
7597 # define SQLITE_BIG_DBL (1e99)
7598 #endif
7599 
7600 /*
7601 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7602 ** afterward. Having this macro allows us to cause the C compiler
7603 ** to omit code used by TEMP tables without messy #ifndef statements.
7604 */
7605 #ifdef SQLITE_OMIT_TEMPDB
7606 #define OMIT_TEMPDB 1
7607 #else
7608 #define OMIT_TEMPDB 0
7609 #endif
7610 
7611 /*
7612 ** The "file format" number is an integer that is incremented whenever
7613 ** the VDBE-level file format changes.  The following macros define the
7614 ** the default file format for new databases and the maximum file format
7615 ** that the library can read.
7616 */
7617 #define SQLITE_MAX_FILE_FORMAT 4
7618 #ifndef SQLITE_DEFAULT_FILE_FORMAT
7619 # define SQLITE_DEFAULT_FILE_FORMAT 1
7620 #endif
7621 
7622 /*
7623 ** Determine whether triggers are recursive by default.  This can be
7624 ** changed at run-time using a pragma.
7625 */
7626 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7627 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7628 #endif
7629 
7630 /*
7631 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7632 ** on the command-line
7633 */
7634 #ifndef SQLITE_TEMP_STORE
7635 # define SQLITE_TEMP_STORE 1
7636 #endif
7637 
7638 /*
7639 ** GCC does not define the offsetof() macro so we'll have to do it
7640 ** ourselves.
7641 */
7642 #ifndef offsetof
7643 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7644 #endif
7645 
7646 /*
7647 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7648 ** not, there are still machines out there that use EBCDIC.)
7649 */
7650 #if 'A' == '\301'
7651 # define SQLITE_EBCDIC 1
7652 #else
7653 # define SQLITE_ASCII 1
7654 #endif
7655 
7656 /*
7657 ** Integers of known sizes.  These typedefs might change for architectures
7658 ** where the sizes very.  Preprocessor macros are available so that the
7659 ** types can be conveniently redefined at compile-type.  Like this:
7660 **
7661 **         cc '-DUINTPTR_TYPE=long long int' ...
7662 */
7663 #ifndef UINT32_TYPE
7664 # ifdef HAVE_UINT32_T
7665 #  define UINT32_TYPE uint32_t
7666 # else
7667 #  define UINT32_TYPE unsigned int
7668 # endif
7669 #endif
7670 #ifndef UINT16_TYPE
7671 # ifdef HAVE_UINT16_T
7672 #  define UINT16_TYPE uint16_t
7673 # else
7674 #  define UINT16_TYPE unsigned short int
7675 # endif
7676 #endif
7677 #ifndef INT16_TYPE
7678 # ifdef HAVE_INT16_T
7679 #  define INT16_TYPE int16_t
7680 # else
7681 #  define INT16_TYPE short int
7682 # endif
7683 #endif
7684 #ifndef UINT8_TYPE
7685 # ifdef HAVE_UINT8_T
7686 #  define UINT8_TYPE uint8_t
7687 # else
7688 #  define UINT8_TYPE unsigned char
7689 # endif
7690 #endif
7691 #ifndef INT8_TYPE
7692 # ifdef HAVE_INT8_T
7693 #  define INT8_TYPE int8_t
7694 # else
7695 #  define INT8_TYPE signed char
7696 # endif
7697 #endif
7698 #ifndef LONGDOUBLE_TYPE
7699 # define LONGDOUBLE_TYPE long double
7700 #endif
7701 typedef sqlite_int64 i64;          /* 8-byte signed integer */
7702 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7703 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7704 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7705 typedef INT16_TYPE i16;            /* 2-byte signed integer */
7706 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7707 typedef INT8_TYPE i8;              /* 1-byte signed integer */
7708 
7709 /*
7710 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7711 ** that can be stored in a u32 without loss of data.  The value
7712 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7713 ** have to specify the value in the less intuitive manner shown:
7714 */
7715 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7716 
7717 /*
7718 ** Macros to determine whether the machine is big or little endian,
7719 ** evaluated at runtime.
7720 */
7721 #ifdef SQLITE_AMALGAMATION
7722 SQLITE_PRIVATE const int sqlite3one = 1;
7723 #else
7724 SQLITE_PRIVATE const int sqlite3one;
7725 #endif
7726 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7727                              || defined(__x86_64) || defined(__x86_64__)
7728 # define SQLITE_BIGENDIAN    0
7729 # define SQLITE_LITTLEENDIAN 1
7730 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7731 #else
7732 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7733 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7734 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7735 #endif
7736 
7737 /*
7738 ** Constants for the largest and smallest possible 64-bit signed integers.
7739 ** These macros are designed to work correctly on both 32-bit and 64-bit
7740 ** compilers.
7741 */
7742 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7743 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7744 
7745 /*
7746 ** Round up a number to the next larger multiple of 8.  This is used
7747 ** to force 8-byte alignment on 64-bit architectures.
7748 */
7749 #define ROUND8(x)     (((x)+7)&~7)
7750 
7751 /*
7752 ** Round down to the nearest multiple of 8
7753 */
7754 #define ROUNDDOWN8(x) ((x)&~7)
7755 
7756 /*
7757 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
7758 ** macro is used only within assert() to verify that the code gets
7759 ** all alignment restrictions correct.
7760 **
7761 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
7762 ** underlying malloc() implemention might return us 4-byte aligned
7763 ** pointers.  In that case, only verify 4-byte alignment.
7764 */
7765 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
7766 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
7767 #else
7768 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
7769 #endif
7770 
7771 
7772 /*
7773 ** An instance of the following structure is used to store the busy-handler
7774 ** callback for a given sqlite handle.
7775 **
7776 ** The sqlite.busyHandler member of the sqlite struct contains the busy
7777 ** callback for the database handle. Each pager opened via the sqlite
7778 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
7779 ** callback is currently invoked only from within pager.c.
7780 */
7781 typedef struct BusyHandler BusyHandler;
7782 struct BusyHandler {
7783   int (*xFunc)(void *,int);  /* The busy callback */
7784   void *pArg;                /* First arg to busy callback */
7785   int nBusy;                 /* Incremented with each busy call */
7786 };
7787 
7788 /*
7789 ** Name of the master database table.  The master database table
7790 ** is a special table that holds the names and attributes of all
7791 ** user tables and indices.
7792 */
7793 #define MASTER_NAME       "sqlite_master"
7794 #define TEMP_MASTER_NAME  "sqlite_temp_master"
7795 
7796 /*
7797 ** The root-page of the master database table.
7798 */
7799 #define MASTER_ROOT       1
7800 
7801 /*
7802 ** The name of the schema table.
7803 */
7804 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
7805 
7806 /*
7807 ** A convenience macro that returns the number of elements in
7808 ** an array.
7809 */
7810 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
7811 
7812 /*
7813 ** The following value as a destructor means to use sqlite3DbFree().
7814 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
7815 */
7816 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
7817 
7818 /*
7819 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
7820 ** not support Writable Static Data (WSD) such as global and static variables.
7821 ** All variables must either be on the stack or dynamically allocated from
7822 ** the heap.  When WSD is unsupported, the variable declarations scattered
7823 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
7824 ** macro is used for this purpose.  And instead of referencing the variable
7825 ** directly, we use its constant as a key to lookup the run-time allocated
7826 ** buffer that holds real variable.  The constant is also the initializer
7827 ** for the run-time allocated buffer.
7828 **
7829 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
7830 ** macros become no-ops and have zero performance impact.
7831 */
7832 #ifdef SQLITE_OMIT_WSD
7833   #define SQLITE_WSD const
7834   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
7835   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
7836 SQLITE_API   int sqlite3_wsd_init(int N, int J);
7837 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
7838 #else
7839   #define SQLITE_WSD
7840   #define GLOBAL(t,v) v
7841   #define sqlite3GlobalConfig sqlite3Config
7842 #endif
7843 
7844 /*
7845 ** The following macros are used to suppress compiler warnings and to
7846 ** make it clear to human readers when a function parameter is deliberately
7847 ** left unused within the body of a function. This usually happens when
7848 ** a function is called via a function pointer. For example the
7849 ** implementation of an SQL aggregate step callback may not use the
7850 ** parameter indicating the number of arguments passed to the aggregate,
7851 ** if it knows that this is enforced elsewhere.
7852 **
7853 ** When a function parameter is not used at all within the body of a function,
7854 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
7855 ** However, these macros may also be used to suppress warnings related to
7856 ** parameters that may or may not be used depending on compilation options.
7857 ** For example those parameters only used in assert() statements. In these
7858 ** cases the parameters are named as per the usual conventions.
7859 */
7860 #define UNUSED_PARAMETER(x) (void)(x)
7861 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
7862 
7863 /*
7864 ** Forward references to structures
7865 */
7866 typedef struct AggInfo AggInfo;
7867 typedef struct AuthContext AuthContext;
7868 typedef struct AutoincInfo AutoincInfo;
7869 typedef struct Bitvec Bitvec;
7870 typedef struct CollSeq CollSeq;
7871 typedef struct Column Column;
7872 typedef struct Db Db;
7873 typedef struct Schema Schema;
7874 typedef struct Expr Expr;
7875 typedef struct ExprList ExprList;
7876 typedef struct ExprSpan ExprSpan;
7877 typedef struct FKey FKey;
7878 typedef struct FuncDestructor FuncDestructor;
7879 typedef struct FuncDef FuncDef;
7880 typedef struct FuncDefHash FuncDefHash;
7881 typedef struct IdList IdList;
7882 typedef struct Index Index;
7883 typedef struct IndexSample IndexSample;
7884 typedef struct KeyClass KeyClass;
7885 typedef struct KeyInfo KeyInfo;
7886 typedef struct Lookaside Lookaside;
7887 typedef struct LookasideSlot LookasideSlot;
7888 typedef struct Module Module;
7889 typedef struct NameContext NameContext;
7890 typedef struct Parse Parse;
7891 typedef struct RowSet RowSet;
7892 typedef struct Savepoint Savepoint;
7893 typedef struct Select Select;
7894 typedef struct SrcList SrcList;
7895 typedef struct StrAccum StrAccum;
7896 typedef struct Table Table;
7897 typedef struct TableLock TableLock;
7898 typedef struct Token Token;
7899 typedef struct Trigger Trigger;
7900 typedef struct TriggerPrg TriggerPrg;
7901 typedef struct TriggerStep TriggerStep;
7902 typedef struct UnpackedRecord UnpackedRecord;
7903 typedef struct VTable VTable;
7904 typedef struct VtabCtx VtabCtx;
7905 typedef struct Walker Walker;
7906 typedef struct WherePlan WherePlan;
7907 typedef struct WhereInfo WhereInfo;
7908 typedef struct WhereLevel WhereLevel;
7909 
7910 /*
7911 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
7912 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
7913 ** pointer types (i.e. FuncDef) defined above.
7914 */
7915 /************** Include btree.h in the middle of sqliteInt.h *****************/
7916 /************** Begin file btree.h *******************************************/
7917 /*
7918 ** 2001 September 15
7919 **
7920 ** The author disclaims copyright to this source code.  In place of
7921 ** a legal notice, here is a blessing:
7922 **
7923 **    May you do good and not evil.
7924 **    May you find forgiveness for yourself and forgive others.
7925 **    May you share freely, never taking more than you give.
7926 **
7927 *************************************************************************
7928 ** This header file defines the interface that the sqlite B-Tree file
7929 ** subsystem.  See comments in the source code for a detailed description
7930 ** of what each interface routine does.
7931 */
7932 #ifndef _BTREE_H_
7933 #define _BTREE_H_
7934 
7935 /* TODO: This definition is just included so other modules compile. It
7936 ** needs to be revisited.
7937 */
7938 #define SQLITE_N_BTREE_META 10
7939 
7940 /*
7941 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
7942 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
7943 */
7944 #ifndef SQLITE_DEFAULT_AUTOVACUUM
7945   #define SQLITE_DEFAULT_AUTOVACUUM 0
7946 #endif
7947 
7948 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
7949 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
7950 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
7951 
7952 /*
7953 ** Forward declarations of structure
7954 */
7955 typedef struct Btree Btree;
7956 typedef struct BtCursor BtCursor;
7957 typedef struct BtShared BtShared;
7958 
7959 
7960 SQLITE_PRIVATE int sqlite3BtreeOpen(
7961   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
7962   const char *zFilename,   /* Name of database file to open */
7963   sqlite3 *db,             /* Associated database connection */
7964   Btree **ppBtree,         /* Return open Btree* here */
7965   int flags,               /* Flags */
7966   int vfsFlags             /* Flags passed through to VFS open */
7967 );
7968 
7969 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
7970 ** following values.
7971 **
7972 ** NOTE:  These values must match the corresponding PAGER_ values in
7973 ** pager.h.
7974 */
7975 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
7976 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
7977 #define BTREE_MEMORY        4  /* This is an in-memory DB */
7978 #define BTREE_SINGLE        8  /* The file contains at most 1 b-tree */
7979 #define BTREE_UNORDERED    16  /* Use of a hash implementation is OK */
7980 
7981 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
7982 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
7983 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
7984 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
7985 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
7986 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
7987 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
7988 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
7989 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
7990 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
7991 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
7992 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
7993 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
7994 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
7995 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
7996 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
7997 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
7998 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
7999 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8000 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8001 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8002 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8003 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8004 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8005 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8006 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8007 
8008 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8009 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8010 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8011 
8012 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8013 
8014 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8015 ** of the flags shown below.
8016 **
8017 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8018 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8019 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8020 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8021 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8022 ** indices.)
8023 */
8024 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8025 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8026 
8027 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8028 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8029 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8030 
8031 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8032 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8033 
8034 /*
8035 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8036 ** should be one of the following values. The integer values are assigned
8037 ** to constants so that the offset of the corresponding field in an
8038 ** SQLite database header may be found using the following formula:
8039 **
8040 **   offset = 36 + (idx * 4)
8041 **
8042 ** For example, the free-page-count field is located at byte offset 36 of
8043 ** the database file header. The incr-vacuum-flag field is located at
8044 ** byte offset 64 (== 36+4*7).
8045 */
8046 #define BTREE_FREE_PAGE_COUNT     0
8047 #define BTREE_SCHEMA_VERSION      1
8048 #define BTREE_FILE_FORMAT         2
8049 #define BTREE_DEFAULT_CACHE_SIZE  3
8050 #define BTREE_LARGEST_ROOT_PAGE   4
8051 #define BTREE_TEXT_ENCODING       5
8052 #define BTREE_USER_VERSION        6
8053 #define BTREE_INCR_VACUUM         7
8054 
8055 SQLITE_PRIVATE int sqlite3BtreeCursor(
8056   Btree*,                              /* BTree containing table to open */
8057   int iTable,                          /* Index of root page */
8058   int wrFlag,                          /* 1 for writing.  0 for read-only */
8059   struct KeyInfo*,                     /* First argument to compare function */
8060   BtCursor *pCursor                    /* Space to write cursor structure */
8061 );
8062 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8063 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8064 
8065 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8066 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8067   BtCursor*,
8068   UnpackedRecord *pUnKey,
8069   i64 intKey,
8070   int bias,
8071   int *pRes
8072 );
8073 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8074 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8075 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8076                                   const void *pData, int nData,
8077                                   int nZero, int bias, int seekResult);
8078 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8079 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8080 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8081 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8082 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8083 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8084 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8085 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8086 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8087 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8088 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8089 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8090 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8091 
8092 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8093 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8094 
8095 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8096 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8097 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8098 
8099 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8100 
8101 #ifndef NDEBUG
8102 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8103 #endif
8104 
8105 #ifndef SQLITE_OMIT_BTREECOUNT
8106 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8107 #endif
8108 
8109 #ifdef SQLITE_TEST
8110 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8111 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8112 #endif
8113 
8114 #ifndef SQLITE_OMIT_WAL
8115 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8116 #endif
8117 
8118 /*
8119 ** If we are not using shared cache, then there is no need to
8120 ** use mutexes to access the BtShared structures.  So make the
8121 ** Enter and Leave procedures no-ops.
8122 */
8123 #ifndef SQLITE_OMIT_SHARED_CACHE
8124 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8125 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8126 #else
8127 # define sqlite3BtreeEnter(X)
8128 # define sqlite3BtreeEnterAll(X)
8129 #endif
8130 
8131 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8132 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8133 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8134 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8135 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8136 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8137 #ifndef NDEBUG
8138   /* These routines are used inside assert() statements only. */
8139 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8140 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8141 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8142 #endif
8143 #else
8144 
8145 # define sqlite3BtreeSharable(X) 0
8146 # define sqlite3BtreeLeave(X)
8147 # define sqlite3BtreeEnterCursor(X)
8148 # define sqlite3BtreeLeaveCursor(X)
8149 # define sqlite3BtreeLeaveAll(X)
8150 
8151 # define sqlite3BtreeHoldsMutex(X) 1
8152 # define sqlite3BtreeHoldsAllMutexes(X) 1
8153 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8154 #endif
8155 
8156 
8157 #endif /* _BTREE_H_ */
8158 
8159 /************** End of btree.h ***********************************************/
8160 /************** Continuing where we left off in sqliteInt.h ******************/
8161 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8162 /************** Begin file vdbe.h ********************************************/
8163 /*
8164 ** 2001 September 15
8165 **
8166 ** The author disclaims copyright to this source code.  In place of
8167 ** a legal notice, here is a blessing:
8168 **
8169 **    May you do good and not evil.
8170 **    May you find forgiveness for yourself and forgive others.
8171 **    May you share freely, never taking more than you give.
8172 **
8173 *************************************************************************
8174 ** Header file for the Virtual DataBase Engine (VDBE)
8175 **
8176 ** This header defines the interface to the virtual database engine
8177 ** or VDBE.  The VDBE implements an abstract machine that runs a
8178 ** simple program to access and modify the underlying database.
8179 */
8180 #ifndef _SQLITE_VDBE_H_
8181 #define _SQLITE_VDBE_H_
8182 /* #include <stdio.h> */
8183 
8184 /*
8185 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8186 ** in the source file sqliteVdbe.c are allowed to see the insides
8187 ** of this structure.
8188 */
8189 typedef struct Vdbe Vdbe;
8190 
8191 /*
8192 ** The names of the following types declared in vdbeInt.h are required
8193 ** for the VdbeOp definition.
8194 */
8195 typedef struct VdbeFunc VdbeFunc;
8196 typedef struct Mem Mem;
8197 typedef struct SubProgram SubProgram;
8198 
8199 /*
8200 ** A single instruction of the virtual machine has an opcode
8201 ** and as many as three operands.  The instruction is recorded
8202 ** as an instance of the following structure:
8203 */
8204 struct VdbeOp {
8205   u8 opcode;          /* What operation to perform */
8206   signed char p4type; /* One of the P4_xxx constants for p4 */
8207   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8208   u8 p5;              /* Fifth parameter is an unsigned character */
8209   int p1;             /* First operand */
8210   int p2;             /* Second parameter (often the jump destination) */
8211   int p3;             /* The third parameter */
8212   union {             /* fourth parameter */
8213     int i;                 /* Integer value if p4type==P4_INT32 */
8214     void *p;               /* Generic pointer */
8215     char *z;               /* Pointer to data for string (char array) types */
8216     i64 *pI64;             /* Used when p4type is P4_INT64 */
8217     double *pReal;         /* Used when p4type is P4_REAL */
8218     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8219     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8220     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8221     Mem *pMem;             /* Used when p4type is P4_MEM */
8222     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8223     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8224     int *ai;               /* Used when p4type is P4_INTARRAY */
8225     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8226     int (*xAdvance)(BtCursor *, int *);
8227   } p4;
8228 #ifdef SQLITE_DEBUG
8229   char *zComment;          /* Comment to improve readability */
8230 #endif
8231 #ifdef VDBE_PROFILE
8232   int cnt;                 /* Number of times this instruction was executed */
8233   u64 cycles;              /* Total time spent executing this instruction */
8234 #endif
8235 };
8236 typedef struct VdbeOp VdbeOp;
8237 
8238 
8239 /*
8240 ** A sub-routine used to implement a trigger program.
8241 */
8242 struct SubProgram {
8243   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8244   int nOp;                      /* Elements in aOp[] */
8245   int nMem;                     /* Number of memory cells required */
8246   int nCsr;                     /* Number of cursors required */
8247   void *token;                  /* id that may be used to recursive triggers */
8248   SubProgram *pNext;            /* Next sub-program already visited */
8249 };
8250 
8251 /*
8252 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8253 ** it takes up less space.
8254 */
8255 struct VdbeOpList {
8256   u8 opcode;          /* What operation to perform */
8257   signed char p1;     /* First operand */
8258   signed char p2;     /* Second parameter (often the jump destination) */
8259   signed char p3;     /* Third parameter */
8260 };
8261 typedef struct VdbeOpList VdbeOpList;
8262 
8263 /*
8264 ** Allowed values of VdbeOp.p4type
8265 */
8266 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8267 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8268 #define P4_STATIC   (-2)  /* Pointer to a static string */
8269 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8270 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8271 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8272 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8273 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8274 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8275 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8276 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8277 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8278 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8279 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8280 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8281 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8282 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8283 
8284 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8285 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8286 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8287 ** gets freed when the Vdbe is finalized so it still should be obtained
8288 ** from a single sqliteMalloc().  But no copy is made and the calling
8289 ** function should *not* try to free the KeyInfo.
8290 */
8291 #define P4_KEYINFO_HANDOFF (-16)
8292 #define P4_KEYINFO_STATIC  (-17)
8293 
8294 /*
8295 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
8296 ** number of columns of data returned by the statement.
8297 */
8298 #define COLNAME_NAME     0
8299 #define COLNAME_DECLTYPE 1
8300 #define COLNAME_DATABASE 2
8301 #define COLNAME_TABLE    3
8302 #define COLNAME_COLUMN   4
8303 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8304 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8305 #else
8306 # ifdef SQLITE_OMIT_DECLTYPE
8307 #   define COLNAME_N      1      /* Store only the name */
8308 # else
8309 #   define COLNAME_N      2      /* Store the name and decltype */
8310 # endif
8311 #endif
8312 
8313 /*
8314 ** The following macro converts a relative address in the p2 field
8315 ** of a VdbeOp structure into a negative number so that
8316 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8317 ** the macro again restores the address.
8318 */
8319 #define ADDR(X)  (-1-(X))
8320 
8321 /*
8322 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8323 ** header file that defines a number for each opcode used by the VDBE.
8324 */
8325 /************** Include opcodes.h in the middle of vdbe.h ********************/
8326 /************** Begin file opcodes.h *****************************************/
8327 /* Automatically generated.  Do not edit */
8328 /* See the mkopcodeh.awk script for details */
8329 #define OP_Goto                                 1
8330 #define OP_Gosub                                2
8331 #define OP_Return                               3
8332 #define OP_Yield                                4
8333 #define OP_HaltIfNull                           5
8334 #define OP_Halt                                 6
8335 #define OP_Integer                              7
8336 #define OP_Int64                                8
8337 #define OP_Real                               130   /* same as TK_FLOAT    */
8338 #define OP_String8                             94   /* same as TK_STRING   */
8339 #define OP_String                               9
8340 #define OP_Null                                10
8341 #define OP_Blob                                11
8342 #define OP_Variable                            12
8343 #define OP_Move                                13
8344 #define OP_Copy                                14
8345 #define OP_SCopy                               15
8346 #define OP_ResultRow                           16
8347 #define OP_Concat                              91   /* same as TK_CONCAT   */
8348 #define OP_Add                                 86   /* same as TK_PLUS     */
8349 #define OP_Subtract                            87   /* same as TK_MINUS    */
8350 #define OP_Multiply                            88   /* same as TK_STAR     */
8351 #define OP_Divide                              89   /* same as TK_SLASH    */
8352 #define OP_Remainder                           90   /* same as TK_REM      */
8353 #define OP_CollSeq                             17
8354 #define OP_Function                            18
8355 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8356 #define OP_BitOr                               83   /* same as TK_BITOR    */
8357 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8358 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8359 #define OP_AddImm                              20
8360 #define OP_MustBeInt                           21
8361 #define OP_RealAffinity                        22
8362 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8363 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8364 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8365 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8366 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8367 #define OP_Eq                                  76   /* same as TK_EQ       */
8368 #define OP_Ne                                  75   /* same as TK_NE       */
8369 #define OP_Lt                                  79   /* same as TK_LT       */
8370 #define OP_Le                                  78   /* same as TK_LE       */
8371 #define OP_Gt                                  77   /* same as TK_GT       */
8372 #define OP_Ge                                  80   /* same as TK_GE       */
8373 #define OP_Permutation                         23
8374 #define OP_Compare                             24
8375 #define OP_Jump                                25
8376 #define OP_And                                 69   /* same as TK_AND      */
8377 #define OP_Or                                  68   /* same as TK_OR       */
8378 #define OP_Not                                 19   /* same as TK_NOT      */
8379 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8380 #define OP_Once                                26
8381 #define OP_If                                  27
8382 #define OP_IfNot                               28
8383 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8384 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8385 #define OP_Column                              29
8386 #define OP_Affinity                            30
8387 #define OP_MakeRecord                          31
8388 #define OP_Count                               32
8389 #define OP_Savepoint                           33
8390 #define OP_AutoCommit                          34
8391 #define OP_Transaction                         35
8392 #define OP_ReadCookie                          36
8393 #define OP_SetCookie                           37
8394 #define OP_VerifyCookie                        38
8395 #define OP_OpenRead                            39
8396 #define OP_OpenWrite                           40
8397 #define OP_OpenAutoindex                       41
8398 #define OP_OpenEphemeral                       42
8399 #define OP_SorterOpen                          43
8400 #define OP_OpenPseudo                          44
8401 #define OP_Close                               45
8402 #define OP_SeekLt                              46
8403 #define OP_SeekLe                              47
8404 #define OP_SeekGe                              48
8405 #define OP_SeekGt                              49
8406 #define OP_Seek                                50
8407 #define OP_NotFound                            51
8408 #define OP_Found                               52
8409 #define OP_IsUnique                            53
8410 #define OP_NotExists                           54
8411 #define OP_Sequence                            55
8412 #define OP_NewRowid                            56
8413 #define OP_Insert                              57
8414 #define OP_InsertInt                           58
8415 #define OP_Delete                              59
8416 #define OP_ResetCount                          60
8417 #define OP_SorterCompare                       61
8418 #define OP_SorterData                          62
8419 #define OP_RowKey                              63
8420 #define OP_RowData                             64
8421 #define OP_Rowid                               65
8422 #define OP_NullRow                             66
8423 #define OP_Last                                67
8424 #define OP_SorterSort                          70
8425 #define OP_Sort                                71
8426 #define OP_Rewind                              72
8427 #define OP_SorterNext                          81
8428 #define OP_Prev                                92
8429 #define OP_Next                                95
8430 #define OP_SorterInsert                        96
8431 #define OP_IdxInsert                           97
8432 #define OP_IdxDelete                           98
8433 #define OP_IdxRowid                            99
8434 #define OP_IdxLT                              100
8435 #define OP_IdxGE                              101
8436 #define OP_Destroy                            102
8437 #define OP_Clear                              103
8438 #define OP_CreateIndex                        104
8439 #define OP_CreateTable                        105
8440 #define OP_ParseSchema                        106
8441 #define OP_LoadAnalysis                       107
8442 #define OP_DropTable                          108
8443 #define OP_DropIndex                          109
8444 #define OP_DropTrigger                        110
8445 #define OP_IntegrityCk                        111
8446 #define OP_RowSetAdd                          112
8447 #define OP_RowSetRead                         113
8448 #define OP_RowSetTest                         114
8449 #define OP_Program                            115
8450 #define OP_Param                              116
8451 #define OP_FkCounter                          117
8452 #define OP_FkIfZero                           118
8453 #define OP_MemMax                             119
8454 #define OP_IfPos                              120
8455 #define OP_IfNeg                              121
8456 #define OP_IfZero                             122
8457 #define OP_AggStep                            123
8458 #define OP_AggFinal                           124
8459 #define OP_Checkpoint                         125
8460 #define OP_JournalMode                        126
8461 #define OP_Vacuum                             127
8462 #define OP_IncrVacuum                         128
8463 #define OP_Expire                             129
8464 #define OP_TableLock                          131
8465 #define OP_VBegin                             132
8466 #define OP_VCreate                            133
8467 #define OP_VDestroy                           134
8468 #define OP_VOpen                              135
8469 #define OP_VFilter                            136
8470 #define OP_VColumn                            137
8471 #define OP_VNext                              138
8472 #define OP_VRename                            139
8473 #define OP_VUpdate                            140
8474 #define OP_Pagecount                          146
8475 #define OP_MaxPgcnt                           147
8476 #define OP_Trace                              148
8477 #define OP_Noop                               149
8478 #define OP_Explain                            150
8479 
8480 
8481 /* Properties such as "out2" or "jump" that are specified in
8482 ** comments following the "case" for each opcode in the vdbe.c
8483 ** are encoded into bitvectors as follows:
8484 */
8485 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8486 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8487 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8488 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8489 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8490 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8491 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8492 #define OPFLG_INITIALIZER {\
8493 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
8494 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8495 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8496 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x05, 0x00, 0x00, 0x00,\
8497 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8498 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8499 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8500 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8501 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8502 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8503 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8504 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8505 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8506 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8507 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8508 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8509 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8510 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8511 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8512 
8513 /************** End of opcodes.h *********************************************/
8514 /************** Continuing where we left off in vdbe.h ***********************/
8515 
8516 /*
8517 ** Prototypes for the VDBE interface.  See comments on the implementation
8518 ** for a description of what each of these routines does.
8519 */
8520 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8521 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8522 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8523 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8524 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8525 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8526 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8527 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8528 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8529 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8530 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8531 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8532 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8533 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8534 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8535 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8536 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8537 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8538 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8539 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8540 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8541 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8542 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8543 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8544 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8545 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8546 #ifdef SQLITE_DEBUG
8547 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8548 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8549 #endif
8550 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8551 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8552 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8553 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8554 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8555 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8556 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8557 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8558 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8559 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8560 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8561 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8562 #ifndef SQLITE_OMIT_TRACE
8563 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8564 #endif
8565 
8566 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8567 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8568 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8569 
8570 #ifndef SQLITE_OMIT_TRIGGER
8571 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8572 #endif
8573 
8574 
8575 #ifndef NDEBUG
8576 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8577 # define VdbeComment(X)  sqlite3VdbeComment X
8578 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8579 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8580 #else
8581 # define VdbeComment(X)
8582 # define VdbeNoopComment(X)
8583 #endif
8584 
8585 #endif
8586 
8587 /************** End of vdbe.h ************************************************/
8588 /************** Continuing where we left off in sqliteInt.h ******************/
8589 /************** Include pager.h in the middle of sqliteInt.h *****************/
8590 /************** Begin file pager.h *******************************************/
8591 /*
8592 ** 2001 September 15
8593 **
8594 ** The author disclaims copyright to this source code.  In place of
8595 ** a legal notice, here is a blessing:
8596 **
8597 **    May you do good and not evil.
8598 **    May you find forgiveness for yourself and forgive others.
8599 **    May you share freely, never taking more than you give.
8600 **
8601 *************************************************************************
8602 ** This header file defines the interface that the sqlite page cache
8603 ** subsystem.  The page cache subsystem reads and writes a file a page
8604 ** at a time and provides a journal for rollback.
8605 */
8606 
8607 #ifndef _PAGER_H_
8608 #define _PAGER_H_
8609 
8610 /*
8611 ** Default maximum size for persistent journal files. A negative
8612 ** value means no limit. This value may be overridden using the
8613 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8614 */
8615 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8616   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8617 #endif
8618 
8619 /*
8620 ** The type used to represent a page number.  The first page in a file
8621 ** is called page 1.  0 is used to represent "not a page".
8622 */
8623 typedef u32 Pgno;
8624 
8625 /*
8626 ** Each open file is managed by a separate instance of the "Pager" structure.
8627 */
8628 typedef struct Pager Pager;
8629 
8630 /*
8631 ** Handle type for pages.
8632 */
8633 typedef struct PgHdr DbPage;
8634 
8635 /*
8636 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8637 ** reserved for working around a windows/posix incompatibility). It is
8638 ** used in the journal to signify that the remainder of the journal file
8639 ** is devoted to storing a master journal name - there are no more pages to
8640 ** roll back. See comments for function writeMasterJournal() in pager.c
8641 ** for details.
8642 */
8643 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8644 
8645 /*
8646 ** Allowed values for the flags parameter to sqlite3PagerOpen().
8647 **
8648 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8649 */
8650 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8651 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
8652 #define PAGER_MEMORY        0x0004    /* In-memory database */
8653 
8654 /*
8655 ** Valid values for the second argument to sqlite3PagerLockingMode().
8656 */
8657 #define PAGER_LOCKINGMODE_QUERY      -1
8658 #define PAGER_LOCKINGMODE_NORMAL      0
8659 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
8660 
8661 /*
8662 ** Numeric constants that encode the journalmode.
8663 */
8664 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8665 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8666 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8667 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8668 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8669 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8670 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8671 
8672 /*
8673 ** The remainder of this file contains the declarations of the functions
8674 ** that make up the Pager sub-system API. See source code comments for
8675 ** a detailed description of each routine.
8676 */
8677 
8678 /* Open and close a Pager connection. */
8679 SQLITE_PRIVATE int sqlite3PagerOpen(
8680   sqlite3_vfs*,
8681   Pager **ppPager,
8682   const char*,
8683   int,
8684   int,
8685   int,
8686   void(*)(DbPage*)
8687 );
8688 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8689 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8690 
8691 /* Functions used to configure a Pager object. */
8692 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8693 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8694 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8695 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8696 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8697 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8698 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8699 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8700 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8701 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8702 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8703 
8704 /* Functions used to obtain and release page references. */
8705 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8706 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8707 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8708 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8709 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8710 
8711 /* Operations on page references. */
8712 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8713 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8714 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8715 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8716 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8717 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8718 
8719 /* Functions used to manage pager transactions and savepoints. */
8720 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8721 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8722 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8723 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8724 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8725 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8726 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8727 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8728 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8729 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8730 
8731 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8732 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8733 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8734 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8735 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8736 
8737 /* Functions used to query pager state and configuration. */
8738 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
8739 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
8740 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
8741 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
8742 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
8743 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
8744 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
8745 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
8746 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
8747 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
8748 
8749 /* Functions used to truncate the database file. */
8750 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
8751 
8752 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
8753 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
8754 #endif
8755 
8756 /* Functions to support testing and debugging. */
8757 #if !defined(NDEBUG) || defined(SQLITE_TEST)
8758 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
8759 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
8760 #endif
8761 #ifdef SQLITE_TEST
8762 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
8763 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
8764   void disable_simulated_io_errors(void);
8765   void enable_simulated_io_errors(void);
8766 #else
8767 # define disable_simulated_io_errors()
8768 # define enable_simulated_io_errors()
8769 #endif
8770 
8771 #endif /* _PAGER_H_ */
8772 
8773 /************** End of pager.h ***********************************************/
8774 /************** Continuing where we left off in sqliteInt.h ******************/
8775 /************** Include pcache.h in the middle of sqliteInt.h ****************/
8776 /************** Begin file pcache.h ******************************************/
8777 /*
8778 ** 2008 August 05
8779 **
8780 ** The author disclaims copyright to this source code.  In place of
8781 ** a legal notice, here is a blessing:
8782 **
8783 **    May you do good and not evil.
8784 **    May you find forgiveness for yourself and forgive others.
8785 **    May you share freely, never taking more than you give.
8786 **
8787 *************************************************************************
8788 ** This header file defines the interface that the sqlite page cache
8789 ** subsystem.
8790 */
8791 
8792 #ifndef _PCACHE_H_
8793 
8794 typedef struct PgHdr PgHdr;
8795 typedef struct PCache PCache;
8796 
8797 /*
8798 ** Every page in the cache is controlled by an instance of the following
8799 ** structure.
8800 */
8801 struct PgHdr {
8802   void *pData;                   /* Content of this page */
8803   void *pExtra;                  /* Extra content */
8804   PgHdr *pDirty;                 /* Transient list of dirty pages */
8805   Pgno pgno;                     /* Page number for this page */
8806   Pager *pPager;                 /* The pager this page is part of */
8807 #ifdef SQLITE_CHECK_PAGES
8808   u32 pageHash;                  /* Hash of page content */
8809 #endif
8810   u16 flags;                     /* PGHDR flags defined below */
8811 
8812   /**********************************************************************
8813   ** Elements above are public.  All that follows is private to pcache.c
8814   ** and should not be accessed by other modules.
8815   */
8816   i16 nRef;                      /* Number of users of this page */
8817   PCache *pCache;                /* Cache that owns this page */
8818 
8819   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
8820   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
8821 };
8822 
8823 /* Bit values for PgHdr.flags */
8824 #define PGHDR_DIRTY             0x002  /* Page has changed */
8825 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
8826                                        ** writing this page to the database */
8827 #define PGHDR_NEED_READ         0x008  /* Content is unread */
8828 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
8829 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
8830 
8831 /* Initialize and shutdown the page cache subsystem */
8832 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
8833 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
8834 
8835 /* Page cache buffer management:
8836 ** These routines implement SQLITE_CONFIG_PAGECACHE.
8837 */
8838 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
8839 
8840 /* Create a new pager cache.
8841 ** Under memory stress, invoke xStress to try to make pages clean.
8842 ** Only clean and unpinned pages can be reclaimed.
8843 */
8844 SQLITE_PRIVATE void sqlite3PcacheOpen(
8845   int szPage,                    /* Size of every page */
8846   int szExtra,                   /* Extra space associated with each page */
8847   int bPurgeable,                /* True if pages are on backing store */
8848   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
8849   void *pStress,                 /* Argument to xStress */
8850   PCache *pToInit                /* Preallocated space for the PCache */
8851 );
8852 
8853 /* Modify the page-size after the cache has been created. */
8854 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
8855 
8856 /* Return the size in bytes of a PCache object.  Used to preallocate
8857 ** storage space.
8858 */
8859 SQLITE_PRIVATE int sqlite3PcacheSize(void);
8860 
8861 /* One release per successful fetch.  Page is pinned until released.
8862 ** Reference counted.
8863 */
8864 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
8865 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
8866 
8867 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
8868 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
8869 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
8870 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
8871 
8872 /* Change a page number.  Used by incr-vacuum. */
8873 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
8874 
8875 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
8876 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
8877 
8878 /* Get a list of all dirty pages in the cache, sorted by page number */
8879 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
8880 
8881 /* Reset and close the cache object */
8882 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
8883 
8884 /* Clear flags from pages of the page cache */
8885 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
8886 
8887 /* Discard the contents of the cache */
8888 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
8889 
8890 /* Return the total number of outstanding page references */
8891 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
8892 
8893 /* Increment the reference count of an existing page */
8894 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
8895 
8896 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
8897 
8898 /* Return the total number of pages stored in the cache */
8899 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
8900 
8901 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
8902 /* Iterate through all dirty pages currently stored in the cache. This
8903 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
8904 ** library is built.
8905 */
8906 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
8907 #endif
8908 
8909 /* Set and get the suggested cache-size for the specified pager-cache.
8910 **
8911 ** If no global maximum is configured, then the system attempts to limit
8912 ** the total number of pages cached by purgeable pager-caches to the sum
8913 ** of the suggested cache-sizes.
8914 */
8915 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
8916 #ifdef SQLITE_TEST
8917 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
8918 #endif
8919 
8920 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
8921 /* Try to return memory used by the pcache module to the main memory heap */
8922 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
8923 #endif
8924 
8925 #ifdef SQLITE_TEST
8926 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
8927 #endif
8928 
8929 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
8930 
8931 #endif /* _PCACHE_H_ */
8932 
8933 /************** End of pcache.h **********************************************/
8934 /************** Continuing where we left off in sqliteInt.h ******************/
8935 
8936 /************** Include os.h in the middle of sqliteInt.h ********************/
8937 /************** Begin file os.h **********************************************/
8938 /*
8939 ** 2001 September 16
8940 **
8941 ** The author disclaims copyright to this source code.  In place of
8942 ** a legal notice, here is a blessing:
8943 **
8944 **    May you do good and not evil.
8945 **    May you find forgiveness for yourself and forgive others.
8946 **    May you share freely, never taking more than you give.
8947 **
8948 ******************************************************************************
8949 **
8950 ** This header file (together with is companion C source-code file
8951 ** "os.c") attempt to abstract the underlying operating system so that
8952 ** the SQLite library will work on both POSIX and windows systems.
8953 **
8954 ** This header file is #include-ed by sqliteInt.h and thus ends up
8955 ** being included by every source file.
8956 */
8957 #ifndef _SQLITE_OS_H_
8958 #define _SQLITE_OS_H_
8959 
8960 /*
8961 ** Figure out if we are dealing with Unix, Windows, or some other
8962 ** operating system.  After the following block of preprocess macros,
8963 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
8964 ** will defined to either 1 or 0.  One of the four will be 1.  The other
8965 ** three will be 0.
8966 */
8967 #if defined(SQLITE_OS_OTHER)
8968 # if SQLITE_OS_OTHER==1
8969 #   undef SQLITE_OS_UNIX
8970 #   define SQLITE_OS_UNIX 0
8971 #   undef SQLITE_OS_WIN
8972 #   define SQLITE_OS_WIN 0
8973 #   undef SQLITE_OS_OS2
8974 #   define SQLITE_OS_OS2 0
8975 # else
8976 #   undef SQLITE_OS_OTHER
8977 # endif
8978 #endif
8979 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
8980 # define SQLITE_OS_OTHER 0
8981 # ifndef SQLITE_OS_WIN
8982 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
8983 #     define SQLITE_OS_WIN 1
8984 #     define SQLITE_OS_UNIX 0
8985 #     define SQLITE_OS_OS2 0
8986 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
8987 #     define SQLITE_OS_WIN 0
8988 #     define SQLITE_OS_UNIX 0
8989 #     define SQLITE_OS_OS2 1
8990 #   else
8991 #     define SQLITE_OS_WIN 0
8992 #     define SQLITE_OS_UNIX 1
8993 #     define SQLITE_OS_OS2 0
8994 #  endif
8995 # else
8996 #  define SQLITE_OS_UNIX 0
8997 #  define SQLITE_OS_OS2 0
8998 # endif
8999 #else
9000 # ifndef SQLITE_OS_WIN
9001 #  define SQLITE_OS_WIN 0
9002 # endif
9003 #endif
9004 
9005 /*
9006 ** Determine if we are dealing with WindowsCE - which has a much
9007 ** reduced API.
9008 */
9009 #if defined(_WIN32_WCE)
9010 # define SQLITE_OS_WINCE 1
9011 #else
9012 # define SQLITE_OS_WINCE 0
9013 #endif
9014 
9015 
9016 /*
9017 ** Define the maximum size of a temporary filename
9018 */
9019 #if SQLITE_OS_WIN
9020 # include <windows.h>
9021 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
9022 #elif SQLITE_OS_OS2
9023 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9024 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
9025 # endif
9026 # define INCL_DOSDATETIME
9027 # define INCL_DOSFILEMGR
9028 # define INCL_DOSERRORS
9029 # define INCL_DOSMISC
9030 # define INCL_DOSPROCESS
9031 # define INCL_DOSMODULEMGR
9032 # define INCL_DOSSEMAPHORES
9033 # include <os2.h>
9034 # include <uconv.h>
9035 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9036 #else
9037 # define SQLITE_TEMPNAME_SIZE 200
9038 #endif
9039 
9040 /* If the SET_FULLSYNC macro is not defined above, then make it
9041 ** a no-op
9042 */
9043 #ifndef SET_FULLSYNC
9044 # define SET_FULLSYNC(x,y)
9045 #endif
9046 
9047 /*
9048 ** The default size of a disk sector
9049 */
9050 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9051 # define SQLITE_DEFAULT_SECTOR_SIZE 512
9052 #endif
9053 
9054 /*
9055 ** Temporary files are named starting with this prefix followed by 16 random
9056 ** alphanumeric characters, and no file extension. They are stored in the
9057 ** OS's standard temporary file directory, and are deleted prior to exit.
9058 ** If sqlite is being embedded in another program, you may wish to change the
9059 ** prefix to reflect your program's name, so that if your program exits
9060 ** prematurely, old temporary files can be easily identified. This can be done
9061 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9062 **
9063 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9064 ** Mcafee started using SQLite in their anti-virus product and it
9065 ** started putting files with the "sqlite" name in the c:/temp folder.
9066 ** This annoyed many windows users.  Those users would then do a
9067 ** Google search for "sqlite", find the telephone numbers of the
9068 ** developers and call to wake them up at night and complain.
9069 ** For this reason, the default name prefix is changed to be "sqlite"
9070 ** spelled backwards.  So the temp files are still identified, but
9071 ** anybody smart enough to figure out the code is also likely smart
9072 ** enough to know that calling the developer will not help get rid
9073 ** of the file.
9074 */
9075 #ifndef SQLITE_TEMP_FILE_PREFIX
9076 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9077 #endif
9078 
9079 /*
9080 ** The following values may be passed as the second argument to
9081 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9082 **
9083 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9084 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9085 **            any time. Other processes may hold and obtain new SHARED locks.
9086 ** PENDING:   A single process may hold a PENDING lock on a file at
9087 **            any one time. Existing SHARED locks may persist, but no new
9088 **            SHARED locks may be obtained by other processes.
9089 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9090 **
9091 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9092 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9093 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9094 ** sqlite3OsLock().
9095 */
9096 #define NO_LOCK         0
9097 #define SHARED_LOCK     1
9098 #define RESERVED_LOCK   2
9099 #define PENDING_LOCK    3
9100 #define EXCLUSIVE_LOCK  4
9101 
9102 /*
9103 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9104 **
9105 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9106 ** those functions are not available.  So we use only LockFile() and
9107 ** UnlockFile().
9108 **
9109 ** LockFile() prevents not just writing but also reading by other processes.
9110 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
9111 ** byte out of a specific range of bytes. The lock byte is obtained at
9112 ** random so two separate readers can probably access the file at the
9113 ** same time, unless they are unlucky and choose the same lock byte.
9114 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9115 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9116 ** a single byte of the file that is designated as the reserved lock byte.
9117 ** A PENDING_LOCK is obtained by locking a designated byte different from
9118 ** the RESERVED_LOCK byte.
9119 **
9120 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9121 ** which means we can use reader/writer locks.  When reader/writer locks
9122 ** are used, the lock is placed on the same range of bytes that is used
9123 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9124 ** will support two or more Win95 readers or two or more WinNT readers.
9125 ** But a single Win95 reader will lock out all WinNT readers and a single
9126 ** WinNT reader will lock out all other Win95 readers.
9127 **
9128 ** The following #defines specify the range of bytes used for locking.
9129 ** SHARED_SIZE is the number of bytes available in the pool from which
9130 ** a random byte is selected for a shared lock.  The pool of bytes for
9131 ** shared locks begins at SHARED_FIRST.
9132 **
9133 ** The same locking strategy and
9134 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9135 ** clients on win95, winNT, and unix all talking to the same shared file
9136 ** and all locking correctly.  To do so would require that samba (or whatever
9137 ** tool is being used for file sharing) implements locks correctly between
9138 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9139 ** using the same locking range we are at least open to the possibility.
9140 **
9141 ** Locking in windows is manditory.  For this reason, we cannot store
9142 ** actual data in the bytes used for locking.  The pager never allocates
9143 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9144 ** that all locks will fit on a single page even at the minimum page size.
9145 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9146 ** is set high so that we don't have to allocate an unused page except
9147 ** for very large databases.  But one should test the page skipping logic
9148 ** by setting PENDING_BYTE low and running the entire regression suite.
9149 **
9150 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9151 ** file format.  Depending on how it is changed, you might not notice
9152 ** the incompatibility right away, even running a full regression test.
9153 ** The default location of PENDING_BYTE is the first byte past the
9154 ** 1GB boundary.
9155 **
9156 */
9157 #ifdef SQLITE_OMIT_WSD
9158 # define PENDING_BYTE     (0x40000000)
9159 #else
9160 # define PENDING_BYTE      sqlite3PendingByte
9161 #endif
9162 #define RESERVED_BYTE     (PENDING_BYTE+1)
9163 #define SHARED_FIRST      (PENDING_BYTE+2)
9164 #define SHARED_SIZE       510
9165 
9166 /*
9167 ** Wrapper around OS specific sqlite3_os_init() function.
9168 */
9169 SQLITE_PRIVATE int sqlite3OsInit(void);
9170 
9171 /*
9172 ** Functions for accessing sqlite3_file methods
9173 */
9174 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9175 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9176 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9177 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9178 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9179 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9180 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9181 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9182 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9183 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9184 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9185 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9186 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9187 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9188 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9189 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9190 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9191 
9192 /*
9193 ** Functions for accessing sqlite3_vfs methods
9194 */
9195 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9196 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9197 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9198 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9199 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9200 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9201 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9202 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9203 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9204 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9205 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9206 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9207 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9208 
9209 /*
9210 ** Convenience functions for opening and closing files using
9211 ** sqlite3_malloc() to obtain space for the file-handle structure.
9212 */
9213 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9214 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9215 
9216 #endif /* _SQLITE_OS_H_ */
9217 
9218 /************** End of os.h **************************************************/
9219 /************** Continuing where we left off in sqliteInt.h ******************/
9220 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9221 /************** Begin file mutex.h *******************************************/
9222 /*
9223 ** 2007 August 28
9224 **
9225 ** The author disclaims copyright to this source code.  In place of
9226 ** a legal notice, here is a blessing:
9227 **
9228 **    May you do good and not evil.
9229 **    May you find forgiveness for yourself and forgive others.
9230 **    May you share freely, never taking more than you give.
9231 **
9232 *************************************************************************
9233 **
9234 ** This file contains the common header for all mutex implementations.
9235 ** The sqliteInt.h header #includes this file so that it is available
9236 ** to all source files.  We break it out in an effort to keep the code
9237 ** better organized.
9238 **
9239 ** NOTE:  source files should *not* #include this header file directly.
9240 ** Source files should #include the sqliteInt.h file and let that file
9241 ** include this one indirectly.
9242 */
9243 
9244 
9245 /*
9246 ** Figure out what version of the code to use.  The choices are
9247 **
9248 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9249 **                             mutexes implemention cannot be overridden
9250 **                             at start-time.
9251 **
9252 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9253 **                             mutual exclusion is provided.  But this
9254 **                             implementation can be overridden at
9255 **                             start-time.
9256 **
9257 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9258 **
9259 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9260 **
9261 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9262 */
9263 #if !SQLITE_THREADSAFE
9264 # define SQLITE_MUTEX_OMIT
9265 #endif
9266 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9267 #  if SQLITE_OS_UNIX
9268 #    define SQLITE_MUTEX_PTHREADS
9269 #  elif SQLITE_OS_WIN
9270 #    define SQLITE_MUTEX_W32
9271 #  elif SQLITE_OS_OS2
9272 #    define SQLITE_MUTEX_OS2
9273 #  else
9274 #    define SQLITE_MUTEX_NOOP
9275 #  endif
9276 #endif
9277 
9278 #ifdef SQLITE_MUTEX_OMIT
9279 /*
9280 ** If this is a no-op implementation, implement everything as macros.
9281 */
9282 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9283 #define sqlite3_mutex_free(X)
9284 #define sqlite3_mutex_enter(X)
9285 #define sqlite3_mutex_try(X)      SQLITE_OK
9286 #define sqlite3_mutex_leave(X)
9287 #define sqlite3_mutex_held(X)     ((void)(X),1)
9288 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9289 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9290 #define sqlite3MutexInit()        SQLITE_OK
9291 #define sqlite3MutexEnd()
9292 #endif /* defined(SQLITE_MUTEX_OMIT) */
9293 
9294 /************** End of mutex.h ***********************************************/
9295 /************** Continuing where we left off in sqliteInt.h ******************/
9296 
9297 
9298 /*
9299 ** Each database file to be accessed by the system is an instance
9300 ** of the following structure.  There are normally two of these structures
9301 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9302 ** aDb[1] is the database file used to hold temporary tables.  Additional
9303 ** databases may be attached.
9304 */
9305 struct Db {
9306   char *zName;         /* Name of this database */
9307   Btree *pBt;          /* The B*Tree structure for this database file */
9308   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9309   u8 safety_level;     /* How aggressive at syncing data to disk */
9310   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9311 };
9312 
9313 /*
9314 ** An instance of the following structure stores a database schema.
9315 **
9316 ** Most Schema objects are associated with a Btree.  The exception is
9317 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9318 ** In shared cache mode, a single Schema object can be shared by multiple
9319 ** Btrees that refer to the same underlying BtShared object.
9320 **
9321 ** Schema objects are automatically deallocated when the last Btree that
9322 ** references them is destroyed.   The TEMP Schema is manually freed by
9323 ** sqlite3_close().
9324 *
9325 ** A thread must be holding a mutex on the corresponding Btree in order
9326 ** to access Schema content.  This implies that the thread must also be
9327 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9328 ** For a TEMP Schema, only the connection mutex is required.
9329 */
9330 struct Schema {
9331   int schema_cookie;   /* Database schema version number for this file */
9332   int iGeneration;     /* Generation counter.  Incremented with each change */
9333   Hash tblHash;        /* All tables indexed by name */
9334   Hash idxHash;        /* All (named) indices indexed by name */
9335   Hash trigHash;       /* All triggers indexed by name */
9336   Hash fkeyHash;       /* All foreign keys by referenced table name */
9337   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9338   u8 file_format;      /* Schema format version for this file */
9339   u8 enc;              /* Text encoding used by this database */
9340   u16 flags;           /* Flags associated with this schema */
9341   int cache_size;      /* Number of pages to use in the cache */
9342 };
9343 
9344 /*
9345 ** These macros can be used to test, set, or clear bits in the
9346 ** Db.pSchema->flags field.
9347 */
9348 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9349 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9350 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9351 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9352 
9353 /*
9354 ** Allowed values for the DB.pSchema->flags field.
9355 **
9356 ** The DB_SchemaLoaded flag is set after the database schema has been
9357 ** read into internal hash tables.
9358 **
9359 ** DB_UnresetViews means that one or more views have column names that
9360 ** have been filled out.  If the schema changes, these column names might
9361 ** changes and so the view will need to be reset.
9362 */
9363 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9364 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9365 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9366 
9367 /*
9368 ** The number of different kinds of things that can be limited
9369 ** using the sqlite3_limit() interface.
9370 */
9371 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9372 
9373 /*
9374 ** Lookaside malloc is a set of fixed-size buffers that can be used
9375 ** to satisfy small transient memory allocation requests for objects
9376 ** associated with a particular database connection.  The use of
9377 ** lookaside malloc provides a significant performance enhancement
9378 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9379 ** SQL statements.
9380 **
9381 ** The Lookaside structure holds configuration information about the
9382 ** lookaside malloc subsystem.  Each available memory allocation in
9383 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9384 ** objects.
9385 **
9386 ** Lookaside allocations are only allowed for objects that are associated
9387 ** with a particular database connection.  Hence, schema information cannot
9388 ** be stored in lookaside because in shared cache mode the schema information
9389 ** is shared by multiple database connections.  Therefore, while parsing
9390 ** schema information, the Lookaside.bEnabled flag is cleared so that
9391 ** lookaside allocations are not used to construct the schema objects.
9392 */
9393 struct Lookaside {
9394   u16 sz;                 /* Size of each buffer in bytes */
9395   u8 bEnabled;            /* False to disable new lookaside allocations */
9396   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9397   int nOut;               /* Number of buffers currently checked out */
9398   int mxOut;              /* Highwater mark for nOut */
9399   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9400   LookasideSlot *pFree;   /* List of available buffers */
9401   void *pStart;           /* First byte of available memory space */
9402   void *pEnd;             /* First byte past end of available space */
9403 };
9404 struct LookasideSlot {
9405   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9406 };
9407 
9408 /*
9409 ** A hash table for function definitions.
9410 **
9411 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9412 ** Collisions are on the FuncDef.pHash chain.
9413 */
9414 struct FuncDefHash {
9415   FuncDef *a[23];       /* Hash table for functions */
9416 };
9417 
9418 /*
9419 ** Each database connection is an instance of the following structure.
9420 **
9421 ** The sqlite.lastRowid records the last insert rowid generated by an
9422 ** insert statement.  Inserts on views do not affect its value.  Each
9423 ** trigger has its own context, so that lastRowid can be updated inside
9424 ** triggers as usual.  The previous value will be restored once the trigger
9425 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
9426 ** longer (since after version 2.8.12) reset to -1.
9427 **
9428 ** The sqlite.nChange does not count changes within triggers and keeps no
9429 ** context.  It is reset at start of sqlite3_exec.
9430 ** The sqlite.lsChange represents the number of changes made by the last
9431 ** insert, update, or delete statement.  It remains constant throughout the
9432 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
9433 ** context stack just like lastRowid so that the count of changes
9434 ** within a trigger is not seen outside the trigger.  Changes to views do not
9435 ** affect the value of lsChange.
9436 ** The sqlite.csChange keeps track of the number of current changes (since
9437 ** the last statement) and is used to update sqlite_lsChange.
9438 **
9439 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
9440 ** store the most recent error code and, if applicable, string. The
9441 ** internal function sqlite3Error() is used to set these variables
9442 ** consistently.
9443 */
9444 struct sqlite3 {
9445   sqlite3_vfs *pVfs;            /* OS Interface */
9446   int nDb;                      /* Number of backends currently in use */
9447   Db *aDb;                      /* All backends */
9448   int flags;                    /* Miscellaneous flags. See below */
9449   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9450   int errCode;                  /* Most recent error code (SQLITE_*) */
9451   int errMask;                  /* & result codes with this before returning */
9452   u8 autoCommit;                /* The auto-commit flag. */
9453   u8 temp_store;                /* 1: file 2: memory 0: default */
9454   u8 mallocFailed;              /* True if we have seen a malloc failure */
9455   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9456   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9457   u8 suppressErr;               /* Do not issue error messages if true */
9458   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9459   int nextPagesize;             /* Pagesize after VACUUM if >0 */
9460   int nTable;                   /* Number of tables in the database */
9461   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9462   i64 lastRowid;                /* ROWID of most recent insert (see above) */
9463   u32 magic;                    /* Magic number for detect library misuse */
9464   int nChange;                  /* Value returned by sqlite3_changes() */
9465   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9466   sqlite3_mutex *mutex;         /* Connection mutex */
9467   int aLimit[SQLITE_N_LIMIT];   /* Limits */
9468   struct sqlite3InitInfo {      /* Information used during initialization */
9469     int iDb;                    /* When back is being initialized */
9470     int newTnum;                /* Rootpage of table being initialized */
9471     u8 busy;                    /* TRUE if currently initializing */
9472     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9473   } init;
9474   int nExtension;               /* Number of loaded extensions */
9475   void **aExtension;            /* Array of shared library handles */
9476   struct Vdbe *pVdbe;           /* List of active virtual machines */
9477   int activeVdbeCnt;            /* Number of VDBEs currently executing */
9478   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9479   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9480   void (*xTrace)(void*,const char*);        /* Trace function */
9481   void *pTraceArg;                          /* Argument to the trace function */
9482   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9483   void *pProfileArg;                        /* Argument to profile function */
9484   void *pCommitArg;                 /* Argument to xCommitCallback() */
9485   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9486   void *pRollbackArg;               /* Argument to xRollbackCallback() */
9487   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9488   void *pUpdateArg;
9489   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9490 #ifndef SQLITE_OMIT_WAL
9491   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9492   void *pWalArg;
9493 #endif
9494   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9495   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9496   void *pCollNeededArg;
9497   sqlite3_value *pErr;          /* Most recent error message */
9498   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9499   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9500   union {
9501     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9502     double notUsed1;            /* Spacer */
9503   } u1;
9504   Lookaside lookaside;          /* Lookaside malloc configuration */
9505 #ifndef SQLITE_OMIT_AUTHORIZATION
9506   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9507                                 /* Access authorization function */
9508   void *pAuthArg;               /* 1st argument to the access auth function */
9509 #endif
9510 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9511   int (*xProgress)(void *);     /* The progress callback */
9512   void *pProgressArg;           /* Argument to the progress callback */
9513   int nProgressOps;             /* Number of opcodes for progress callback */
9514 #endif
9515 #ifndef SQLITE_OMIT_VIRTUALTABLE
9516   Hash aModule;                 /* populated by sqlite3_create_module() */
9517   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9518   VTable **aVTrans;             /* Virtual tables with open transactions */
9519   int nVTrans;                  /* Allocated size of aVTrans */
9520   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9521 #endif
9522   FuncDefHash aFunc;            /* Hash table of connection functions */
9523   Hash aCollSeq;                /* All collating sequences */
9524   BusyHandler busyHandler;      /* Busy callback */
9525   int busyTimeout;              /* Busy handler timeout, in msec */
9526   Db aDbStatic[2];              /* Static space for the 2 default backends */
9527   Savepoint *pSavepoint;        /* List of active savepoints */
9528   int nSavepoint;               /* Number of non-transaction savepoints */
9529   int nStatement;               /* Number of nested statement-transactions  */
9530   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9531   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9532   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9533 
9534 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9535   /* The following variables are all protected by the STATIC_MASTER
9536   ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9537   **
9538   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9539   ** unlock so that it can proceed.
9540   **
9541   ** When X.pBlockingConnection==Y, that means that something that X tried
9542   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9543   ** held by Y.
9544   */
9545   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9546   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9547   void *pUnlockArg;                     /* Argument to xUnlockNotify */
9548   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9549   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9550 #endif
9551 };
9552 
9553 /*
9554 ** A macro to discover the encoding of a database.
9555 */
9556 #define ENC(db) ((db)->aDb[0].pSchema->enc)
9557 
9558 /*
9559 ** Possible values for the sqlite3.flags.
9560 */
9561 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9562 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9563 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9564 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9565 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9566                                           /*   DELETE, or UPDATE and return */
9567                                           /*   the count using a callback. */
9568 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9569                                           /*   result set is empty */
9570 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9571 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9572 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9573 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
9574                                           ** accessing read-only databases */
9575 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9576 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9577 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9578 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9579 #define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9580 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9581 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9582 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9583 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9584 #define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9585 #define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9586 #define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9587 #define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9588 
9589 /*
9590 ** Bits of the sqlite3.flags field that are used by the
9591 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9592 ** These must be the low-order bits of the flags field.
9593 */
9594 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9595 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9596 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9597 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9598 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
9599 #define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9600 #define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9601 #define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9602 #define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
9603 #define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9604 
9605 /*
9606 ** Possible values for the sqlite.magic field.
9607 ** The numbers are obtained at random and have no special meaning, other
9608 ** than being distinct from one another.
9609 */
9610 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9611 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9612 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9613 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9614 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9615 
9616 /*
9617 ** Each SQL function is defined by an instance of the following
9618 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
9619 ** hash table.  When multiple functions have the same name, the hash table
9620 ** points to a linked list of these structures.
9621 */
9622 struct FuncDef {
9623   i16 nArg;            /* Number of arguments.  -1 means unlimited */
9624   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9625   u8 flags;            /* Some combination of SQLITE_FUNC_* */
9626   void *pUserData;     /* User data parameter */
9627   FuncDef *pNext;      /* Next function with same name */
9628   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9629   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9630   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9631   char *zName;         /* SQL name of the function. */
9632   FuncDef *pHash;      /* Next with a different name but the same hash */
9633   FuncDestructor *pDestructor;   /* Reference counted destructor function */
9634 };
9635 
9636 /*
9637 ** This structure encapsulates a user-function destructor callback (as
9638 ** configured using create_function_v2()) and a reference counter. When
9639 ** create_function_v2() is called to create a function with a destructor,
9640 ** a single object of this type is allocated. FuncDestructor.nRef is set to
9641 ** the number of FuncDef objects created (either 1 or 3, depending on whether
9642 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9643 ** member of each of the new FuncDef objects is set to point to the allocated
9644 ** FuncDestructor.
9645 **
9646 ** Thereafter, when one of the FuncDef objects is deleted, the reference
9647 ** count on this object is decremented. When it reaches 0, the destructor
9648 ** is invoked and the FuncDestructor structure freed.
9649 */
9650 struct FuncDestructor {
9651   int nRef;
9652   void (*xDestroy)(void *);
9653   void *pUserData;
9654 };
9655 
9656 /*
9657 ** Possible values for FuncDef.flags
9658 */
9659 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9660 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9661 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9662 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9663 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
9664 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9665 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9666 
9667 /*
9668 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9669 ** used to create the initializers for the FuncDef structures.
9670 **
9671 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9672 **     Used to create a scalar function definition of a function zName
9673 **     implemented by C function xFunc that accepts nArg arguments. The
9674 **     value passed as iArg is cast to a (void*) and made available
9675 **     as the user-data (sqlite3_user_data()) for the function. If
9676 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9677 **
9678 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9679 **     Used to create an aggregate function definition implemented by
9680 **     the C functions xStep and xFinal. The first four parameters
9681 **     are interpreted in the same way as the first 4 parameters to
9682 **     FUNCTION().
9683 **
9684 **   LIKEFUNC(zName, nArg, pArg, flags)
9685 **     Used to create a scalar function definition of a function zName
9686 **     that accepts nArg arguments and is implemented by a call to C
9687 **     function likeFunc. Argument pArg is cast to a (void *) and made
9688 **     available as the function user-data (sqlite3_user_data()). The
9689 **     FuncDef.flags variable is set to the value passed as the flags
9690 **     parameter.
9691 */
9692 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9693   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9694    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9695 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9696   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9697    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9698 #define LIKEFUNC(zName, nArg, arg, flags) \
9699   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9700 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9701   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9702    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9703 
9704 /*
9705 ** All current savepoints are stored in a linked list starting at
9706 ** sqlite3.pSavepoint. The first element in the list is the most recently
9707 ** opened savepoint. Savepoints are added to the list by the vdbe
9708 ** OP_Savepoint instruction.
9709 */
9710 struct Savepoint {
9711   char *zName;                        /* Savepoint name (nul-terminated) */
9712   i64 nDeferredCons;                  /* Number of deferred fk violations */
9713   Savepoint *pNext;                   /* Parent savepoint (if any) */
9714 };
9715 
9716 /*
9717 ** The following are used as the second parameter to sqlite3Savepoint(),
9718 ** and as the P1 argument to the OP_Savepoint instruction.
9719 */
9720 #define SAVEPOINT_BEGIN      0
9721 #define SAVEPOINT_RELEASE    1
9722 #define SAVEPOINT_ROLLBACK   2
9723 
9724 
9725 /*
9726 ** Each SQLite module (virtual table definition) is defined by an
9727 ** instance of the following structure, stored in the sqlite3.aModule
9728 ** hash table.
9729 */
9730 struct Module {
9731   const sqlite3_module *pModule;       /* Callback pointers */
9732   const char *zName;                   /* Name passed to create_module() */
9733   void *pAux;                          /* pAux passed to create_module() */
9734   void (*xDestroy)(void *);            /* Module destructor function */
9735 };
9736 
9737 /*
9738 ** information about each column of an SQL table is held in an instance
9739 ** of this structure.
9740 */
9741 struct Column {
9742   char *zName;     /* Name of this column */
9743   Expr *pDflt;     /* Default value of this column */
9744   char *zDflt;     /* Original text of the default value */
9745   char *zType;     /* Data type for this column */
9746   char *zColl;     /* Collating sequence.  If NULL, use the default */
9747   u8 notNull;      /* True if there is a NOT NULL constraint */
9748   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
9749   char affinity;   /* One of the SQLITE_AFF_... values */
9750 #ifndef SQLITE_OMIT_VIRTUALTABLE
9751   u8 isHidden;     /* True if this column is 'hidden' */
9752 #endif
9753 };
9754 
9755 /*
9756 ** A "Collating Sequence" is defined by an instance of the following
9757 ** structure. Conceptually, a collating sequence consists of a name and
9758 ** a comparison routine that defines the order of that sequence.
9759 **
9760 ** There may two separate implementations of the collation function, one
9761 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
9762 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
9763 ** native byte order. When a collation sequence is invoked, SQLite selects
9764 ** the version that will require the least expensive encoding
9765 ** translations, if any.
9766 **
9767 ** The CollSeq.pUser member variable is an extra parameter that passed in
9768 ** as the first argument to the UTF-8 comparison function, xCmp.
9769 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
9770 ** xCmp16.
9771 **
9772 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
9773 ** collating sequence is undefined.  Indices built on an undefined
9774 ** collating sequence may not be read or written.
9775 */
9776 struct CollSeq {
9777   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
9778   u8 enc;               /* Text encoding handled by xCmp() */
9779   u8 type;              /* One of the SQLITE_COLL_... values below */
9780   void *pUser;          /* First argument to xCmp() */
9781   int (*xCmp)(void*,int, const void*, int, const void*);
9782   void (*xDel)(void*);  /* Destructor for pUser */
9783 };
9784 
9785 /*
9786 ** Allowed values of CollSeq.type:
9787 */
9788 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
9789 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
9790 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
9791 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
9792 
9793 /*
9794 ** A sort order can be either ASC or DESC.
9795 */
9796 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
9797 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
9798 
9799 /*
9800 ** Column affinity types.
9801 **
9802 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
9803 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
9804 ** the speed a little by numbering the values consecutively.
9805 **
9806 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
9807 ** when multiple affinity types are concatenated into a string and
9808 ** used as the P4 operand, they will be more readable.
9809 **
9810 ** Note also that the numeric types are grouped together so that testing
9811 ** for a numeric type is a single comparison.
9812 */
9813 #define SQLITE_AFF_TEXT     'a'
9814 #define SQLITE_AFF_NONE     'b'
9815 #define SQLITE_AFF_NUMERIC  'c'
9816 #define SQLITE_AFF_INTEGER  'd'
9817 #define SQLITE_AFF_REAL     'e'
9818 
9819 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
9820 
9821 /*
9822 ** The SQLITE_AFF_MASK values masks off the significant bits of an
9823 ** affinity value.
9824 */
9825 #define SQLITE_AFF_MASK     0x67
9826 
9827 /*
9828 ** Additional bit values that can be ORed with an affinity without
9829 ** changing the affinity.
9830 */
9831 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
9832 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
9833 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
9834 
9835 /*
9836 ** An object of this type is created for each virtual table present in
9837 ** the database schema.
9838 **
9839 ** If the database schema is shared, then there is one instance of this
9840 ** structure for each database connection (sqlite3*) that uses the shared
9841 ** schema. This is because each database connection requires its own unique
9842 ** instance of the sqlite3_vtab* handle used to access the virtual table
9843 ** implementation. sqlite3_vtab* handles can not be shared between
9844 ** database connections, even when the rest of the in-memory database
9845 ** schema is shared, as the implementation often stores the database
9846 ** connection handle passed to it via the xConnect() or xCreate() method
9847 ** during initialization internally. This database connection handle may
9848 ** then be used by the virtual table implementation to access real tables
9849 ** within the database. So that they appear as part of the callers
9850 ** transaction, these accesses need to be made via the same database
9851 ** connection as that used to execute SQL operations on the virtual table.
9852 **
9853 ** All VTable objects that correspond to a single table in a shared
9854 ** database schema are initially stored in a linked-list pointed to by
9855 ** the Table.pVTable member variable of the corresponding Table object.
9856 ** When an sqlite3_prepare() operation is required to access the virtual
9857 ** table, it searches the list for the VTable that corresponds to the
9858 ** database connection doing the preparing so as to use the correct
9859 ** sqlite3_vtab* handle in the compiled query.
9860 **
9861 ** When an in-memory Table object is deleted (for example when the
9862 ** schema is being reloaded for some reason), the VTable objects are not
9863 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
9864 ** immediately. Instead, they are moved from the Table.pVTable list to
9865 ** another linked list headed by the sqlite3.pDisconnect member of the
9866 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
9867 ** next time a statement is prepared using said sqlite3*. This is done
9868 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
9869 ** Refer to comments above function sqlite3VtabUnlockList() for an
9870 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
9871 ** list without holding the corresponding sqlite3.mutex mutex.
9872 **
9873 ** The memory for objects of this type is always allocated by
9874 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
9875 ** the first argument.
9876 */
9877 struct VTable {
9878   sqlite3 *db;              /* Database connection associated with this table */
9879   Module *pMod;             /* Pointer to module implementation */
9880   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
9881   int nRef;                 /* Number of pointers to this structure */
9882   u8 bConstraint;           /* True if constraints are supported */
9883   int iSavepoint;           /* Depth of the SAVEPOINT stack */
9884   VTable *pNext;            /* Next in linked list (see above) */
9885 };
9886 
9887 /*
9888 ** Each SQL table is represented in memory by an instance of the
9889 ** following structure.
9890 **
9891 ** Table.zName is the name of the table.  The case of the original
9892 ** CREATE TABLE statement is stored, but case is not significant for
9893 ** comparisons.
9894 **
9895 ** Table.nCol is the number of columns in this table.  Table.aCol is a
9896 ** pointer to an array of Column structures, one for each column.
9897 **
9898 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
9899 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
9900 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
9901 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
9902 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
9903 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
9904 ** the table has any PRIMARY KEY, INTEGER or otherwise.
9905 **
9906 ** Table.tnum is the page number for the root BTree page of the table in the
9907 ** database file.  If Table.iDb is the index of the database table backend
9908 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
9909 ** holds temporary tables and indices.  If TF_Ephemeral is set
9910 ** then the table is stored in a file that is automatically deleted
9911 ** when the VDBE cursor to the table is closed.  In this case Table.tnum
9912 ** refers VDBE cursor number that holds the table open, not to the root
9913 ** page number.  Transient tables are used to hold the results of a
9914 ** sub-query that appears instead of a real table name in the FROM clause
9915 ** of a SELECT statement.
9916 */
9917 struct Table {
9918   char *zName;         /* Name of the table or view */
9919   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
9920   int nCol;            /* Number of columns in this table */
9921   Column *aCol;        /* Information about each column */
9922   Index *pIndex;       /* List of SQL indexes on this table. */
9923   int tnum;            /* Root BTree node for this table (see note above) */
9924   unsigned nRowEst;    /* Estimated rows in table - from sqlite_stat1 table */
9925   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
9926   u16 nRef;            /* Number of pointers to this Table */
9927   u8 tabFlags;         /* Mask of TF_* values */
9928   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
9929   FKey *pFKey;         /* Linked list of all foreign keys in this table */
9930   char *zColAff;       /* String defining the affinity of each column */
9931 #ifndef SQLITE_OMIT_CHECK
9932   Expr *pCheck;        /* The AND of all CHECK constraints */
9933 #endif
9934 #ifndef SQLITE_OMIT_ALTERTABLE
9935   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
9936 #endif
9937 #ifndef SQLITE_OMIT_VIRTUALTABLE
9938   VTable *pVTable;     /* List of VTable objects. */
9939   int nModuleArg;      /* Number of arguments to the module */
9940   char **azModuleArg;  /* Text of all module args. [0] is module name */
9941 #endif
9942   Trigger *pTrigger;   /* List of triggers stored in pSchema */
9943   Schema *pSchema;     /* Schema that contains this table */
9944   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
9945 };
9946 
9947 /*
9948 ** Allowed values for Tabe.tabFlags.
9949 */
9950 #define TF_Readonly        0x01    /* Read-only system table */
9951 #define TF_Ephemeral       0x02    /* An ephemeral table */
9952 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
9953 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
9954 #define TF_Virtual         0x10    /* Is a virtual table */
9955 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
9956 
9957 
9958 
9959 /*
9960 ** Test to see whether or not a table is a virtual table.  This is
9961 ** done as a macro so that it will be optimized out when virtual
9962 ** table support is omitted from the build.
9963 */
9964 #ifndef SQLITE_OMIT_VIRTUALTABLE
9965 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
9966 #  define IsHiddenColumn(X) ((X)->isHidden)
9967 #else
9968 #  define IsVirtual(X)      0
9969 #  define IsHiddenColumn(X) 0
9970 #endif
9971 
9972 /*
9973 ** Each foreign key constraint is an instance of the following structure.
9974 **
9975 ** A foreign key is associated with two tables.  The "from" table is
9976 ** the table that contains the REFERENCES clause that creates the foreign
9977 ** key.  The "to" table is the table that is named in the REFERENCES clause.
9978 ** Consider this example:
9979 **
9980 **     CREATE TABLE ex1(
9981 **       a INTEGER PRIMARY KEY,
9982 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
9983 **     );
9984 **
9985 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
9986 **
9987 ** Each REFERENCES clause generates an instance of the following structure
9988 ** which is attached to the from-table.  The to-table need not exist when
9989 ** the from-table is created.  The existence of the to-table is not checked.
9990 */
9991 struct FKey {
9992   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
9993   FKey *pNextFrom;  /* Next foreign key in pFrom */
9994   char *zTo;        /* Name of table that the key points to (aka: Parent) */
9995   FKey *pNextTo;    /* Next foreign key on table named zTo */
9996   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
9997   int nCol;         /* Number of columns in this key */
9998   /* EV: R-30323-21917 */
9999   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10000   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10001   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10002   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10003     int iFrom;         /* Index of column in pFrom */
10004     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10005   } aCol[1];        /* One entry for each of nCol column s */
10006 };
10007 
10008 /*
10009 ** SQLite supports many different ways to resolve a constraint
10010 ** error.  ROLLBACK processing means that a constraint violation
10011 ** causes the operation in process to fail and for the current transaction
10012 ** to be rolled back.  ABORT processing means the operation in process
10013 ** fails and any prior changes from that one operation are backed out,
10014 ** but the transaction is not rolled back.  FAIL processing means that
10015 ** the operation in progress stops and returns an error code.  But prior
10016 ** changes due to the same operation are not backed out and no rollback
10017 ** occurs.  IGNORE means that the particular row that caused the constraint
10018 ** error is not inserted or updated.  Processing continues and no error
10019 ** is returned.  REPLACE means that preexisting database rows that caused
10020 ** a UNIQUE constraint violation are removed so that the new insert or
10021 ** update can proceed.  Processing continues and no error is reported.
10022 **
10023 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10024 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10025 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10026 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10027 ** referenced table row is propagated into the row that holds the
10028 ** foreign key.
10029 **
10030 ** The following symbolic values are used to record which type
10031 ** of action to take.
10032 */
10033 #define OE_None     0   /* There is no constraint to check */
10034 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10035 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10036 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10037 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10038 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10039 
10040 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10041 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10042 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10043 #define OE_Cascade  9   /* Cascade the changes */
10044 
10045 #define OE_Default  99  /* Do whatever the default action is */
10046 
10047 
10048 /*
10049 ** An instance of the following structure is passed as the first
10050 ** argument to sqlite3VdbeKeyCompare and is used to control the
10051 ** comparison of the two index keys.
10052 */
10053 struct KeyInfo {
10054   sqlite3 *db;        /* The database connection */
10055   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10056   u16 nField;         /* Number of entries in aColl[] */
10057   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10058   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10059 };
10060 
10061 /*
10062 ** An instance of the following structure holds information about a
10063 ** single index record that has already been parsed out into individual
10064 ** values.
10065 **
10066 ** A record is an object that contains one or more fields of data.
10067 ** Records are used to store the content of a table row and to store
10068 ** the key of an index.  A blob encoding of a record is created by
10069 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10070 ** OP_Column opcode.
10071 **
10072 ** This structure holds a record that has already been disassembled
10073 ** into its constituent fields.
10074 */
10075 struct UnpackedRecord {
10076   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10077   u16 nField;         /* Number of entries in apMem[] */
10078   u16 flags;          /* Boolean settings.  UNPACKED_... below */
10079   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10080   Mem *aMem;          /* Values */
10081 };
10082 
10083 /*
10084 ** Allowed values of UnpackedRecord.flags
10085 */
10086 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
10087 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
10088 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
10089 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
10090 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
10091 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
10092 
10093 /*
10094 ** Each SQL index is represented in memory by an
10095 ** instance of the following structure.
10096 **
10097 ** The columns of the table that are to be indexed are described
10098 ** by the aiColumn[] field of this structure.  For example, suppose
10099 ** we have the following table and index:
10100 **
10101 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10102 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10103 **
10104 ** In the Table structure describing Ex1, nCol==3 because there are
10105 ** three columns in the table.  In the Index structure describing
10106 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10107 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10108 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10109 ** The second column to be indexed (c1) has an index of 0 in
10110 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10111 **
10112 ** The Index.onError field determines whether or not the indexed columns
10113 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10114 ** it means this is not a unique index.  Otherwise it is a unique index
10115 ** and the value of Index.onError indicate the which conflict resolution
10116 ** algorithm to employ whenever an attempt is made to insert a non-unique
10117 ** element.
10118 */
10119 struct Index {
10120   char *zName;     /* Name of this index */
10121   int nColumn;     /* Number of columns in the table used by this index */
10122   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10123   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10124   Table *pTable;   /* The SQL table being indexed */
10125   int tnum;        /* Page containing root of this index in database file */
10126   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10127   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10128   u8 bUnordered;   /* Use this index for == or IN queries only */
10129   char *zColAff;   /* String defining the affinity of each column */
10130   Index *pNext;    /* The next index associated with the same table */
10131   Schema *pSchema; /* Schema containing this index */
10132   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10133   char **azColl;   /* Array of collation sequence names for index */
10134   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
10135 };
10136 
10137 /*
10138 ** Each sample stored in the sqlite_stat2 table is represented in memory
10139 ** using a structure of this type.
10140 */
10141 struct IndexSample {
10142   union {
10143     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10144     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
10145   } u;
10146   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10147   u8 nByte;         /* Size in byte of text or blob. */
10148 };
10149 
10150 /*
10151 ** Each token coming out of the lexer is an instance of
10152 ** this structure.  Tokens are also used as part of an expression.
10153 **
10154 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10155 ** may contain random values.  Do not make any assumptions about Token.dyn
10156 ** and Token.n when Token.z==0.
10157 */
10158 struct Token {
10159   const char *z;     /* Text of the token.  Not NULL-terminated! */
10160   unsigned int n;    /* Number of characters in this token */
10161 };
10162 
10163 /*
10164 ** An instance of this structure contains information needed to generate
10165 ** code for a SELECT that contains aggregate functions.
10166 **
10167 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10168 ** pointer to this structure.  The Expr.iColumn field is the index in
10169 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10170 ** code for that node.
10171 **
10172 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10173 ** original Select structure that describes the SELECT statement.  These
10174 ** fields do not need to be freed when deallocating the AggInfo structure.
10175 */
10176 struct AggInfo {
10177   u8 directMode;          /* Direct rendering mode means take data directly
10178                           ** from source tables rather than from accumulators */
10179   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10180                           ** than the source table */
10181   int sortingIdx;         /* Cursor number of the sorting index */
10182   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10183   ExprList *pGroupBy;     /* The group by clause */
10184   int nSortingColumn;     /* Number of columns in the sorting index */
10185   struct AggInfo_col {    /* For each column used in source tables */
10186     Table *pTab;             /* Source table */
10187     int iTable;              /* Cursor number of the source table */
10188     int iColumn;             /* Column number within the source table */
10189     int iSorterColumn;       /* Column number in the sorting index */
10190     int iMem;                /* Memory location that acts as accumulator */
10191     Expr *pExpr;             /* The original expression */
10192   } *aCol;
10193   int nColumn;            /* Number of used entries in aCol[] */
10194   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
10195   int nAccumulator;       /* Number of columns that show through to the output.
10196                           ** Additional columns are used only as parameters to
10197                           ** aggregate functions */
10198   struct AggInfo_func {   /* For each aggregate function */
10199     Expr *pExpr;             /* Expression encoding the function */
10200     FuncDef *pFunc;          /* The aggregate function implementation */
10201     int iMem;                /* Memory location that acts as accumulator */
10202     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10203   } *aFunc;
10204   int nFunc;              /* Number of entries in aFunc[] */
10205   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
10206 };
10207 
10208 /*
10209 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10210 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10211 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10212 ** it uses less memory in the Expr object, which is a big memory user
10213 ** in systems with lots of prepared statements.  And few applications
10214 ** need more than about 10 or 20 variables.  But some extreme users want
10215 ** to have prepared statements with over 32767 variables, and for them
10216 ** the option is available (at compile-time).
10217 */
10218 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10219 typedef i16 ynVar;
10220 #else
10221 typedef int ynVar;
10222 #endif
10223 
10224 /*
10225 ** Each node of an expression in the parse tree is an instance
10226 ** of this structure.
10227 **
10228 ** Expr.op is the opcode. The integer parser token codes are reused
10229 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10230 ** code representing the ">=" operator. This same integer code is reused
10231 ** to represent the greater-than-or-equal-to operator in the expression
10232 ** tree.
10233 **
10234 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10235 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10236 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10237 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10238 ** then Expr.token contains the name of the function.
10239 **
10240 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10241 ** binary operator. Either or both may be NULL.
10242 **
10243 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10244 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10245 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10246 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10247 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10248 ** valid.
10249 **
10250 ** An expression of the form ID or ID.ID refers to a column in a table.
10251 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10252 ** the integer cursor number of a VDBE cursor pointing to that table and
10253 ** Expr.iColumn is the column number for the specific column.  If the
10254 ** expression is used as a result in an aggregate SELECT, then the
10255 ** value is also stored in the Expr.iAgg column in the aggregate so that
10256 ** it can be accessed after all aggregates are computed.
10257 **
10258 ** If the expression is an unbound variable marker (a question mark
10259 ** character '?' in the original SQL) then the Expr.iTable holds the index
10260 ** number for that variable.
10261 **
10262 ** If the expression is a subquery then Expr.iColumn holds an integer
10263 ** register number containing the result of the subquery.  If the
10264 ** subquery gives a constant result, then iTable is -1.  If the subquery
10265 ** gives a different answer at different times during statement processing
10266 ** then iTable is the address of a subroutine that computes the subquery.
10267 **
10268 ** If the Expr is of type OP_Column, and the table it is selecting from
10269 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10270 ** corresponding table definition.
10271 **
10272 ** ALLOCATION NOTES:
10273 **
10274 ** Expr objects can use a lot of memory space in database schema.  To
10275 ** help reduce memory requirements, sometimes an Expr object will be
10276 ** truncated.  And to reduce the number of memory allocations, sometimes
10277 ** two or more Expr objects will be stored in a single memory allocation,
10278 ** together with Expr.zToken strings.
10279 **
10280 ** If the EP_Reduced and EP_TokenOnly flags are set when
10281 ** an Expr object is truncated.  When EP_Reduced is set, then all
10282 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10283 ** are contained within the same memory allocation.  Note, however, that
10284 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10285 ** allocated, regardless of whether or not EP_Reduced is set.
10286 */
10287 struct Expr {
10288   u8 op;                 /* Operation performed by this node */
10289   char affinity;         /* The affinity of the column or 0 if not a column */
10290   u16 flags;             /* Various flags.  EP_* See below */
10291   union {
10292     char *zToken;          /* Token value. Zero terminated and dequoted */
10293     int iValue;            /* Non-negative integer value if EP_IntValue */
10294   } u;
10295 
10296   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10297   ** space is allocated for the fields below this point. An attempt to
10298   ** access them will result in a segfault or malfunction.
10299   *********************************************************************/
10300 
10301   Expr *pLeft;           /* Left subnode */
10302   Expr *pRight;          /* Right subnode */
10303   union {
10304     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10305     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10306   } x;
10307   CollSeq *pColl;        /* The collation type of the column or 0 */
10308 
10309   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10310   ** space is allocated for the fields below this point. An attempt to
10311   ** access them will result in a segfault or malfunction.
10312   *********************************************************************/
10313 
10314   int iTable;            /* TK_COLUMN: cursor number of table holding column
10315                          ** TK_REGISTER: register number
10316                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10317   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10318                          ** TK_VARIABLE: variable number (always >= 1). */
10319   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10320   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10321   u8 flags2;             /* Second set of flags.  EP2_... */
10322   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10323   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10324   Table *pTab;           /* Table for TK_COLUMN expressions. */
10325 #if SQLITE_MAX_EXPR_DEPTH>0
10326   int nHeight;           /* Height of the tree headed by this node */
10327 #endif
10328 };
10329 
10330 /*
10331 ** The following are the meanings of bits in the Expr.flags field.
10332 */
10333 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10334 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10335 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10336 #define EP_Error      0x0008  /* Expression contains one or more errors */
10337 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10338 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10339 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10340 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10341 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10342 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10343 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10344 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10345 
10346 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10347 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10348 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
10349 
10350 /*
10351 ** The following are the meanings of bits in the Expr.flags2 field.
10352 */
10353 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10354 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10355 
10356 /*
10357 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10358 ** flag on an expression structure.  This flag is used for VV&A only.  The
10359 ** routine is implemented as a macro that only works when in debugging mode,
10360 ** so as not to burden production code.
10361 */
10362 #ifdef SQLITE_DEBUG
10363 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10364 #else
10365 # define ExprSetIrreducible(X)
10366 #endif
10367 
10368 /*
10369 ** These macros can be used to test, set, or clear bits in the
10370 ** Expr.flags field.
10371 */
10372 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10373 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10374 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10375 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10376 
10377 /*
10378 ** Macros to determine the number of bytes required by a normal Expr
10379 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10380 ** and an Expr struct with the EP_TokenOnly flag set.
10381 */
10382 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10383 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10384 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10385 
10386 /*
10387 ** Flags passed to the sqlite3ExprDup() function. See the header comment
10388 ** above sqlite3ExprDup() for details.
10389 */
10390 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10391 
10392 /*
10393 ** A list of expressions.  Each expression may optionally have a
10394 ** name.  An expr/name combination can be used in several ways, such
10395 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10396 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10397 ** also be used as the argument to a function, in which case the a.zName
10398 ** field is not used.
10399 */
10400 struct ExprList {
10401   int nExpr;             /* Number of expressions on the list */
10402   int nAlloc;            /* Number of entries allocated below */
10403   int iECursor;          /* VDBE Cursor associated with this ExprList */
10404   struct ExprList_item {
10405     Expr *pExpr;           /* The list of expressions */
10406     char *zName;           /* Token associated with this expression */
10407     char *zSpan;           /* Original text of the expression */
10408     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10409     u8 done;               /* A flag to indicate when processing is finished */
10410     u16 iCol;              /* For ORDER BY, column number in result set */
10411     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10412   } *a;                  /* One entry for each expression */
10413 };
10414 
10415 /*
10416 ** An instance of this structure is used by the parser to record both
10417 ** the parse tree for an expression and the span of input text for an
10418 ** expression.
10419 */
10420 struct ExprSpan {
10421   Expr *pExpr;          /* The expression parse tree */
10422   const char *zStart;   /* First character of input text */
10423   const char *zEnd;     /* One character past the end of input text */
10424 };
10425 
10426 /*
10427 ** An instance of this structure can hold a simple list of identifiers,
10428 ** such as the list "a,b,c" in the following statements:
10429 **
10430 **      INSERT INTO t(a,b,c) VALUES ...;
10431 **      CREATE INDEX idx ON t(a,b,c);
10432 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10433 **
10434 ** The IdList.a.idx field is used when the IdList represents the list of
10435 ** column names after a table name in an INSERT statement.  In the statement
10436 **
10437 **     INSERT INTO t(a,b,c) ...
10438 **
10439 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10440 */
10441 struct IdList {
10442   struct IdList_item {
10443     char *zName;      /* Name of the identifier */
10444     int idx;          /* Index in some Table.aCol[] of a column named zName */
10445   } *a;
10446   int nId;         /* Number of identifiers on the list */
10447   int nAlloc;      /* Number of entries allocated for a[] below */
10448 };
10449 
10450 /*
10451 ** The bitmask datatype defined below is used for various optimizations.
10452 **
10453 ** Changing this from a 64-bit to a 32-bit type limits the number of
10454 ** tables in a join to 32 instead of 64.  But it also reduces the size
10455 ** of the library by 738 bytes on ix86.
10456 */
10457 typedef u64 Bitmask;
10458 
10459 /*
10460 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10461 */
10462 #define BMS  ((int)(sizeof(Bitmask)*8))
10463 
10464 /*
10465 ** The following structure describes the FROM clause of a SELECT statement.
10466 ** Each table or subquery in the FROM clause is a separate element of
10467 ** the SrcList.a[] array.
10468 **
10469 ** With the addition of multiple database support, the following structure
10470 ** can also be used to describe a particular table such as the table that
10471 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10472 ** such a table must be a simple name: ID.  But in SQLite, the table can
10473 ** now be identified by a database name, a dot, then the table name: ID.ID.
10474 **
10475 ** The jointype starts out showing the join type between the current table
10476 ** and the next table on the list.  The parser builds the list this way.
10477 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10478 ** jointype expresses the join between the table and the previous table.
10479 **
10480 ** In the colUsed field, the high-order bit (bit 63) is set if the table
10481 ** contains more than 63 columns and the 64-th or later column is used.
10482 */
10483 struct SrcList {
10484   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10485   i16 nAlloc;      /* Number of entries allocated in a[] below */
10486   struct SrcList_item {
10487     char *zDatabase;  /* Name of database holding this table */
10488     char *zName;      /* Name of the table */
10489     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10490     Table *pTab;      /* An SQL table corresponding to zName */
10491     Select *pSelect;  /* A SELECT statement used in place of a table name */
10492     int addrFillSub;  /* Address of subroutine to manifest a subquery */
10493     int regReturn;    /* Register holding return address of addrFillSub */
10494     u8 jointype;      /* Type of join between this able and the previous */
10495     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10496     u8 isCorrelated;  /* True if sub-query is correlated */
10497 #ifndef SQLITE_OMIT_EXPLAIN
10498     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10499 #endif
10500     int iCursor;      /* The VDBE cursor number used to access this table */
10501     Expr *pOn;        /* The ON clause of a join */
10502     IdList *pUsing;   /* The USING clause of a join */
10503     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10504     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10505     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10506   } a[1];             /* One entry for each identifier on the list */
10507 };
10508 
10509 /*
10510 ** Permitted values of the SrcList.a.jointype field
10511 */
10512 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
10513 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10514 #define JT_NATURAL   0x0004    /* True for a "natural" join */
10515 #define JT_LEFT      0x0008    /* Left outer join */
10516 #define JT_RIGHT     0x0010    /* Right outer join */
10517 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10518 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
10519 
10520 
10521 /*
10522 ** A WherePlan object holds information that describes a lookup
10523 ** strategy.
10524 **
10525 ** This object is intended to be opaque outside of the where.c module.
10526 ** It is included here only so that that compiler will know how big it
10527 ** is.  None of the fields in this object should be used outside of
10528 ** the where.c module.
10529 **
10530 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10531 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10532 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10533 ** case that more than one of these conditions is true.
10534 */
10535 struct WherePlan {
10536   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10537   u32 nEq;                       /* Number of == constraints */
10538   double nRow;                   /* Estimated number of rows (for EQP) */
10539   union {
10540     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10541     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10542     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10543   } u;
10544 };
10545 
10546 /*
10547 ** For each nested loop in a WHERE clause implementation, the WhereInfo
10548 ** structure contains a single instance of this structure.  This structure
10549 ** is intended to be private the the where.c module and should not be
10550 ** access or modified by other modules.
10551 **
10552 ** The pIdxInfo field is used to help pick the best index on a
10553 ** virtual table.  The pIdxInfo pointer contains indexing
10554 ** information for the i-th table in the FROM clause before reordering.
10555 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10556 ** All other information in the i-th WhereLevel object for the i-th table
10557 ** after FROM clause ordering.
10558 */
10559 struct WhereLevel {
10560   WherePlan plan;       /* query plan for this element of the FROM clause */
10561   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10562   int iTabCur;          /* The VDBE cursor used to access the table */
10563   int iIdxCur;          /* The VDBE cursor used to access pIdx */
10564   int addrBrk;          /* Jump here to break out of the loop */
10565   int addrNxt;          /* Jump here to start the next IN combination */
10566   int addrCont;         /* Jump here to continue with the next loop cycle */
10567   int addrFirst;        /* First instruction of interior of the loop */
10568   u8 iFrom;             /* Which entry in the FROM clause */
10569   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10570   int p1, p2;           /* Operands of the opcode used to ends the loop */
10571   union {               /* Information that depends on plan.wsFlags */
10572     struct {
10573       int nIn;              /* Number of entries in aInLoop[] */
10574       struct InLoop {
10575         int iCur;              /* The VDBE cursor used by this IN operator */
10576         int addrInTop;         /* Top of the IN loop */
10577       } *aInLoop;           /* Information about each nested IN operator */
10578     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10579   } u;
10580 
10581   /* The following field is really not part of the current level.  But
10582   ** we need a place to cache virtual table index information for each
10583   ** virtual table in the FROM clause and the WhereLevel structure is
10584   ** a convenient place since there is one WhereLevel for each FROM clause
10585   ** element.
10586   */
10587   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10588 };
10589 
10590 /*
10591 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10592 ** and the WhereInfo.wctrlFlags member.
10593 */
10594 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10595 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10596 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10597 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10598 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10599 #define WHERE_OMIT_OPEN        0x0010 /* Table cursors are already open */
10600 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
10601 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
10602 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
10603 
10604 /*
10605 ** The WHERE clause processing routine has two halves.  The
10606 ** first part does the start of the WHERE loop and the second
10607 ** half does the tail of the WHERE loop.  An instance of
10608 ** this structure is returned by the first half and passed
10609 ** into the second half to give some continuity.
10610 */
10611 struct WhereInfo {
10612   Parse *pParse;       /* Parsing and code generating context */
10613   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10614   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10615   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10616   u8 eDistinct;
10617   SrcList *pTabList;             /* List of tables in the join */
10618   int iTop;                      /* The very beginning of the WHERE loop */
10619   int iContinue;                 /* Jump here to continue with next record */
10620   int iBreak;                    /* Jump here to break out of the loop */
10621   int nLevel;                    /* Number of nested loop */
10622   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10623   double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10624   double nRowOut;                /* Estimated number of output rows */
10625   WhereLevel a[1];               /* Information about each nest loop in WHERE */
10626 };
10627 
10628 #define WHERE_DISTINCT_UNIQUE 1
10629 #define WHERE_DISTINCT_ORDERED 2
10630 
10631 /*
10632 ** A NameContext defines a context in which to resolve table and column
10633 ** names.  The context consists of a list of tables (the pSrcList) field and
10634 ** a list of named expression (pEList).  The named expression list may
10635 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10636 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10637 ** pEList corresponds to the result set of a SELECT and is NULL for
10638 ** other statements.
10639 **
10640 ** NameContexts can be nested.  When resolving names, the inner-most
10641 ** context is searched first.  If no match is found, the next outer
10642 ** context is checked.  If there is still no match, the next context
10643 ** is checked.  This process continues until either a match is found
10644 ** or all contexts are check.  When a match is found, the nRef member of
10645 ** the context containing the match is incremented.
10646 **
10647 ** Each subquery gets a new NameContext.  The pNext field points to the
10648 ** NameContext in the parent query.  Thus the process of scanning the
10649 ** NameContext list corresponds to searching through successively outer
10650 ** subqueries looking for a match.
10651 */
10652 struct NameContext {
10653   Parse *pParse;       /* The parser */
10654   SrcList *pSrcList;   /* One or more tables used to resolve names */
10655   ExprList *pEList;    /* Optional list of named expressions */
10656   int nRef;            /* Number of names resolved by this context */
10657   int nErr;            /* Number of errors encountered while resolving names */
10658   u8 allowAgg;         /* Aggregate functions allowed here */
10659   u8 hasAgg;           /* True if aggregates are seen */
10660   u8 isCheck;          /* True if resolving names in a CHECK constraint */
10661   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10662   AggInfo *pAggInfo;   /* Information about aggregates at this level */
10663   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10664 };
10665 
10666 /*
10667 ** An instance of the following structure contains all information
10668 ** needed to generate code for a single SELECT statement.
10669 **
10670 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10671 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
10672 ** limit and nOffset to the value of the offset (or 0 if there is not
10673 ** offset).  But later on, nLimit and nOffset become the memory locations
10674 ** in the VDBE that record the limit and offset counters.
10675 **
10676 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10677 ** These addresses must be stored so that we can go back and fill in
10678 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10679 ** the number of columns in P2 can be computed at the same time
10680 ** as the OP_OpenEphm instruction is coded because not
10681 ** enough information about the compound query is known at that point.
10682 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10683 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10684 ** sequences for the ORDER BY clause.
10685 */
10686 struct Select {
10687   ExprList *pEList;      /* The fields of the result */
10688   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10689   char affinity;         /* MakeRecord with this affinity for SRT_Set */
10690   u16 selFlags;          /* Various SF_* values */
10691   SrcList *pSrc;         /* The FROM clause */
10692   Expr *pWhere;          /* The WHERE clause */
10693   ExprList *pGroupBy;    /* The GROUP BY clause */
10694   Expr *pHaving;         /* The HAVING clause */
10695   ExprList *pOrderBy;    /* The ORDER BY clause */
10696   Select *pPrior;        /* Prior select in a compound select statement */
10697   Select *pNext;         /* Next select to the left in a compound */
10698   Select *pRightmost;    /* Right-most select in a compound select statement */
10699   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10700   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10701   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10702   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10703   double nSelectRow;     /* Estimated number of result rows */
10704 };
10705 
10706 /*
10707 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
10708 ** "Select Flag".
10709 */
10710 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
10711 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
10712 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
10713 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
10714 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
10715 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
10716 #define SF_UseSorter       0x0040  /* Sort using a sorter */
10717 
10718 
10719 /*
10720 ** The results of a select can be distributed in several ways.  The
10721 ** "SRT" prefix means "SELECT Result Type".
10722 */
10723 #define SRT_Union        1  /* Store result as keys in an index */
10724 #define SRT_Except       2  /* Remove result from a UNION index */
10725 #define SRT_Exists       3  /* Store 1 if the result is not empty */
10726 #define SRT_Discard      4  /* Do not save the results anywhere */
10727 
10728 /* The ORDER BY clause is ignored for all of the above */
10729 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10730 
10731 #define SRT_Output       5  /* Output each row of result */
10732 #define SRT_Mem          6  /* Store result in a memory cell */
10733 #define SRT_Set          7  /* Store results as keys in an index */
10734 #define SRT_Table        8  /* Store result as data with an automatic rowid */
10735 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10736 #define SRT_Coroutine   10  /* Generate a single row of result */
10737 
10738 /*
10739 ** A structure used to customize the behavior of sqlite3Select(). See
10740 ** comments above sqlite3Select() for details.
10741 */
10742 typedef struct SelectDest SelectDest;
10743 struct SelectDest {
10744   u8 eDest;         /* How to dispose of the results */
10745   u8 affinity;      /* Affinity used when eDest==SRT_Set */
10746   int iParm;        /* A parameter used by the eDest disposal method */
10747   int iMem;         /* Base register where results are written */
10748   int nMem;         /* Number of registers allocated */
10749 };
10750 
10751 /*
10752 ** During code generation of statements that do inserts into AUTOINCREMENT
10753 ** tables, the following information is attached to the Table.u.autoInc.p
10754 ** pointer of each autoincrement table to record some side information that
10755 ** the code generator needs.  We have to keep per-table autoincrement
10756 ** information in case inserts are down within triggers.  Triggers do not
10757 ** normally coordinate their activities, but we do need to coordinate the
10758 ** loading and saving of autoincrement information.
10759 */
10760 struct AutoincInfo {
10761   AutoincInfo *pNext;   /* Next info block in a list of them all */
10762   Table *pTab;          /* Table this info block refers to */
10763   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
10764   int regCtr;           /* Memory register holding the rowid counter */
10765 };
10766 
10767 /*
10768 ** Size of the column cache
10769 */
10770 #ifndef SQLITE_N_COLCACHE
10771 # define SQLITE_N_COLCACHE 10
10772 #endif
10773 
10774 /*
10775 ** At least one instance of the following structure is created for each
10776 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
10777 ** statement. All such objects are stored in the linked list headed at
10778 ** Parse.pTriggerPrg and deleted once statement compilation has been
10779 ** completed.
10780 **
10781 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
10782 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
10783 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
10784 ** The Parse.pTriggerPrg list never contains two entries with the same
10785 ** values for both pTrigger and orconf.
10786 **
10787 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
10788 ** accessed (or set to 0 for triggers fired as a result of INSERT
10789 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
10790 ** a mask of new.* columns used by the program.
10791 */
10792 struct TriggerPrg {
10793   Trigger *pTrigger;      /* Trigger this program was coded from */
10794   int orconf;             /* Default ON CONFLICT policy */
10795   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
10796   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
10797   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
10798 };
10799 
10800 /*
10801 ** The yDbMask datatype for the bitmask of all attached databases.
10802 */
10803 #if SQLITE_MAX_ATTACHED>30
10804   typedef sqlite3_uint64 yDbMask;
10805 #else
10806   typedef unsigned int yDbMask;
10807 #endif
10808 
10809 /*
10810 ** An SQL parser context.  A copy of this structure is passed through
10811 ** the parser and down into all the parser action routine in order to
10812 ** carry around information that is global to the entire parse.
10813 **
10814 ** The structure is divided into two parts.  When the parser and code
10815 ** generate call themselves recursively, the first part of the structure
10816 ** is constant but the second part is reset at the beginning and end of
10817 ** each recursion.
10818 **
10819 ** The nTableLock and aTableLock variables are only used if the shared-cache
10820 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
10821 ** used to store the set of table-locks required by the statement being
10822 ** compiled. Function sqlite3TableLock() is used to add entries to the
10823 ** list.
10824 */
10825 struct Parse {
10826   sqlite3 *db;         /* The main database structure */
10827   int rc;              /* Return code from execution */
10828   char *zErrMsg;       /* An error message */
10829   Vdbe *pVdbe;         /* An engine for executing database bytecode */
10830   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
10831   u8 nameClash;        /* A permanent table name clashes with temp table name */
10832   u8 checkSchema;      /* Causes schema cookie check after an error */
10833   u8 nested;           /* Number of nested calls to the parser/code generator */
10834   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
10835   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
10836   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
10837   int aTempReg[8];     /* Holding area for temporary registers */
10838   int nRangeReg;       /* Size of the temporary register block */
10839   int iRangeReg;       /* First register in temporary register block */
10840   int nErr;            /* Number of errors seen */
10841   int nTab;            /* Number of previously allocated VDBE cursors */
10842   int nMem;            /* Number of memory cells used so far */
10843   int nSet;            /* Number of sets used so far */
10844   int ckBase;          /* Base register of data during check constraints */
10845   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
10846   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
10847   u8 nColCache;        /* Number of entries in the column cache */
10848   u8 iColCache;        /* Next entry of the cache to replace */
10849   struct yColCache {
10850     int iTable;           /* Table cursor number */
10851     int iColumn;          /* Table column number */
10852     u8 tempReg;           /* iReg is a temp register that needs to be freed */
10853     int iLevel;           /* Nesting level */
10854     int iReg;             /* Reg with value of this column. 0 means none. */
10855     int lru;              /* Least recently used entry has the smallest value */
10856   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
10857   yDbMask writeMask;   /* Start a write transaction on these databases */
10858   yDbMask cookieMask;  /* Bitmask of schema verified databases */
10859   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
10860   u8 mayAbort;         /* True if statement may throw an ABORT exception */
10861   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
10862   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
10863 #ifndef SQLITE_OMIT_SHARED_CACHE
10864   int nTableLock;        /* Number of locks in aTableLock */
10865   TableLock *aTableLock; /* Required table locks for shared-cache mode */
10866 #endif
10867   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
10868   int regRoot;         /* Register holding root page number for new objects */
10869   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
10870   int nMaxArg;         /* Max args passed to user function by sub-program */
10871 
10872   /* Information used while coding trigger programs. */
10873   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
10874   Table *pTriggerTab;  /* Table triggers are being coded for */
10875   u32 oldmask;         /* Mask of old.* columns referenced */
10876   u32 newmask;         /* Mask of new.* columns referenced */
10877   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
10878   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
10879   u8 disableTriggers;  /* True to disable triggers */
10880   double nQueryLoop;   /* Estimated number of iterations of a query */
10881 
10882   /* Above is constant between recursions.  Below is reset before and after
10883   ** each recursion */
10884 
10885   int nVar;            /* Number of '?' variables seen in the SQL so far */
10886   int nzVar;           /* Number of available slots in azVar[] */
10887   char **azVar;        /* Pointers to names of parameters */
10888   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
10889   int nAlias;          /* Number of aliased result set columns */
10890   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
10891   int *aAlias;         /* Register used to hold aliased result */
10892   u8 explain;          /* True if the EXPLAIN flag is found on the query */
10893   Token sNameToken;    /* Token with unqualified schema object name */
10894   Token sLastToken;    /* The last token parsed */
10895   const char *zTail;   /* All SQL text past the last semicolon parsed */
10896   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
10897   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
10898   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
10899 #ifndef SQLITE_OMIT_VIRTUALTABLE
10900   Token sArg;                /* Complete text of a module argument */
10901   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
10902   int nVtabLock;             /* Number of virtual tables to lock */
10903   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
10904 #endif
10905   int nHeight;            /* Expression tree height of current sub-select */
10906   Table *pZombieTab;      /* List of Table objects to delete after code gen */
10907   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
10908 
10909 #ifndef SQLITE_OMIT_EXPLAIN
10910   int iSelectId;
10911   int iNextSelectId;
10912 #endif
10913 };
10914 
10915 #ifdef SQLITE_OMIT_VIRTUALTABLE
10916   #define IN_DECLARE_VTAB 0
10917 #else
10918   #define IN_DECLARE_VTAB (pParse->declareVtab)
10919 #endif
10920 
10921 /*
10922 ** An instance of the following structure can be declared on a stack and used
10923 ** to save the Parse.zAuthContext value so that it can be restored later.
10924 */
10925 struct AuthContext {
10926   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
10927   Parse *pParse;              /* The Parse structure */
10928 };
10929 
10930 /*
10931 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
10932 */
10933 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
10934 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
10935 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
10936 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
10937 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
10938 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
10939 
10940 /*
10941  * Each trigger present in the database schema is stored as an instance of
10942  * struct Trigger.
10943  *
10944  * Pointers to instances of struct Trigger are stored in two ways.
10945  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
10946  *    database). This allows Trigger structures to be retrieved by name.
10947  * 2. All triggers associated with a single table form a linked list, using the
10948  *    pNext member of struct Trigger. A pointer to the first element of the
10949  *    linked list is stored as the "pTrigger" member of the associated
10950  *    struct Table.
10951  *
10952  * The "step_list" member points to the first element of a linked list
10953  * containing the SQL statements specified as the trigger program.
10954  */
10955 struct Trigger {
10956   char *zName;            /* The name of the trigger                        */
10957   char *table;            /* The table or view to which the trigger applies */
10958   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
10959   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
10960   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
10961   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
10962                              the <column-list> is stored here */
10963   Schema *pSchema;        /* Schema containing the trigger */
10964   Schema *pTabSchema;     /* Schema containing the table */
10965   TriggerStep *step_list; /* Link list of trigger program steps             */
10966   Trigger *pNext;         /* Next trigger associated with the table */
10967 };
10968 
10969 /*
10970 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
10971 ** determine which.
10972 **
10973 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
10974 ** In that cases, the constants below can be ORed together.
10975 */
10976 #define TRIGGER_BEFORE  1
10977 #define TRIGGER_AFTER   2
10978 
10979 /*
10980  * An instance of struct TriggerStep is used to store a single SQL statement
10981  * that is a part of a trigger-program.
10982  *
10983  * Instances of struct TriggerStep are stored in a singly linked list (linked
10984  * using the "pNext" member) referenced by the "step_list" member of the
10985  * associated struct Trigger instance. The first element of the linked list is
10986  * the first step of the trigger-program.
10987  *
10988  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
10989  * "SELECT" statement. The meanings of the other members is determined by the
10990  * value of "op" as follows:
10991  *
10992  * (op == TK_INSERT)
10993  * orconf    -> stores the ON CONFLICT algorithm
10994  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
10995  *              this stores a pointer to the SELECT statement. Otherwise NULL.
10996  * target    -> A token holding the quoted name of the table to insert into.
10997  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
10998  *              this stores values to be inserted. Otherwise NULL.
10999  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11000  *              statement, then this stores the column-names to be
11001  *              inserted into.
11002  *
11003  * (op == TK_DELETE)
11004  * target    -> A token holding the quoted name of the table to delete from.
11005  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11006  *              Otherwise NULL.
11007  *
11008  * (op == TK_UPDATE)
11009  * target    -> A token holding the quoted name of the table to update rows of.
11010  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11011  *              Otherwise NULL.
11012  * pExprList -> A list of the columns to update and the expressions to update
11013  *              them to. See sqlite3Update() documentation of "pChanges"
11014  *              argument.
11015  *
11016  */
11017 struct TriggerStep {
11018   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11019   u8 orconf;           /* OE_Rollback etc. */
11020   Trigger *pTrig;      /* The trigger that this step is a part of */
11021   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11022   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11023   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11024   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11025   IdList *pIdList;     /* Column names for INSERT */
11026   TriggerStep *pNext;  /* Next in the link-list */
11027   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11028 };
11029 
11030 /*
11031 ** The following structure contains information used by the sqliteFix...
11032 ** routines as they walk the parse tree to make database references
11033 ** explicit.
11034 */
11035 typedef struct DbFixer DbFixer;
11036 struct DbFixer {
11037   Parse *pParse;      /* The parsing context.  Error messages written here */
11038   const char *zDb;    /* Make sure all objects are contained in this database */
11039   const char *zType;  /* Type of the container - used for error messages */
11040   const Token *pName; /* Name of the container - used for error messages */
11041 };
11042 
11043 /*
11044 ** An objected used to accumulate the text of a string where we
11045 ** do not necessarily know how big the string will be in the end.
11046 */
11047 struct StrAccum {
11048   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11049   char *zBase;         /* A base allocation.  Not from malloc. */
11050   char *zText;         /* The string collected so far */
11051   int  nChar;          /* Length of the string so far */
11052   int  nAlloc;         /* Amount of space allocated in zText */
11053   int  mxAlloc;        /* Maximum allowed string length */
11054   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11055   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11056   u8   tooBig;         /* Becomes true if string size exceeds limits */
11057 };
11058 
11059 /*
11060 ** A pointer to this structure is used to communicate information
11061 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11062 */
11063 typedef struct {
11064   sqlite3 *db;        /* The database being initialized */
11065   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11066   char **pzErrMsg;    /* Error message stored here */
11067   int rc;             /* Result code stored here */
11068 } InitData;
11069 
11070 /*
11071 ** Structure containing global configuration data for the SQLite library.
11072 **
11073 ** This structure also contains some state information.
11074 */
11075 struct Sqlite3Config {
11076   int bMemstat;                     /* True to enable memory status */
11077   int bCoreMutex;                   /* True to enable core mutexing */
11078   int bFullMutex;                   /* True to enable full mutexing */
11079   int bOpenUri;                     /* True to interpret filenames as URIs */
11080   int mxStrlen;                     /* Maximum string length */
11081   int szLookaside;                  /* Default lookaside buffer size */
11082   int nLookaside;                   /* Default lookaside buffer count */
11083   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11084   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11085   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
11086   void *pHeap;                      /* Heap storage space */
11087   int nHeap;                        /* Size of pHeap[] */
11088   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11089   void *pScratch;                   /* Scratch memory */
11090   int szScratch;                    /* Size of each scratch buffer */
11091   int nScratch;                     /* Number of scratch buffers */
11092   void *pPage;                      /* Page cache memory */
11093   int szPage;                       /* Size of each page in pPage[] */
11094   int nPage;                        /* Number of pages in pPage[] */
11095   int mxParserStack;                /* maximum depth of the parser stack */
11096   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11097   /* The above might be initialized to non-zero.  The following need to always
11098   ** initially be zero, however. */
11099   int isInit;                       /* True after initialization has finished */
11100   int inProgress;                   /* True while initialization in progress */
11101   int isMutexInit;                  /* True after mutexes are initialized */
11102   int isMallocInit;                 /* True after malloc is initialized */
11103   int isPCacheInit;                 /* True after malloc is initialized */
11104   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11105   int nRefInitMutex;                /* Number of users of pInitMutex */
11106   void (*xLog)(void*,int,const char*); /* Function for logging */
11107   void *pLogArg;                       /* First argument to xLog() */
11108   int bLocaltimeFault;              /* True to fail localtime() calls */
11109 };
11110 
11111 /*
11112 ** Context pointer passed down through the tree-walk.
11113 */
11114 struct Walker {
11115   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11116   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11117   Parse *pParse;                            /* Parser context.  */
11118   union {                                   /* Extra data for callback */
11119     NameContext *pNC;                          /* Naming context */
11120     int i;                                     /* Integer value */
11121   } u;
11122 };
11123 
11124 /* Forward declarations */
11125 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11126 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11127 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11128 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11129 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11130 
11131 /*
11132 ** Return code from the parse-tree walking primitives and their
11133 ** callbacks.
11134 */
11135 #define WRC_Continue    0   /* Continue down into children */
11136 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11137 #define WRC_Abort       2   /* Abandon the tree walk */
11138 
11139 /*
11140 ** Assuming zIn points to the first byte of a UTF-8 character,
11141 ** advance zIn to point to the first byte of the next UTF-8 character.
11142 */
11143 #define SQLITE_SKIP_UTF8(zIn) {                        \
11144   if( (*(zIn++))>=0xc0 ){                              \
11145     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11146   }                                                    \
11147 }
11148 
11149 /*
11150 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11151 ** the same name but without the _BKPT suffix.  These macros invoke
11152 ** routines that report the line-number on which the error originated
11153 ** using sqlite3_log().  The routines also provide a convenient place
11154 ** to set a debugger breakpoint.
11155 */
11156 SQLITE_PRIVATE int sqlite3CorruptError(int);
11157 SQLITE_PRIVATE int sqlite3MisuseError(int);
11158 SQLITE_PRIVATE int sqlite3CantopenError(int);
11159 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11160 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11161 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11162 
11163 
11164 /*
11165 ** FTS4 is really an extension for FTS3.  It is enabled using the
11166 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11167 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11168 */
11169 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11170 # define SQLITE_ENABLE_FTS3
11171 #endif
11172 
11173 /*
11174 ** The ctype.h header is needed for non-ASCII systems.  It is also
11175 ** needed by FTS3 when FTS3 is included in the amalgamation.
11176 */
11177 #if !defined(SQLITE_ASCII) || \
11178     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11179 # include <ctype.h>
11180 #endif
11181 
11182 /*
11183 ** The following macros mimic the standard library functions toupper(),
11184 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11185 ** sqlite versions only work for ASCII characters, regardless of locale.
11186 */
11187 #ifdef SQLITE_ASCII
11188 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11189 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11190 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11191 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11192 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11193 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11194 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11195 #else
11196 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11197 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11198 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11199 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11200 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11201 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11202 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11203 #endif
11204 
11205 /*
11206 ** Internal function prototypes
11207 */
11208 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
11209 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11210 #define sqlite3StrNICmp sqlite3_strnicmp
11211 
11212 SQLITE_PRIVATE int sqlite3MallocInit(void);
11213 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11214 SQLITE_PRIVATE void *sqlite3Malloc(int);
11215 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11216 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11217 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11218 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11219 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11220 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11221 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11222 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11223 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11224 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11225 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11226 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11227 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11228 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11229 SQLITE_PRIVATE void sqlite3PageFree(void*);
11230 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11231 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11232 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11233 
11234 /*
11235 ** On systems with ample stack space and that support alloca(), make
11236 ** use of alloca() to obtain space for large automatic objects.  By default,
11237 ** obtain space from malloc().
11238 **
11239 ** The alloca() routine never returns NULL.  This will cause code paths
11240 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11241 */
11242 #ifdef SQLITE_USE_ALLOCA
11243 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11244 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11245 # define sqlite3StackFree(D,P)
11246 #else
11247 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11248 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11249 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11250 #endif
11251 
11252 #ifdef SQLITE_ENABLE_MEMSYS3
11253 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11254 #endif
11255 #ifdef SQLITE_ENABLE_MEMSYS5
11256 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11257 #endif
11258 
11259 
11260 #ifndef SQLITE_MUTEX_OMIT
11261 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11262 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11263 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11264 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11265 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11266 #endif
11267 
11268 SQLITE_PRIVATE int sqlite3StatusValue(int);
11269 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11270 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11271 
11272 #ifndef SQLITE_OMIT_FLOATING_POINT
11273 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11274 #else
11275 # define sqlite3IsNaN(X)  0
11276 #endif
11277 
11278 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11279 #ifndef SQLITE_OMIT_TRACE
11280 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11281 #endif
11282 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11283 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11284 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11285 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11286 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11287 #endif
11288 #if defined(SQLITE_TEST)
11289 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11290 #endif
11291 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11292 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11293 SQLITE_PRIVATE int sqlite3Dequote(char*);
11294 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11295 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11296 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11297 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11298 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11299 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11300 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11301 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11302 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11303 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11304 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11305 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11306 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11307 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11308 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11309 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11310 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11311 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11312 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11313 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11314 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11315 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11316 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11317 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11318 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11319 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11320 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11321 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11322 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11323 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11324 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11325 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11326 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11327 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11328 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11329 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11330 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11331                     sqlite3_vfs**,char**,char **);
11332 
11333 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11334 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11335 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11336 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11337 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11338 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11339 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11340 
11341 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11342 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11343 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11344 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11345 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11346 
11347 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11348 
11349 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11350 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11351 #else
11352 # define sqlite3ViewGetColumnNames(A,B) 0
11353 #endif
11354 
11355 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11356 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11357 #ifndef SQLITE_OMIT_AUTOINCREMENT
11358 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11359 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11360 #else
11361 # define sqlite3AutoincrementBegin(X)
11362 # define sqlite3AutoincrementEnd(X)
11363 #endif
11364 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11365 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
11366 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11367 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11368 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11369 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11370 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11371                                       Token*, Select*, Expr*, IdList*);
11372 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11373 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11374 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11375 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11376 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11377 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11378 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11379                         Token*, int, int);
11380 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11381 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11382 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11383                          Expr*,ExprList*,int,Expr*,Expr*);
11384 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11385 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11386 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11387 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11388 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11389 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11390 #endif
11391 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11392 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11393 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11394 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11395 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11396 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11397 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11398 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11399 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11400 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11401 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11402 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11403 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11404 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11405 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11406 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11407 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11408 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11409 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11410 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11411 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11412 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11413 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11414 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11415 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11416 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11417 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11418 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11419 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11420 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11421 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11422 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11423 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11424 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11425 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11426 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11427 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11428 SQLITE_PRIVATE void sqlite3PrngResetState(void);
11429 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
11430 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11431 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11432 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11433 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11434 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11435 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11436 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11437 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11438 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11439 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11440 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11441 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11442 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11443 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11444 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11445 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11446 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11447 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11448 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11449                                      int*,int,int,int,int,int*);
11450 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11451 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11452 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11453 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11454 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11455 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11456 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11457 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11458 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11459 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11460 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11461 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11462 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11463 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11464 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11465 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11466 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11467 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11468 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11469 
11470 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11471 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11472 #endif
11473 
11474 #ifndef SQLITE_OMIT_TRIGGER
11475 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11476                            Expr*,int, int);
11477 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11478 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11479 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11480 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11481 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11482 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11483                             int, int, int);
11484 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11485   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11486 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11487 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11488 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11489                                         ExprList*,Select*,u8);
11490 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11491 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11492 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11493 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11494 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11495 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11496 #else
11497 # define sqlite3TriggersExist(B,C,D,E,F) 0
11498 # define sqlite3DeleteTrigger(A,B)
11499 # define sqlite3DropTriggerPtr(A,B)
11500 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11501 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11502 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11503 # define sqlite3TriggerList(X, Y) 0
11504 # define sqlite3ParseToplevel(p) p
11505 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11506 #endif
11507 
11508 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11509 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11510 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11511 #ifndef SQLITE_OMIT_AUTHORIZATION
11512 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11513 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11514 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11515 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11516 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11517 #else
11518 # define sqlite3AuthRead(a,b,c,d)
11519 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11520 # define sqlite3AuthContextPush(a,b,c)
11521 # define sqlite3AuthContextPop(a)  ((void)(a))
11522 #endif
11523 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11524 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11525 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11526 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11527 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11528 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11529 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11530 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11531 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11532 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11533 SQLITE_PRIVATE int sqlite3Atoi(const char*);
11534 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11535 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11536 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11537 
11538 /*
11539 ** Routines to read and write variable-length integers.  These used to
11540 ** be defined locally, but now we use the varint routines in the util.c
11541 ** file.  Code should use the MACRO forms below, as the Varint32 versions
11542 ** are coded to assume the single byte case is already handled (which
11543 ** the MACRO form does).
11544 */
11545 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11546 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11547 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11548 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11549 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11550 
11551 /*
11552 ** The header of a record consists of a sequence variable-length integers.
11553 ** These integers are almost always small and are encoded as a single byte.
11554 ** The following macros take advantage this fact to provide a fast encode
11555 ** and decode of the integers in a record header.  It is faster for the common
11556 ** case where the integer is a single byte.  It is a little slower when the
11557 ** integer is two or more bytes.  But overall it is faster.
11558 **
11559 ** The following expressions are equivalent:
11560 **
11561 **     x = sqlite3GetVarint32( A, &B );
11562 **     x = sqlite3PutVarint32( A, B );
11563 **
11564 **     x = getVarint32( A, B );
11565 **     x = putVarint32( A, B );
11566 **
11567 */
11568 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11569 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11570 #define getVarint    sqlite3GetVarint
11571 #define putVarint    sqlite3PutVarint
11572 
11573 
11574 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11575 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11576 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11577 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11578 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11579 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11580 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11581 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11582 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11583 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11584 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11585 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11586 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11587 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11588 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11589 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11590 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11591 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11592 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11593 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11594 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11595 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11596 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11597 SQLITE_PRIVATE int sqlite3AbsInt32(int);
11598 #ifdef SQLITE_ENABLE_8_3_NAMES
11599 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11600 #else
11601 # define sqlite3FileSuffix3(X,Y)
11602 #endif
11603 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z);
11604 
11605 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11606 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11607 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11608                         void(*)(void*));
11609 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11610 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11611 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11612 #ifdef SQLITE_ENABLE_STAT2
11613 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11614 #endif
11615 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11616 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11617 #ifndef SQLITE_AMALGAMATION
11618 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11619 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11620 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11621 SQLITE_PRIVATE const Token sqlite3IntTokens[];
11622 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11623 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11624 #ifndef SQLITE_OMIT_WSD
11625 SQLITE_PRIVATE int sqlite3PendingByte;
11626 #endif
11627 #endif
11628 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11629 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11630 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11631 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11632 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11633 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11634 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11635 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11636 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11637 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11638 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11639 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11640 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11641 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11642 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11643 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11644 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11645 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11646 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11647 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11648 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11649 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11650 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11651 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11652 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11653 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11654 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11655 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11656 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11657 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11658 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11659 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11660   void (*)(sqlite3_context*,int,sqlite3_value **),
11661   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11662   FuncDestructor *pDestructor
11663 );
11664 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11665 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11666 
11667 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11668 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11669 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11670 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11671 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11672 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11673 
11674 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11675 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11676 
11677 /*
11678 ** The interface to the LEMON-generated parser
11679 */
11680 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11681 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11682 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11683 #ifdef YYTRACKMAXSTACKDEPTH
11684 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11685 #endif
11686 
11687 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11688 #ifndef SQLITE_OMIT_LOAD_EXTENSION
11689 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11690 #else
11691 # define sqlite3CloseExtensions(X)
11692 #endif
11693 
11694 #ifndef SQLITE_OMIT_SHARED_CACHE
11695 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11696 #else
11697   #define sqlite3TableLock(v,w,x,y,z)
11698 #endif
11699 
11700 #ifdef SQLITE_TEST
11701 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11702 #endif
11703 
11704 #ifdef SQLITE_OMIT_VIRTUALTABLE
11705 #  define sqlite3VtabClear(Y)
11706 #  define sqlite3VtabSync(X,Y) SQLITE_OK
11707 #  define sqlite3VtabRollback(X)
11708 #  define sqlite3VtabCommit(X)
11709 #  define sqlite3VtabInSync(db) 0
11710 #  define sqlite3VtabLock(X)
11711 #  define sqlite3VtabUnlock(X)
11712 #  define sqlite3VtabUnlockList(X)
11713 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
11714 #else
11715 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
11716 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
11717 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
11718 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
11719 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
11720 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
11721 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
11722 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
11723 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
11724 #endif
11725 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
11726 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
11727 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
11728 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
11729 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
11730 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
11731 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
11732 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
11733 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
11734 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
11735 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
11736 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
11737 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
11738 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
11739 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
11740 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
11741 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
11742 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
11743 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
11744 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
11745 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
11746 
11747 /* Declarations for functions in fkey.c. All of these are replaced by
11748 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
11749 ** key functionality is available. If OMIT_TRIGGER is defined but
11750 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
11751 ** this case foreign keys are parsed, but no other functionality is
11752 ** provided (enforcement of FK constraints requires the triggers sub-system).
11753 */
11754 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
11755 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
11756 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
11757 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
11758 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
11759 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
11760 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
11761 #else
11762   #define sqlite3FkActions(a,b,c,d)
11763   #define sqlite3FkCheck(a,b,c,d)
11764   #define sqlite3FkDropTable(a,b,c)
11765   #define sqlite3FkOldmask(a,b)      0
11766   #define sqlite3FkRequired(a,b,c,d) 0
11767 #endif
11768 #ifndef SQLITE_OMIT_FOREIGN_KEY
11769 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
11770 #else
11771   #define sqlite3FkDelete(a,b)
11772 #endif
11773 
11774 
11775 /*
11776 ** Available fault injectors.  Should be numbered beginning with 0.
11777 */
11778 #define SQLITE_FAULTINJECTOR_MALLOC     0
11779 #define SQLITE_FAULTINJECTOR_COUNT      1
11780 
11781 /*
11782 ** The interface to the code in fault.c used for identifying "benign"
11783 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
11784 ** is not defined.
11785 */
11786 #ifndef SQLITE_OMIT_BUILTIN_TEST
11787 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
11788 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
11789 #else
11790   #define sqlite3BeginBenignMalloc()
11791   #define sqlite3EndBenignMalloc()
11792 #endif
11793 
11794 #define IN_INDEX_ROWID           1
11795 #define IN_INDEX_EPH             2
11796 #define IN_INDEX_INDEX           3
11797 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
11798 
11799 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
11800 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
11801 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
11802 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
11803 #else
11804   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
11805 #endif
11806 
11807 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
11808 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
11809 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
11810 
11811 #if SQLITE_MAX_EXPR_DEPTH>0
11812 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
11813 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
11814 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
11815 #else
11816   #define sqlite3ExprSetHeight(x,y)
11817   #define sqlite3SelectExprHeight(x) 0
11818   #define sqlite3ExprCheckHeight(x,y)
11819 #endif
11820 
11821 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
11822 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
11823 
11824 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11825 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
11826 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
11827 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
11828 #else
11829   #define sqlite3ConnectionBlocked(x,y)
11830   #define sqlite3ConnectionUnlocked(x)
11831   #define sqlite3ConnectionClosed(x)
11832 #endif
11833 
11834 #ifdef SQLITE_DEBUG
11835 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
11836 #endif
11837 
11838 /*
11839 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
11840 ** sqlite3IoTrace is a pointer to a printf-like routine used to
11841 ** print I/O tracing messages.
11842 */
11843 #ifdef SQLITE_ENABLE_IOTRACE
11844 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
11845 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
11846 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
11847 #else
11848 # define IOTRACE(A)
11849 # define sqlite3VdbeIOTraceSql(X)
11850 #endif
11851 
11852 /*
11853 ** These routines are available for the mem2.c debugging memory allocator
11854 ** only.  They are used to verify that different "types" of memory
11855 ** allocations are properly tracked by the system.
11856 **
11857 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
11858 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
11859 ** a single bit set.
11860 **
11861 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
11862 ** argument match the type set by the previous sqlite3MemdebugSetType().
11863 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
11864 **
11865 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
11866 ** argument match the type set by the previous sqlite3MemdebugSetType().
11867 **
11868 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
11869 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
11870 ** it might have been allocated by lookaside, except the allocation was
11871 ** too large or lookaside was already full.  It is important to verify
11872 ** that allocations that might have been satisfied by lookaside are not
11873 ** passed back to non-lookaside free() routines.  Asserts such as the
11874 ** example above are placed on the non-lookaside free() routines to verify
11875 ** this constraint.
11876 **
11877 ** All of this is no-op for a production build.  It only comes into
11878 ** play when the SQLITE_MEMDEBUG compile-time option is used.
11879 */
11880 #ifdef SQLITE_MEMDEBUG
11881 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
11882 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
11883 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
11884 #else
11885 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
11886 # define sqlite3MemdebugHasType(X,Y)  1
11887 # define sqlite3MemdebugNoType(X,Y)   1
11888 #endif
11889 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
11890 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
11891 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
11892 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
11893 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
11894 
11895 #endif /* _SQLITEINT_H_ */
11896 
11897 /************** End of sqliteInt.h *******************************************/
11898 /************** Begin file global.c ******************************************/
11899 /*
11900 ** 2008 June 13
11901 **
11902 ** The author disclaims copyright to this source code.  In place of
11903 ** a legal notice, here is a blessing:
11904 **
11905 **    May you do good and not evil.
11906 **    May you find forgiveness for yourself and forgive others.
11907 **    May you share freely, never taking more than you give.
11908 **
11909 *************************************************************************
11910 **
11911 ** This file contains definitions of global variables and contants.
11912 */
11913 
11914 /* An array to map all upper-case characters into their corresponding
11915 ** lower-case character.
11916 **
11917 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11918 ** handle case conversions for the UTF character set since the tables
11919 ** involved are nearly as big or bigger than SQLite itself.
11920 */
11921 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
11922 #ifdef SQLITE_ASCII
11923       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
11924      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
11925      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
11926      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
11927     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
11928     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
11929     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
11930     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
11931     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
11932     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
11933     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
11934     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
11935     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
11936     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
11937     252,253,254,255
11938 #endif
11939 #ifdef SQLITE_EBCDIC
11940       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
11941      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
11942      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
11943      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
11944      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
11945      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
11946      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
11947     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
11948     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
11949     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
11950     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
11951     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
11952     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
11953     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
11954     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
11955     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
11956 #endif
11957 };
11958 
11959 /*
11960 ** The following 256 byte lookup table is used to support SQLites built-in
11961 ** equivalents to the following standard library functions:
11962 **
11963 **   isspace()                        0x01
11964 **   isalpha()                        0x02
11965 **   isdigit()                        0x04
11966 **   isalnum()                        0x06
11967 **   isxdigit()                       0x08
11968 **   toupper()                        0x20
11969 **   SQLite identifier character      0x40
11970 **
11971 ** Bit 0x20 is set if the mapped character requires translation to upper
11972 ** case. i.e. if the character is a lower-case ASCII character.
11973 ** If x is a lower-case ASCII character, then its upper-case equivalent
11974 ** is (x - 0x20). Therefore toupper() can be implemented as:
11975 **
11976 **   (x & ~(map[x]&0x20))
11977 **
11978 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
11979 ** array. tolower() is used more often than toupper() by SQLite.
11980 **
11981 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
11982 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
11983 ** non-ASCII UTF character. Hence the test for whether or not a character is
11984 ** part of an identifier is 0x46.
11985 **
11986 ** SQLite's versions are identical to the standard versions assuming a
11987 ** locale of "C". They are implemented as macros in sqliteInt.h.
11988 */
11989 #ifdef SQLITE_ASCII
11990 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
11991   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
11992   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
11993   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
11994   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
11995   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
11996   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
11997   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
11998   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
11999 
12000   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12001   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12002   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12003   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12004   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12005   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12006   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12007   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12008 
12009   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12010   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12011   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12012   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12013   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12014   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12015   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12016   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12017 
12018   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12019   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12020   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12021   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12022   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12023   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12024   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12025   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12026 };
12027 #endif
12028 
12029 #ifndef SQLITE_USE_URI
12030 # define  SQLITE_USE_URI 0
12031 #endif
12032 
12033 /*
12034 ** The following singleton contains the global configuration for
12035 ** the SQLite library.
12036 */
12037 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12038    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12039    1,                         /* bCoreMutex */
12040    SQLITE_THREADSAFE==1,      /* bFullMutex */
12041    SQLITE_USE_URI,            /* bOpenUri */
12042    0x7ffffffe,                /* mxStrlen */
12043    128,                       /* szLookaside */
12044    500,                       /* nLookaside */
12045    {0,0,0,0,0,0,0,0},         /* m */
12046    {0,0,0,0,0,0,0,0,0},       /* mutex */
12047    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
12048    (void*)0,                  /* pHeap */
12049    0,                         /* nHeap */
12050    0, 0,                      /* mnHeap, mxHeap */
12051    (void*)0,                  /* pScratch */
12052    0,                         /* szScratch */
12053    0,                         /* nScratch */
12054    (void*)0,                  /* pPage */
12055    0,                         /* szPage */
12056    0,                         /* nPage */
12057    0,                         /* mxParserStack */
12058    0,                         /* sharedCacheEnabled */
12059    /* All the rest should always be initialized to zero */
12060    0,                         /* isInit */
12061    0,                         /* inProgress */
12062    0,                         /* isMutexInit */
12063    0,                         /* isMallocInit */
12064    0,                         /* isPCacheInit */
12065    0,                         /* pInitMutex */
12066    0,                         /* nRefInitMutex */
12067    0,                         /* xLog */
12068    0,                         /* pLogArg */
12069    0,                         /* bLocaltimeFault */
12070 };
12071 
12072 
12073 /*
12074 ** Hash table for global functions - functions common to all
12075 ** database connections.  After initialization, this table is
12076 ** read-only.
12077 */
12078 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12079 
12080 /*
12081 ** Constant tokens for values 0 and 1.
12082 */
12083 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12084    { "0", 1 },
12085    { "1", 1 }
12086 };
12087 
12088 
12089 /*
12090 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12091 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12092 ** the database page that contains the pending byte.  It never attempts
12093 ** to read or write that page.  The pending byte page is set assign
12094 ** for use by the VFS layers as space for managing file locks.
12095 **
12096 ** During testing, it is often desirable to move the pending byte to
12097 ** a different position in the file.  This allows code that has to
12098 ** deal with the pending byte to run on files that are much smaller
12099 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12100 ** move the pending byte.
12101 **
12102 ** IMPORTANT:  Changing the pending byte to any value other than
12103 ** 0x40000000 results in an incompatible database file format!
12104 ** Changing the pending byte during operating results in undefined
12105 ** and dileterious behavior.
12106 */
12107 #ifndef SQLITE_OMIT_WSD
12108 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12109 #endif
12110 
12111 /*
12112 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12113 ** created by mkopcodeh.awk during compilation.  Data is obtained
12114 ** from the comments following the "case OP_xxxx:" statements in
12115 ** the vdbe.c file.
12116 */
12117 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12118 
12119 /************** End of global.c **********************************************/
12120 /************** Begin file ctime.c *******************************************/
12121 /*
12122 ** 2010 February 23
12123 **
12124 ** The author disclaims copyright to this source code.  In place of
12125 ** a legal notice, here is a blessing:
12126 **
12127 **    May you do good and not evil.
12128 **    May you find forgiveness for yourself and forgive others.
12129 **    May you share freely, never taking more than you give.
12130 **
12131 *************************************************************************
12132 **
12133 ** This file implements routines used to report what compile-time options
12134 ** SQLite was built with.
12135 */
12136 
12137 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12138 
12139 
12140 /*
12141 ** An array of names of all compile-time options.  This array should
12142 ** be sorted A-Z.
12143 **
12144 ** This array looks large, but in a typical installation actually uses
12145 ** only a handful of compile-time options, so most times this array is usually
12146 ** rather short and uses little memory space.
12147 */
12148 static const char * const azCompileOpt[] = {
12149 
12150 /* These macros are provided to "stringify" the value of the define
12151 ** for those options in which the value is meaningful. */
12152 #define CTIMEOPT_VAL_(opt) #opt
12153 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12154 
12155 #ifdef SQLITE_32BIT_ROWID
12156   "32BIT_ROWID",
12157 #endif
12158 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12159   "4_BYTE_ALIGNED_MALLOC",
12160 #endif
12161 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12162   "CASE_SENSITIVE_LIKE",
12163 #endif
12164 #ifdef SQLITE_CHECK_PAGES
12165   "CHECK_PAGES",
12166 #endif
12167 #ifdef SQLITE_COVERAGE_TEST
12168   "COVERAGE_TEST",
12169 #endif
12170 #ifdef SQLITE_DEBUG
12171   "DEBUG",
12172 #endif
12173 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12174   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12175 #endif
12176 #ifdef SQLITE_DISABLE_DIRSYNC
12177   "DISABLE_DIRSYNC",
12178 #endif
12179 #ifdef SQLITE_DISABLE_LFS
12180   "DISABLE_LFS",
12181 #endif
12182 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12183   "ENABLE_ATOMIC_WRITE",
12184 #endif
12185 #ifdef SQLITE_ENABLE_CEROD
12186   "ENABLE_CEROD",
12187 #endif
12188 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12189   "ENABLE_COLUMN_METADATA",
12190 #endif
12191 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12192   "ENABLE_EXPENSIVE_ASSERT",
12193 #endif
12194 #ifdef SQLITE_ENABLE_FTS1
12195   "ENABLE_FTS1",
12196 #endif
12197 #ifdef SQLITE_ENABLE_FTS2
12198   "ENABLE_FTS2",
12199 #endif
12200 #ifdef SQLITE_ENABLE_FTS3
12201   "ENABLE_FTS3",
12202 #endif
12203 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12204   "ENABLE_FTS3_PARENTHESIS",
12205 #endif
12206 #ifdef SQLITE_ENABLE_FTS4
12207   "ENABLE_FTS4",
12208 #endif
12209 #ifdef SQLITE_ENABLE_ICU
12210   "ENABLE_ICU",
12211 #endif
12212 #ifdef SQLITE_ENABLE_IOTRACE
12213   "ENABLE_IOTRACE",
12214 #endif
12215 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12216   "ENABLE_LOAD_EXTENSION",
12217 #endif
12218 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12219   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12220 #endif
12221 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12222   "ENABLE_MEMORY_MANAGEMENT",
12223 #endif
12224 #ifdef SQLITE_ENABLE_MEMSYS3
12225   "ENABLE_MEMSYS3",
12226 #endif
12227 #ifdef SQLITE_ENABLE_MEMSYS5
12228   "ENABLE_MEMSYS5",
12229 #endif
12230 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12231   "ENABLE_OVERSIZE_CELL_CHECK",
12232 #endif
12233 #ifdef SQLITE_ENABLE_RTREE
12234   "ENABLE_RTREE",
12235 #endif
12236 #ifdef SQLITE_ENABLE_STAT2
12237   "ENABLE_STAT2",
12238 #endif
12239 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12240   "ENABLE_UNLOCK_NOTIFY",
12241 #endif
12242 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12243   "ENABLE_UPDATE_DELETE_LIMIT",
12244 #endif
12245 #ifdef SQLITE_HAS_CODEC
12246   "HAS_CODEC",
12247 #endif
12248 #ifdef SQLITE_HAVE_ISNAN
12249   "HAVE_ISNAN",
12250 #endif
12251 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12252   "HOMEGROWN_RECURSIVE_MUTEX",
12253 #endif
12254 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12255   "IGNORE_AFP_LOCK_ERRORS",
12256 #endif
12257 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12258   "IGNORE_FLOCK_LOCK_ERRORS",
12259 #endif
12260 #ifdef SQLITE_INT64_TYPE
12261   "INT64_TYPE",
12262 #endif
12263 #ifdef SQLITE_LOCK_TRACE
12264   "LOCK_TRACE",
12265 #endif
12266 #ifdef SQLITE_MAX_SCHEMA_RETRY
12267   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12268 #endif
12269 #ifdef SQLITE_MEMDEBUG
12270   "MEMDEBUG",
12271 #endif
12272 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12273   "MIXED_ENDIAN_64BIT_FLOAT",
12274 #endif
12275 #ifdef SQLITE_NO_SYNC
12276   "NO_SYNC",
12277 #endif
12278 #ifdef SQLITE_OMIT_ALTERTABLE
12279   "OMIT_ALTERTABLE",
12280 #endif
12281 #ifdef SQLITE_OMIT_ANALYZE
12282   "OMIT_ANALYZE",
12283 #endif
12284 #ifdef SQLITE_OMIT_ATTACH
12285   "OMIT_ATTACH",
12286 #endif
12287 #ifdef SQLITE_OMIT_AUTHORIZATION
12288   "OMIT_AUTHORIZATION",
12289 #endif
12290 #ifdef SQLITE_OMIT_AUTOINCREMENT
12291   "OMIT_AUTOINCREMENT",
12292 #endif
12293 #ifdef SQLITE_OMIT_AUTOINIT
12294   "OMIT_AUTOINIT",
12295 #endif
12296 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12297   "OMIT_AUTOMATIC_INDEX",
12298 #endif
12299 #ifdef SQLITE_OMIT_AUTORESET
12300   "OMIT_AUTORESET",
12301 #endif
12302 #ifdef SQLITE_OMIT_AUTOVACUUM
12303   "OMIT_AUTOVACUUM",
12304 #endif
12305 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12306   "OMIT_BETWEEN_OPTIMIZATION",
12307 #endif
12308 #ifdef SQLITE_OMIT_BLOB_LITERAL
12309   "OMIT_BLOB_LITERAL",
12310 #endif
12311 #ifdef SQLITE_OMIT_BTREECOUNT
12312   "OMIT_BTREECOUNT",
12313 #endif
12314 #ifdef SQLITE_OMIT_BUILTIN_TEST
12315   "OMIT_BUILTIN_TEST",
12316 #endif
12317 #ifdef SQLITE_OMIT_CAST
12318   "OMIT_CAST",
12319 #endif
12320 #ifdef SQLITE_OMIT_CHECK
12321   "OMIT_CHECK",
12322 #endif
12323 /* // redundant
12324 ** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12325 **   "OMIT_COMPILEOPTION_DIAGS",
12326 ** #endif
12327 */
12328 #ifdef SQLITE_OMIT_COMPLETE
12329   "OMIT_COMPLETE",
12330 #endif
12331 #ifdef SQLITE_OMIT_COMPOUND_SELECT
12332   "OMIT_COMPOUND_SELECT",
12333 #endif
12334 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12335   "OMIT_DATETIME_FUNCS",
12336 #endif
12337 #ifdef SQLITE_OMIT_DECLTYPE
12338   "OMIT_DECLTYPE",
12339 #endif
12340 #ifdef SQLITE_OMIT_DEPRECATED
12341   "OMIT_DEPRECATED",
12342 #endif
12343 #ifdef SQLITE_OMIT_DISKIO
12344   "OMIT_DISKIO",
12345 #endif
12346 #ifdef SQLITE_OMIT_EXPLAIN
12347   "OMIT_EXPLAIN",
12348 #endif
12349 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
12350   "OMIT_FLAG_PRAGMAS",
12351 #endif
12352 #ifdef SQLITE_OMIT_FLOATING_POINT
12353   "OMIT_FLOATING_POINT",
12354 #endif
12355 #ifdef SQLITE_OMIT_FOREIGN_KEY
12356   "OMIT_FOREIGN_KEY",
12357 #endif
12358 #ifdef SQLITE_OMIT_GET_TABLE
12359   "OMIT_GET_TABLE",
12360 #endif
12361 #ifdef SQLITE_OMIT_INCRBLOB
12362   "OMIT_INCRBLOB",
12363 #endif
12364 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
12365   "OMIT_INTEGRITY_CHECK",
12366 #endif
12367 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12368   "OMIT_LIKE_OPTIMIZATION",
12369 #endif
12370 #ifdef SQLITE_OMIT_LOAD_EXTENSION
12371   "OMIT_LOAD_EXTENSION",
12372 #endif
12373 #ifdef SQLITE_OMIT_LOCALTIME
12374   "OMIT_LOCALTIME",
12375 #endif
12376 #ifdef SQLITE_OMIT_LOOKASIDE
12377   "OMIT_LOOKASIDE",
12378 #endif
12379 #ifdef SQLITE_OMIT_MEMORYDB
12380   "OMIT_MEMORYDB",
12381 #endif
12382 #ifdef SQLITE_OMIT_MERGE_SORT
12383   "OMIT_MERGE_SORT",
12384 #endif
12385 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
12386   "OMIT_OR_OPTIMIZATION",
12387 #endif
12388 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
12389   "OMIT_PAGER_PRAGMAS",
12390 #endif
12391 #ifdef SQLITE_OMIT_PRAGMA
12392   "OMIT_PRAGMA",
12393 #endif
12394 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12395   "OMIT_PROGRESS_CALLBACK",
12396 #endif
12397 #ifdef SQLITE_OMIT_QUICKBALANCE
12398   "OMIT_QUICKBALANCE",
12399 #endif
12400 #ifdef SQLITE_OMIT_REINDEX
12401   "OMIT_REINDEX",
12402 #endif
12403 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12404   "OMIT_SCHEMA_PRAGMAS",
12405 #endif
12406 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12407   "OMIT_SCHEMA_VERSION_PRAGMAS",
12408 #endif
12409 #ifdef SQLITE_OMIT_SHARED_CACHE
12410   "OMIT_SHARED_CACHE",
12411 #endif
12412 #ifdef SQLITE_OMIT_SUBQUERY
12413   "OMIT_SUBQUERY",
12414 #endif
12415 #ifdef SQLITE_OMIT_TCL_VARIABLE
12416   "OMIT_TCL_VARIABLE",
12417 #endif
12418 #ifdef SQLITE_OMIT_TEMPDB
12419   "OMIT_TEMPDB",
12420 #endif
12421 #ifdef SQLITE_OMIT_TRACE
12422   "OMIT_TRACE",
12423 #endif
12424 #ifdef SQLITE_OMIT_TRIGGER
12425   "OMIT_TRIGGER",
12426 #endif
12427 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12428   "OMIT_TRUNCATE_OPTIMIZATION",
12429 #endif
12430 #ifdef SQLITE_OMIT_UTF16
12431   "OMIT_UTF16",
12432 #endif
12433 #ifdef SQLITE_OMIT_VACUUM
12434   "OMIT_VACUUM",
12435 #endif
12436 #ifdef SQLITE_OMIT_VIEW
12437   "OMIT_VIEW",
12438 #endif
12439 #ifdef SQLITE_OMIT_VIRTUALTABLE
12440   "OMIT_VIRTUALTABLE",
12441 #endif
12442 #ifdef SQLITE_OMIT_WAL
12443   "OMIT_WAL",
12444 #endif
12445 #ifdef SQLITE_OMIT_WSD
12446   "OMIT_WSD",
12447 #endif
12448 #ifdef SQLITE_OMIT_XFER_OPT
12449   "OMIT_XFER_OPT",
12450 #endif
12451 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
12452   "PAGECACHE_BLOCKALLOC",
12453 #endif
12454 #ifdef SQLITE_PERFORMANCE_TRACE
12455   "PERFORMANCE_TRACE",
12456 #endif
12457 #ifdef SQLITE_PROXY_DEBUG
12458   "PROXY_DEBUG",
12459 #endif
12460 #ifdef SQLITE_SECURE_DELETE
12461   "SECURE_DELETE",
12462 #endif
12463 #ifdef SQLITE_SMALL_STACK
12464   "SMALL_STACK",
12465 #endif
12466 #ifdef SQLITE_SOUNDEX
12467   "SOUNDEX",
12468 #endif
12469 #ifdef SQLITE_TCL
12470   "TCL",
12471 #endif
12472 #ifdef SQLITE_TEMP_STORE
12473   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12474 #endif
12475 #ifdef SQLITE_TEST
12476   "TEST",
12477 #endif
12478 #ifdef SQLITE_THREADSAFE
12479   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12480 #endif
12481 #ifdef SQLITE_USE_ALLOCA
12482   "USE_ALLOCA",
12483 #endif
12484 #ifdef SQLITE_ZERO_MALLOC
12485   "ZERO_MALLOC"
12486 #endif
12487 };
12488 
12489 /*
12490 ** Given the name of a compile-time option, return true if that option
12491 ** was used and false if not.
12492 **
12493 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12494 ** is not required for a match.
12495 */
sqlite3_compileoption_used(const char * zOptName)12496 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12497   int i, n;
12498   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12499   n = sqlite3Strlen30(zOptName);
12500 
12501   /* Since ArraySize(azCompileOpt) is normally in single digits, a
12502   ** linear search is adequate.  No need for a binary search. */
12503   for(i=0; i<ArraySize(azCompileOpt); i++){
12504     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12505        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12506   }
12507   return 0;
12508 }
12509 
12510 /*
12511 ** Return the N-th compile-time option string.  If N is out of range,
12512 ** return a NULL pointer.
12513 */
sqlite3_compileoption_get(int N)12514 SQLITE_API const char *sqlite3_compileoption_get(int N){
12515   if( N>=0 && N<ArraySize(azCompileOpt) ){
12516     return azCompileOpt[N];
12517   }
12518   return 0;
12519 }
12520 
12521 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12522 
12523 /************** End of ctime.c ***********************************************/
12524 /************** Begin file status.c ******************************************/
12525 /*
12526 ** 2008 June 18
12527 **
12528 ** The author disclaims copyright to this source code.  In place of
12529 ** a legal notice, here is a blessing:
12530 **
12531 **    May you do good and not evil.
12532 **    May you find forgiveness for yourself and forgive others.
12533 **    May you share freely, never taking more than you give.
12534 **
12535 *************************************************************************
12536 **
12537 ** This module implements the sqlite3_status() interface and related
12538 ** functionality.
12539 */
12540 /************** Include vdbeInt.h in the middle of status.c ******************/
12541 /************** Begin file vdbeInt.h *****************************************/
12542 /*
12543 ** 2003 September 6
12544 **
12545 ** The author disclaims copyright to this source code.  In place of
12546 ** a legal notice, here is a blessing:
12547 **
12548 **    May you do good and not evil.
12549 **    May you find forgiveness for yourself and forgive others.
12550 **    May you share freely, never taking more than you give.
12551 **
12552 *************************************************************************
12553 ** This is the header file for information that is private to the
12554 ** VDBE.  This information used to all be at the top of the single
12555 ** source code file "vdbe.c".  When that file became too big (over
12556 ** 6000 lines long) it was split up into several smaller files and
12557 ** this header information was factored out.
12558 */
12559 #ifndef _VDBEINT_H_
12560 #define _VDBEINT_H_
12561 
12562 /*
12563 ** SQL is translated into a sequence of instructions to be
12564 ** executed by a virtual machine.  Each instruction is an instance
12565 ** of the following structure.
12566 */
12567 typedef struct VdbeOp Op;
12568 
12569 /*
12570 ** Boolean values
12571 */
12572 typedef unsigned char Bool;
12573 
12574 /* Opaque type used by code in vdbesort.c */
12575 typedef struct VdbeSorter VdbeSorter;
12576 
12577 /*
12578 ** A cursor is a pointer into a single BTree within a database file.
12579 ** The cursor can seek to a BTree entry with a particular key, or
12580 ** loop over all entries of the Btree.  You can also insert new BTree
12581 ** entries or retrieve the key or data from the entry that the cursor
12582 ** is currently pointing to.
12583 **
12584 ** Every cursor that the virtual machine has open is represented by an
12585 ** instance of the following structure.
12586 */
12587 struct VdbeCursor {
12588   BtCursor *pCursor;    /* The cursor structure of the backend */
12589   Btree *pBt;           /* Separate file holding temporary table */
12590   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12591   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12592   int pseudoTableReg;   /* Register holding pseudotable content. */
12593   int nField;           /* Number of fields in the header */
12594   Bool zeroed;          /* True if zeroed out and ready for reuse */
12595   Bool rowidIsValid;    /* True if lastRowid is valid */
12596   Bool atFirst;         /* True if pointing to first entry */
12597   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12598   Bool nullRow;         /* True if pointing to a row with no data */
12599   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12600   Bool isTable;         /* True if a table requiring integer keys */
12601   Bool isIndex;         /* True if an index containing keys only - no data */
12602   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12603   Bool isSorter;        /* True if a new-style sorter */
12604   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12605   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12606   i64 seqCount;         /* Sequence counter */
12607   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12608   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12609   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
12610 
12611   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12612   ** OP_IsUnique opcode on this cursor. */
12613   int seekResult;
12614 
12615   /* Cached information about the header for the data record that the
12616   ** cursor is currently pointing to.  Only valid if cacheStatus matches
12617   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12618   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12619   ** the cache is out of date.
12620   **
12621   ** aRow might point to (ephemeral) data for the current row, or it might
12622   ** be NULL.
12623   */
12624   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12625   int payloadSize;      /* Total number of bytes in the record */
12626   u32 *aType;           /* Type values for all entries in the record */
12627   u32 *aOffset;         /* Cached offsets to the start of each columns data */
12628   u8 *aRow;             /* Data for the current row, if all on one page */
12629 };
12630 typedef struct VdbeCursor VdbeCursor;
12631 
12632 /*
12633 ** When a sub-program is executed (OP_Program), a structure of this type
12634 ** is allocated to store the current value of the program counter, as
12635 ** well as the current memory cell array and various other frame specific
12636 ** values stored in the Vdbe struct. When the sub-program is finished,
12637 ** these values are copied back to the Vdbe from the VdbeFrame structure,
12638 ** restoring the state of the VM to as it was before the sub-program
12639 ** began executing.
12640 **
12641 ** The memory for a VdbeFrame object is allocated and managed by a memory
12642 ** cell in the parent (calling) frame. When the memory cell is deleted or
12643 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12644 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12645 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12646 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
12647 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12648 ** child frame are released.
12649 **
12650 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12651 ** set to NULL if the currently executing frame is the main program.
12652 */
12653 typedef struct VdbeFrame VdbeFrame;
12654 struct VdbeFrame {
12655   Vdbe *v;                /* VM this frame belongs to */
12656   int pc;                 /* Program Counter in parent (calling) frame */
12657   Op *aOp;                /* Program instructions for parent frame */
12658   int nOp;                /* Size of aOp array */
12659   Mem *aMem;              /* Array of memory cells for parent frame */
12660   int nMem;               /* Number of entries in aMem */
12661   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12662   u16 nCursor;            /* Number of entries in apCsr */
12663   void *token;            /* Copy of SubProgram.token */
12664   int nChildMem;          /* Number of memory cells for child frame */
12665   int nChildCsr;          /* Number of cursors for child frame */
12666   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12667   int nChange;            /* Statement changes (Vdbe.nChanges)     */
12668   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12669 };
12670 
12671 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12672 
12673 /*
12674 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12675 */
12676 #define CACHE_STALE 0
12677 
12678 /*
12679 ** Internally, the vdbe manipulates nearly all SQL values as Mem
12680 ** structures. Each Mem struct may cache multiple representations (string,
12681 ** integer etc.) of the same value.
12682 */
12683 struct Mem {
12684   sqlite3 *db;        /* The associated database connection */
12685   char *z;            /* String or BLOB value */
12686   double r;           /* Real value */
12687   union {
12688     i64 i;              /* Integer value used when MEM_Int is set in flags */
12689     int nZero;          /* Used when bit MEM_Zero is set in flags */
12690     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12691     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12692     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12693   } u;
12694   int n;              /* Number of characters in string value, excluding '\0' */
12695   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12696   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12697   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12698 #ifdef SQLITE_DEBUG
12699   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12700   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12701 #endif
12702   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12703   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12704 };
12705 
12706 /* One or more of the following flags are set to indicate the validOK
12707 ** representations of the value stored in the Mem struct.
12708 **
12709 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
12710 ** No other flags may be set in this case.
12711 **
12712 ** If the MEM_Str flag is set then Mem.z points at a string representation.
12713 ** Usually this is encoded in the same unicode encoding as the main
12714 ** database (see below for exceptions). If the MEM_Term flag is also
12715 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
12716 ** flags may coexist with the MEM_Str flag.
12717 */
12718 #define MEM_Null      0x0001   /* Value is NULL */
12719 #define MEM_Str       0x0002   /* Value is a string */
12720 #define MEM_Int       0x0004   /* Value is an integer */
12721 #define MEM_Real      0x0008   /* Value is a real number */
12722 #define MEM_Blob      0x0010   /* Value is a BLOB */
12723 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
12724 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
12725 #define MEM_Invalid   0x0080   /* Value is undefined */
12726 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
12727 
12728 /* Whenever Mem contains a valid string or blob representation, one of
12729 ** the following flags must be set to determine the memory management
12730 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
12731 ** string is \000 or \u0000 terminated
12732 */
12733 #define MEM_Term      0x0200   /* String rep is nul terminated */
12734 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
12735 #define MEM_Static    0x0800   /* Mem.z points to a static string */
12736 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
12737 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
12738 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
12739 #ifdef SQLITE_OMIT_INCRBLOB
12740   #undef MEM_Zero
12741   #define MEM_Zero 0x0000
12742 #endif
12743 
12744 /*
12745 ** Clear any existing type flags from a Mem and replace them with f
12746 */
12747 #define MemSetTypeFlag(p, f) \
12748    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
12749 
12750 /*
12751 ** Return true if a memory cell is not marked as invalid.  This macro
12752 ** is for use inside assert() statements only.
12753 */
12754 #ifdef SQLITE_DEBUG
12755 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
12756 #endif
12757 
12758 
12759 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
12760 ** additional information about auxiliary information bound to arguments
12761 ** of the function.  This is used to implement the sqlite3_get_auxdata()
12762 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
12763 ** that can be associated with a constant argument to a function.  This
12764 ** allows functions such as "regexp" to compile their constant regular
12765 ** expression argument once and reused the compiled code for multiple
12766 ** invocations.
12767 */
12768 struct VdbeFunc {
12769   FuncDef *pFunc;               /* The definition of the function */
12770   int nAux;                     /* Number of entries allocated for apAux[] */
12771   struct AuxData {
12772     void *pAux;                   /* Aux data for the i-th argument */
12773     void (*xDelete)(void *);      /* Destructor for the aux data */
12774   } apAux[1];                   /* One slot for each function argument */
12775 };
12776 
12777 /*
12778 ** The "context" argument for a installable function.  A pointer to an
12779 ** instance of this structure is the first argument to the routines used
12780 ** implement the SQL functions.
12781 **
12782 ** There is a typedef for this structure in sqlite.h.  So all routines,
12783 ** even the public interface to SQLite, can use a pointer to this structure.
12784 ** But this file is the only place where the internal details of this
12785 ** structure are known.
12786 **
12787 ** This structure is defined inside of vdbeInt.h because it uses substructures
12788 ** (Mem) which are only defined there.
12789 */
12790 struct sqlite3_context {
12791   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
12792   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
12793   Mem s;                /* The return value is stored here */
12794   Mem *pMem;            /* Memory cell used to store aggregate context */
12795   int isError;          /* Error code returned by the function. */
12796   CollSeq *pColl;       /* Collating sequence */
12797 };
12798 
12799 /*
12800 ** An instance of the virtual machine.  This structure contains the complete
12801 ** state of the virtual machine.
12802 **
12803 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
12804 ** is really a pointer to an instance of this structure.
12805 **
12806 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
12807 ** any virtual table method invocations made by the vdbe program. It is
12808 ** set to 2 for xDestroy method calls and 1 for all other methods. This
12809 ** variable is used for two purposes: to allow xDestroy methods to execute
12810 ** "DROP TABLE" statements and to prevent some nasty side effects of
12811 ** malloc failure when SQLite is invoked recursively by a virtual table
12812 ** method function.
12813 */
12814 struct Vdbe {
12815   sqlite3 *db;            /* The database connection that owns this statement */
12816   Op *aOp;                /* Space to hold the virtual machine's program */
12817   Mem *aMem;              /* The memory locations */
12818   Mem **apArg;            /* Arguments to currently executing user function */
12819   Mem *aColName;          /* Column names to return */
12820   Mem *pResultSet;        /* Pointer to an array of results */
12821   int nMem;               /* Number of memory locations currently allocated */
12822   int nOp;                /* Number of instructions in the program */
12823   int nOpAlloc;           /* Number of slots allocated for aOp[] */
12824   int nLabel;             /* Number of labels used */
12825   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
12826   int *aLabel;            /* Space to hold the labels */
12827   u16 nResColumn;         /* Number of columns in one row of the result set */
12828   u16 nCursor;            /* Number of slots in apCsr[] */
12829   u32 magic;              /* Magic number for sanity checking */
12830   char *zErrMsg;          /* Error message written here */
12831   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
12832   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
12833   Mem *aVar;              /* Values for the OP_Variable opcode. */
12834   char **azVar;           /* Name of variables */
12835   ynVar nVar;             /* Number of entries in aVar[] */
12836   ynVar nzVar;            /* Number of entries in azVar[] */
12837   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
12838   int pc;                 /* The program counter */
12839   int rc;                 /* Value to return */
12840   u8 errorAction;         /* Recovery action to do in case of an error */
12841   u8 explain;             /* True if EXPLAIN present on SQL command */
12842   u8 changeCntOn;         /* True to update the change-counter */
12843   u8 expired;             /* True if the VM needs to be recompiled */
12844   u8 runOnlyOnce;         /* Automatically expire on reset */
12845   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
12846   u8 inVtabMethod;        /* See comments above */
12847   u8 usesStmtJournal;     /* True if uses a statement journal */
12848   u8 readOnly;            /* True for read-only statements */
12849   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
12850   int nChange;            /* Number of db changes made since last reset */
12851   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
12852   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
12853   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
12854   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
12855 #ifndef SQLITE_OMIT_TRACE
12856   i64 startTime;          /* Time when query started - used for profiling */
12857 #endif
12858   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
12859   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
12860   char *zSql;             /* Text of the SQL statement that generated this */
12861   void *pFree;            /* Free this when deleting the vdbe */
12862 #ifdef SQLITE_DEBUG
12863   FILE *trace;            /* Write an execution trace here, if not NULL */
12864 #endif
12865   VdbeFrame *pFrame;      /* Parent frame */
12866   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
12867   int nFrame;             /* Number of frames in pFrame list */
12868   u32 expmask;            /* Binding to these vars invalidates VM */
12869   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
12870 };
12871 
12872 /*
12873 ** The following are allowed values for Vdbe.magic
12874 */
12875 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
12876 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
12877 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
12878 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
12879 
12880 /*
12881 ** Function prototypes
12882 */
12883 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
12884 void sqliteVdbePopStack(Vdbe*,int);
12885 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
12886 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
12887 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
12888 #endif
12889 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
12890 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
12891 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
12892 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
12893 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
12894 
12895 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
12896 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
12897 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
12898 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12899 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
12900 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
12901 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
12902 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
12903 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
12904 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
12905 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
12906 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
12907 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
12908 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
12909 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
12910 #ifdef SQLITE_OMIT_FLOATING_POINT
12911 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
12912 #else
12913 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
12914 #endif
12915 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
12916 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
12917 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
12918 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
12919 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
12920 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
12921 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
12922 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
12923 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
12924 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
12925 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
12926 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
12927 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
12928 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
12929 #define MemReleaseExt(X)  \
12930   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
12931     sqlite3VdbeMemReleaseExternal(X);
12932 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
12933 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
12934 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
12935 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
12936 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
12937 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
12938 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
12939 
12940 #ifdef SQLITE_OMIT_MERGE_SORT
12941 # define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
12942 # define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
12943 # define sqlite3VdbeSorterClose(Y,Z)
12944 # define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
12945 # define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
12946 # define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
12947 # define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
12948 #else
12949 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
12950 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
12951 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
12952 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
12953 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
12954 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
12955 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
12956 #endif
12957 
12958 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
12959 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
12960 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
12961 #else
12962 # define sqlite3VdbeEnter(X)
12963 # define sqlite3VdbeLeave(X)
12964 #endif
12965 
12966 #ifdef SQLITE_DEBUG
12967 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem*);
12968 #endif
12969 
12970 #ifndef SQLITE_OMIT_FOREIGN_KEY
12971 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
12972 #else
12973 # define sqlite3VdbeCheckFk(p,i) 0
12974 #endif
12975 
12976 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
12977 #ifdef SQLITE_DEBUG
12978 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
12979 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
12980 #endif
12981 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
12982 
12983 #ifndef SQLITE_OMIT_INCRBLOB
12984 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
12985 #else
12986   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
12987 #endif
12988 
12989 #endif /* !defined(_VDBEINT_H_) */
12990 
12991 /************** End of vdbeInt.h *********************************************/
12992 /************** Continuing where we left off in status.c *********************/
12993 
12994 /*
12995 ** Variables in which to record status information.
12996 */
12997 typedef struct sqlite3StatType sqlite3StatType;
12998 static SQLITE_WSD struct sqlite3StatType {
12999   int nowValue[10];         /* Current value */
13000   int mxValue[10];          /* Maximum value */
13001 } sqlite3Stat = { {0,}, {0,} };
13002 
13003 
13004 /* The "wsdStat" macro will resolve to the status information
13005 ** state vector.  If writable static data is unsupported on the target,
13006 ** we have to locate the state vector at run-time.  In the more common
13007 ** case where writable static data is supported, wsdStat can refer directly
13008 ** to the "sqlite3Stat" state vector declared above.
13009 */
13010 #ifdef SQLITE_OMIT_WSD
13011 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13012 # define wsdStat x[0]
13013 #else
13014 # define wsdStatInit
13015 # define wsdStat sqlite3Stat
13016 #endif
13017 
13018 /*
13019 ** Return the current value of a status parameter.
13020 */
sqlite3StatusValue(int op)13021 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13022   wsdStatInit;
13023   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13024   return wsdStat.nowValue[op];
13025 }
13026 
13027 /*
13028 ** Add N to the value of a status record.  It is assumed that the
13029 ** caller holds appropriate locks.
13030 */
sqlite3StatusAdd(int op,int N)13031 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13032   wsdStatInit;
13033   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13034   wsdStat.nowValue[op] += N;
13035   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13036     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13037   }
13038 }
13039 
13040 /*
13041 ** Set the value of a status to X.
13042 */
sqlite3StatusSet(int op,int X)13043 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13044   wsdStatInit;
13045   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13046   wsdStat.nowValue[op] = X;
13047   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13048     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13049   }
13050 }
13051 
13052 /*
13053 ** Query status information.
13054 **
13055 ** This implementation assumes that reading or writing an aligned
13056 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13057 ** then this routine is not threadsafe.
13058 */
sqlite3_status(int op,int * pCurrent,int * pHighwater,int resetFlag)13059 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13060   wsdStatInit;
13061   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13062     return SQLITE_MISUSE_BKPT;
13063   }
13064   *pCurrent = wsdStat.nowValue[op];
13065   *pHighwater = wsdStat.mxValue[op];
13066   if( resetFlag ){
13067     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13068   }
13069   return SQLITE_OK;
13070 }
13071 
13072 /*
13073 ** Query status information for a single database connection
13074 */
sqlite3_db_status(sqlite3 * db,int op,int * pCurrent,int * pHighwater,int resetFlag)13075 SQLITE_API int sqlite3_db_status(
13076   sqlite3 *db,          /* The database connection whose status is desired */
13077   int op,               /* Status verb */
13078   int *pCurrent,        /* Write current value here */
13079   int *pHighwater,      /* Write high-water mark here */
13080   int resetFlag         /* Reset high-water mark if true */
13081 ){
13082   int rc = SQLITE_OK;   /* Return code */
13083   sqlite3_mutex_enter(db->mutex);
13084   switch( op ){
13085     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13086       *pCurrent = db->lookaside.nOut;
13087       *pHighwater = db->lookaside.mxOut;
13088       if( resetFlag ){
13089         db->lookaside.mxOut = db->lookaside.nOut;
13090       }
13091       break;
13092     }
13093 
13094     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13095     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13096     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13097       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13098       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13099       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13100       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13101       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13102       *pCurrent = 0;
13103       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13104       if( resetFlag ){
13105         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13106       }
13107       break;
13108     }
13109 
13110     /*
13111     ** Return an approximation for the amount of memory currently used
13112     ** by all pagers associated with the given database connection.  The
13113     ** highwater mark is meaningless and is returned as zero.
13114     */
13115     case SQLITE_DBSTATUS_CACHE_USED: {
13116       int totalUsed = 0;
13117       int i;
13118       sqlite3BtreeEnterAll(db);
13119       for(i=0; i<db->nDb; i++){
13120         Btree *pBt = db->aDb[i].pBt;
13121         if( pBt ){
13122           Pager *pPager = sqlite3BtreePager(pBt);
13123           totalUsed += sqlite3PagerMemUsed(pPager);
13124         }
13125       }
13126       sqlite3BtreeLeaveAll(db);
13127       *pCurrent = totalUsed;
13128       *pHighwater = 0;
13129       break;
13130     }
13131 
13132     /*
13133     ** *pCurrent gets an accurate estimate of the amount of memory used
13134     ** to store the schema for all databases (main, temp, and any ATTACHed
13135     ** databases.  *pHighwater is set to zero.
13136     */
13137     case SQLITE_DBSTATUS_SCHEMA_USED: {
13138       int i;                      /* Used to iterate through schemas */
13139       int nByte = 0;              /* Used to accumulate return value */
13140 
13141       sqlite3BtreeEnterAll(db);
13142       db->pnBytesFreed = &nByte;
13143       for(i=0; i<db->nDb; i++){
13144         Schema *pSchema = db->aDb[i].pSchema;
13145         if( ALWAYS(pSchema!=0) ){
13146           HashElem *p;
13147 
13148           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13149               pSchema->tblHash.count
13150             + pSchema->trigHash.count
13151             + pSchema->idxHash.count
13152             + pSchema->fkeyHash.count
13153           );
13154           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13155           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13156           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13157           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13158 
13159           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13160             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13161           }
13162           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13163             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13164           }
13165         }
13166       }
13167       db->pnBytesFreed = 0;
13168       sqlite3BtreeLeaveAll(db);
13169 
13170       *pHighwater = 0;
13171       *pCurrent = nByte;
13172       break;
13173     }
13174 
13175     /*
13176     ** *pCurrent gets an accurate estimate of the amount of memory used
13177     ** to store all prepared statements.
13178     ** *pHighwater is set to zero.
13179     */
13180     case SQLITE_DBSTATUS_STMT_USED: {
13181       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13182       int nByte = 0;              /* Used to accumulate return value */
13183 
13184       db->pnBytesFreed = &nByte;
13185       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13186         sqlite3VdbeDeleteObject(db, pVdbe);
13187       }
13188       db->pnBytesFreed = 0;
13189 
13190       *pHighwater = 0;
13191       *pCurrent = nByte;
13192 
13193       break;
13194     }
13195 
13196     default: {
13197       rc = SQLITE_ERROR;
13198     }
13199   }
13200   sqlite3_mutex_leave(db->mutex);
13201   return rc;
13202 }
13203 
13204 /************** End of status.c **********************************************/
13205 /************** Begin file date.c ********************************************/
13206 /*
13207 ** 2003 October 31
13208 **
13209 ** The author disclaims copyright to this source code.  In place of
13210 ** a legal notice, here is a blessing:
13211 **
13212 **    May you do good and not evil.
13213 **    May you find forgiveness for yourself and forgive others.
13214 **    May you share freely, never taking more than you give.
13215 **
13216 *************************************************************************
13217 ** This file contains the C functions that implement date and time
13218 ** functions for SQLite.
13219 **
13220 ** There is only one exported symbol in this file - the function
13221 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13222 ** All other code has file scope.
13223 **
13224 ** SQLite processes all times and dates as Julian Day numbers.  The
13225 ** dates and times are stored as the number of days since noon
13226 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13227 ** calendar system.
13228 **
13229 ** 1970-01-01 00:00:00 is JD 2440587.5
13230 ** 2000-01-01 00:00:00 is JD 2451544.5
13231 **
13232 ** This implemention requires years to be expressed as a 4-digit number
13233 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13234 ** be represented, even though julian day numbers allow a much wider
13235 ** range of dates.
13236 **
13237 ** The Gregorian calendar system is used for all dates and times,
13238 ** even those that predate the Gregorian calendar.  Historians usually
13239 ** use the Julian calendar for dates prior to 1582-10-15 and for some
13240 ** dates afterwards, depending on locale.  Beware of this difference.
13241 **
13242 ** The conversion algorithms are implemented based on descriptions
13243 ** in the following text:
13244 **
13245 **      Jean Meeus
13246 **      Astronomical Algorithms, 2nd Edition, 1998
13247 **      ISBM 0-943396-61-1
13248 **      Willmann-Bell, Inc
13249 **      Richmond, Virginia (USA)
13250 */
13251 /* #include <stdlib.h> */
13252 /* #include <assert.h> */
13253 #include <time.h>
13254 
13255 #ifndef SQLITE_OMIT_DATETIME_FUNCS
13256 
13257 
13258 /*
13259 ** A structure for holding a single date and time.
13260 */
13261 typedef struct DateTime DateTime;
13262 struct DateTime {
13263   sqlite3_int64 iJD; /* The julian day number times 86400000 */
13264   int Y, M, D;       /* Year, month, and day */
13265   int h, m;          /* Hour and minutes */
13266   int tz;            /* Timezone offset in minutes */
13267   double s;          /* Seconds */
13268   char validYMD;     /* True (1) if Y,M,D are valid */
13269   char validHMS;     /* True (1) if h,m,s are valid */
13270   char validJD;      /* True (1) if iJD is valid */
13271   char validTZ;      /* True (1) if tz is valid */
13272 };
13273 
13274 
13275 /*
13276 ** Convert zDate into one or more integers.  Additional arguments
13277 ** come in groups of 5 as follows:
13278 **
13279 **       N       number of digits in the integer
13280 **       min     minimum allowed value of the integer
13281 **       max     maximum allowed value of the integer
13282 **       nextC   first character after the integer
13283 **       pVal    where to write the integers value.
13284 **
13285 ** Conversions continue until one with nextC==0 is encountered.
13286 ** The function returns the number of successful conversions.
13287 */
getDigits(const char * zDate,...)13288 static int getDigits(const char *zDate, ...){
13289   va_list ap;
13290   int val;
13291   int N;
13292   int min;
13293   int max;
13294   int nextC;
13295   int *pVal;
13296   int cnt = 0;
13297   va_start(ap, zDate);
13298   do{
13299     N = va_arg(ap, int);
13300     min = va_arg(ap, int);
13301     max = va_arg(ap, int);
13302     nextC = va_arg(ap, int);
13303     pVal = va_arg(ap, int*);
13304     val = 0;
13305     while( N-- ){
13306       if( !sqlite3Isdigit(*zDate) ){
13307         goto end_getDigits;
13308       }
13309       val = val*10 + *zDate - '0';
13310       zDate++;
13311     }
13312     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13313       goto end_getDigits;
13314     }
13315     *pVal = val;
13316     zDate++;
13317     cnt++;
13318   }while( nextC );
13319 end_getDigits:
13320   va_end(ap);
13321   return cnt;
13322 }
13323 
13324 /*
13325 ** Parse a timezone extension on the end of a date-time.
13326 ** The extension is of the form:
13327 **
13328 **        (+/-)HH:MM
13329 **
13330 ** Or the "zulu" notation:
13331 **
13332 **        Z
13333 **
13334 ** If the parse is successful, write the number of minutes
13335 ** of change in p->tz and return 0.  If a parser error occurs,
13336 ** return non-zero.
13337 **
13338 ** A missing specifier is not considered an error.
13339 */
parseTimezone(const char * zDate,DateTime * p)13340 static int parseTimezone(const char *zDate, DateTime *p){
13341   int sgn = 0;
13342   int nHr, nMn;
13343   int c;
13344   while( sqlite3Isspace(*zDate) ){ zDate++; }
13345   p->tz = 0;
13346   c = *zDate;
13347   if( c=='-' ){
13348     sgn = -1;
13349   }else if( c=='+' ){
13350     sgn = +1;
13351   }else if( c=='Z' || c=='z' ){
13352     zDate++;
13353     goto zulu_time;
13354   }else{
13355     return c!=0;
13356   }
13357   zDate++;
13358   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13359     return 1;
13360   }
13361   zDate += 5;
13362   p->tz = sgn*(nMn + nHr*60);
13363 zulu_time:
13364   while( sqlite3Isspace(*zDate) ){ zDate++; }
13365   return *zDate!=0;
13366 }
13367 
13368 /*
13369 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13370 ** The HH, MM, and SS must each be exactly 2 digits.  The
13371 ** fractional seconds FFFF can be one or more digits.
13372 **
13373 ** Return 1 if there is a parsing error and 0 on success.
13374 */
parseHhMmSs(const char * zDate,DateTime * p)13375 static int parseHhMmSs(const char *zDate, DateTime *p){
13376   int h, m, s;
13377   double ms = 0.0;
13378   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13379     return 1;
13380   }
13381   zDate += 5;
13382   if( *zDate==':' ){
13383     zDate++;
13384     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13385       return 1;
13386     }
13387     zDate += 2;
13388     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13389       double rScale = 1.0;
13390       zDate++;
13391       while( sqlite3Isdigit(*zDate) ){
13392         ms = ms*10.0 + *zDate - '0';
13393         rScale *= 10.0;
13394         zDate++;
13395       }
13396       ms /= rScale;
13397     }
13398   }else{
13399     s = 0;
13400   }
13401   p->validJD = 0;
13402   p->validHMS = 1;
13403   p->h = h;
13404   p->m = m;
13405   p->s = s + ms;
13406   if( parseTimezone(zDate, p) ) return 1;
13407   p->validTZ = (p->tz!=0)?1:0;
13408   return 0;
13409 }
13410 
13411 /*
13412 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13413 ** that the YYYY-MM-DD is according to the Gregorian calendar.
13414 **
13415 ** Reference:  Meeus page 61
13416 */
computeJD(DateTime * p)13417 static void computeJD(DateTime *p){
13418   int Y, M, D, A, B, X1, X2;
13419 
13420   if( p->validJD ) return;
13421   if( p->validYMD ){
13422     Y = p->Y;
13423     M = p->M;
13424     D = p->D;
13425   }else{
13426     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13427     M = 1;
13428     D = 1;
13429   }
13430   if( M<=2 ){
13431     Y--;
13432     M += 12;
13433   }
13434   A = Y/100;
13435   B = 2 - A + (A/4);
13436   X1 = 36525*(Y+4716)/100;
13437   X2 = 306001*(M+1)/10000;
13438   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13439   p->validJD = 1;
13440   if( p->validHMS ){
13441     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13442     if( p->validTZ ){
13443       p->iJD -= p->tz*60000;
13444       p->validYMD = 0;
13445       p->validHMS = 0;
13446       p->validTZ = 0;
13447     }
13448   }
13449 }
13450 
13451 /*
13452 ** Parse dates of the form
13453 **
13454 **     YYYY-MM-DD HH:MM:SS.FFF
13455 **     YYYY-MM-DD HH:MM:SS
13456 **     YYYY-MM-DD HH:MM
13457 **     YYYY-MM-DD
13458 **
13459 ** Write the result into the DateTime structure and return 0
13460 ** on success and 1 if the input string is not a well-formed
13461 ** date.
13462 */
parseYyyyMmDd(const char * zDate,DateTime * p)13463 static int parseYyyyMmDd(const char *zDate, DateTime *p){
13464   int Y, M, D, neg;
13465 
13466   if( zDate[0]=='-' ){
13467     zDate++;
13468     neg = 1;
13469   }else{
13470     neg = 0;
13471   }
13472   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13473     return 1;
13474   }
13475   zDate += 10;
13476   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13477   if( parseHhMmSs(zDate, p)==0 ){
13478     /* We got the time */
13479   }else if( *zDate==0 ){
13480     p->validHMS = 0;
13481   }else{
13482     return 1;
13483   }
13484   p->validJD = 0;
13485   p->validYMD = 1;
13486   p->Y = neg ? -Y : Y;
13487   p->M = M;
13488   p->D = D;
13489   if( p->validTZ ){
13490     computeJD(p);
13491   }
13492   return 0;
13493 }
13494 
13495 /*
13496 ** Set the time to the current time reported by the VFS
13497 */
setDateTimeToCurrent(sqlite3_context * context,DateTime * p)13498 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13499   sqlite3 *db = sqlite3_context_db_handle(context);
13500   sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD);
13501   p->validJD = 1;
13502 }
13503 
13504 /*
13505 ** Attempt to parse the given string into a Julian Day Number.  Return
13506 ** the number of errors.
13507 **
13508 ** The following are acceptable forms for the input string:
13509 **
13510 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13511 **      DDDD.DD
13512 **      now
13513 **
13514 ** In the first form, the +/-HH:MM is always optional.  The fractional
13515 ** seconds extension (the ".FFF") is optional.  The seconds portion
13516 ** (":SS.FFF") is option.  The year and date can be omitted as long
13517 ** as there is a time string.  The time string can be omitted as long
13518 ** as there is a year and date.
13519 */
parseDateOrTime(sqlite3_context * context,const char * zDate,DateTime * p)13520 static int parseDateOrTime(
13521   sqlite3_context *context,
13522   const char *zDate,
13523   DateTime *p
13524 ){
13525   double r;
13526   if( parseYyyyMmDd(zDate,p)==0 ){
13527     return 0;
13528   }else if( parseHhMmSs(zDate, p)==0 ){
13529     return 0;
13530   }else if( sqlite3StrICmp(zDate,"now")==0){
13531     setDateTimeToCurrent(context, p);
13532     return 0;
13533   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13534     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13535     p->validJD = 1;
13536     return 0;
13537   }
13538   return 1;
13539 }
13540 
13541 /*
13542 ** Compute the Year, Month, and Day from the julian day number.
13543 */
computeYMD(DateTime * p)13544 static void computeYMD(DateTime *p){
13545   int Z, A, B, C, D, E, X1;
13546   if( p->validYMD ) return;
13547   if( !p->validJD ){
13548     p->Y = 2000;
13549     p->M = 1;
13550     p->D = 1;
13551   }else{
13552     Z = (int)((p->iJD + 43200000)/86400000);
13553     A = (int)((Z - 1867216.25)/36524.25);
13554     A = Z + 1 + A - (A/4);
13555     B = A + 1524;
13556     C = (int)((B - 122.1)/365.25);
13557     D = (36525*C)/100;
13558     E = (int)((B-D)/30.6001);
13559     X1 = (int)(30.6001*E);
13560     p->D = B - D - X1;
13561     p->M = E<14 ? E-1 : E-13;
13562     p->Y = p->M>2 ? C - 4716 : C - 4715;
13563   }
13564   p->validYMD = 1;
13565 }
13566 
13567 /*
13568 ** Compute the Hour, Minute, and Seconds from the julian day number.
13569 */
computeHMS(DateTime * p)13570 static void computeHMS(DateTime *p){
13571   int s;
13572   if( p->validHMS ) return;
13573   computeJD(p);
13574   s = (int)((p->iJD + 43200000) % 86400000);
13575   p->s = s/1000.0;
13576   s = (int)p->s;
13577   p->s -= s;
13578   p->h = s/3600;
13579   s -= p->h*3600;
13580   p->m = s/60;
13581   p->s += s - p->m*60;
13582   p->validHMS = 1;
13583 }
13584 
13585 /*
13586 ** Compute both YMD and HMS
13587 */
computeYMD_HMS(DateTime * p)13588 static void computeYMD_HMS(DateTime *p){
13589   computeYMD(p);
13590   computeHMS(p);
13591 }
13592 
13593 /*
13594 ** Clear the YMD and HMS and the TZ
13595 */
clearYMD_HMS_TZ(DateTime * p)13596 static void clearYMD_HMS_TZ(DateTime *p){
13597   p->validYMD = 0;
13598   p->validHMS = 0;
13599   p->validTZ = 0;
13600 }
13601 
13602 /*
13603 ** On recent Windows platforms, the localtime_s() function is available
13604 ** as part of the "Secure CRT". It is essentially equivalent to
13605 ** localtime_r() available under most POSIX platforms, except that the
13606 ** order of the parameters is reversed.
13607 **
13608 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
13609 **
13610 ** If the user has not indicated to use localtime_r() or localtime_s()
13611 ** already, check for an MSVC build environment that provides
13612 ** localtime_s().
13613 */
13614 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
13615      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
13616 #define HAVE_LOCALTIME_S 1
13617 #endif
13618 
13619 #ifndef SQLITE_OMIT_LOCALTIME
13620 /*
13621 ** The following routine implements the rough equivalent of localtime_r()
13622 ** using whatever operating-system specific localtime facility that
13623 ** is available.  This routine returns 0 on success and
13624 ** non-zero on any kind of error.
13625 **
13626 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
13627 ** routine will always fail.
13628 */
osLocaltime(time_t * t,struct tm * pTm)13629 static int osLocaltime(time_t *t, struct tm *pTm){
13630   int rc;
13631 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
13632       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
13633   struct tm *pX;
13634 #if SQLITE_THREADSAFE>0
13635   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13636 #endif
13637   sqlite3_mutex_enter(mutex);
13638   pX = localtime(t);
13639 #ifndef SQLITE_OMIT_BUILTIN_TEST
13640   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
13641 #endif
13642   if( pX ) *pTm = *pX;
13643   sqlite3_mutex_leave(mutex);
13644   rc = pX==0;
13645 #else
13646 #ifndef SQLITE_OMIT_BUILTIN_TEST
13647   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
13648 #endif
13649 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
13650   rc = localtime_r(t, pTm)==0;
13651 #else
13652   rc = localtime_s(pTm, t);
13653 #endif /* HAVE_LOCALTIME_R */
13654 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
13655   return rc;
13656 }
13657 #endif /* SQLITE_OMIT_LOCALTIME */
13658 
13659 
13660 #ifndef SQLITE_OMIT_LOCALTIME
13661 /*
13662 ** Compute the difference (in milliseconds) between localtime and UTC
13663 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
13664 ** return this value and set *pRc to SQLITE_OK.
13665 **
13666 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
13667 ** is undefined in this case.
13668 */
localtimeOffset(DateTime * p,sqlite3_context * pCtx,int * pRc)13669 static sqlite3_int64 localtimeOffset(
13670   DateTime *p,                    /* Date at which to calculate offset */
13671   sqlite3_context *pCtx,          /* Write error here if one occurs */
13672   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
13673 ){
13674   DateTime x, y;
13675   time_t t;
13676   struct tm sLocal;
13677 
13678   /* Initialize the contents of sLocal to avoid a compiler warning. */
13679   memset(&sLocal, 0, sizeof(sLocal));
13680 
13681   x = *p;
13682   computeYMD_HMS(&x);
13683   if( x.Y<1971 || x.Y>=2038 ){
13684     x.Y = 2000;
13685     x.M = 1;
13686     x.D = 1;
13687     x.h = 0;
13688     x.m = 0;
13689     x.s = 0.0;
13690   } else {
13691     int s = (int)(x.s + 0.5);
13692     x.s = s;
13693   }
13694   x.tz = 0;
13695   x.validJD = 0;
13696   computeJD(&x);
13697   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
13698   if( osLocaltime(&t, &sLocal) ){
13699     sqlite3_result_error(pCtx, "local time unavailable", -1);
13700     *pRc = SQLITE_ERROR;
13701     return 0;
13702   }
13703   y.Y = sLocal.tm_year + 1900;
13704   y.M = sLocal.tm_mon + 1;
13705   y.D = sLocal.tm_mday;
13706   y.h = sLocal.tm_hour;
13707   y.m = sLocal.tm_min;
13708   y.s = sLocal.tm_sec;
13709   y.validYMD = 1;
13710   y.validHMS = 1;
13711   y.validJD = 0;
13712   y.validTZ = 0;
13713   computeJD(&y);
13714   *pRc = SQLITE_OK;
13715   return y.iJD - x.iJD;
13716 }
13717 #endif /* SQLITE_OMIT_LOCALTIME */
13718 
13719 /*
13720 ** Process a modifier to a date-time stamp.  The modifiers are
13721 ** as follows:
13722 **
13723 **     NNN days
13724 **     NNN hours
13725 **     NNN minutes
13726 **     NNN.NNNN seconds
13727 **     NNN months
13728 **     NNN years
13729 **     start of month
13730 **     start of year
13731 **     start of week
13732 **     start of day
13733 **     weekday N
13734 **     unixepoch
13735 **     localtime
13736 **     utc
13737 **
13738 ** Return 0 on success and 1 if there is any kind of error. If the error
13739 ** is in a system call (i.e. localtime()), then an error message is written
13740 ** to context pCtx. If the error is an unrecognized modifier, no error is
13741 ** written to pCtx.
13742 */
parseModifier(sqlite3_context * pCtx,const char * zMod,DateTime * p)13743 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
13744   int rc = 1;
13745   int n;
13746   double r;
13747   char *z, zBuf[30];
13748   z = zBuf;
13749   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
13750     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
13751   }
13752   z[n] = 0;
13753   switch( z[0] ){
13754 #ifndef SQLITE_OMIT_LOCALTIME
13755     case 'l': {
13756       /*    localtime
13757       **
13758       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
13759       ** show local time.
13760       */
13761       if( strcmp(z, "localtime")==0 ){
13762         computeJD(p);
13763         p->iJD += localtimeOffset(p, pCtx, &rc);
13764         clearYMD_HMS_TZ(p);
13765       }
13766       break;
13767     }
13768 #endif
13769     case 'u': {
13770       /*
13771       **    unixepoch
13772       **
13773       ** Treat the current value of p->iJD as the number of
13774       ** seconds since 1970.  Convert to a real julian day number.
13775       */
13776       if( strcmp(z, "unixepoch")==0 && p->validJD ){
13777         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
13778         clearYMD_HMS_TZ(p);
13779         rc = 0;
13780       }
13781 #ifndef SQLITE_OMIT_LOCALTIME
13782       else if( strcmp(z, "utc")==0 ){
13783         sqlite3_int64 c1;
13784         computeJD(p);
13785         c1 = localtimeOffset(p, pCtx, &rc);
13786         if( rc==SQLITE_OK ){
13787           p->iJD -= c1;
13788           clearYMD_HMS_TZ(p);
13789           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
13790         }
13791       }
13792 #endif
13793       break;
13794     }
13795     case 'w': {
13796       /*
13797       **    weekday N
13798       **
13799       ** Move the date to the same time on the next occurrence of
13800       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
13801       ** date is already on the appropriate weekday, this is a no-op.
13802       */
13803       if( strncmp(z, "weekday ", 8)==0
13804                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
13805                && (n=(int)r)==r && n>=0 && r<7 ){
13806         sqlite3_int64 Z;
13807         computeYMD_HMS(p);
13808         p->validTZ = 0;
13809         p->validJD = 0;
13810         computeJD(p);
13811         Z = ((p->iJD + 129600000)/86400000) % 7;
13812         if( Z>n ) Z -= 7;
13813         p->iJD += (n - Z)*86400000;
13814         clearYMD_HMS_TZ(p);
13815         rc = 0;
13816       }
13817       break;
13818     }
13819     case 's': {
13820       /*
13821       **    start of TTTTT
13822       **
13823       ** Move the date backwards to the beginning of the current day,
13824       ** or month or year.
13825       */
13826       if( strncmp(z, "start of ", 9)!=0 ) break;
13827       z += 9;
13828       computeYMD(p);
13829       p->validHMS = 1;
13830       p->h = p->m = 0;
13831       p->s = 0.0;
13832       p->validTZ = 0;
13833       p->validJD = 0;
13834       if( strcmp(z,"month")==0 ){
13835         p->D = 1;
13836         rc = 0;
13837       }else if( strcmp(z,"year")==0 ){
13838         computeYMD(p);
13839         p->M = 1;
13840         p->D = 1;
13841         rc = 0;
13842       }else if( strcmp(z,"day")==0 ){
13843         rc = 0;
13844       }
13845       break;
13846     }
13847     case '+':
13848     case '-':
13849     case '0':
13850     case '1':
13851     case '2':
13852     case '3':
13853     case '4':
13854     case '5':
13855     case '6':
13856     case '7':
13857     case '8':
13858     case '9': {
13859       double rRounder;
13860       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
13861       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
13862         rc = 1;
13863         break;
13864       }
13865       if( z[n]==':' ){
13866         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
13867         ** specified number of hours, minutes, seconds, and fractional seconds
13868         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
13869         ** omitted.
13870         */
13871         const char *z2 = z;
13872         DateTime tx;
13873         sqlite3_int64 day;
13874         if( !sqlite3Isdigit(*z2) ) z2++;
13875         memset(&tx, 0, sizeof(tx));
13876         if( parseHhMmSs(z2, &tx) ) break;
13877         computeJD(&tx);
13878         tx.iJD -= 43200000;
13879         day = tx.iJD/86400000;
13880         tx.iJD -= day*86400000;
13881         if( z[0]=='-' ) tx.iJD = -tx.iJD;
13882         computeJD(p);
13883         clearYMD_HMS_TZ(p);
13884         p->iJD += tx.iJD;
13885         rc = 0;
13886         break;
13887       }
13888       z += n;
13889       while( sqlite3Isspace(*z) ) z++;
13890       n = sqlite3Strlen30(z);
13891       if( n>10 || n<3 ) break;
13892       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
13893       computeJD(p);
13894       rc = 0;
13895       rRounder = r<0 ? -0.5 : +0.5;
13896       if( n==3 && strcmp(z,"day")==0 ){
13897         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
13898       }else if( n==4 && strcmp(z,"hour")==0 ){
13899         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
13900       }else if( n==6 && strcmp(z,"minute")==0 ){
13901         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
13902       }else if( n==6 && strcmp(z,"second")==0 ){
13903         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
13904       }else if( n==5 && strcmp(z,"month")==0 ){
13905         int x, y;
13906         computeYMD_HMS(p);
13907         p->M += (int)r;
13908         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
13909         p->Y += x;
13910         p->M -= x*12;
13911         p->validJD = 0;
13912         computeJD(p);
13913         y = (int)r;
13914         if( y!=r ){
13915           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
13916         }
13917       }else if( n==4 && strcmp(z,"year")==0 ){
13918         int y = (int)r;
13919         computeYMD_HMS(p);
13920         p->Y += y;
13921         p->validJD = 0;
13922         computeJD(p);
13923         if( y!=r ){
13924           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
13925         }
13926       }else{
13927         rc = 1;
13928       }
13929       clearYMD_HMS_TZ(p);
13930       break;
13931     }
13932     default: {
13933       break;
13934     }
13935   }
13936   return rc;
13937 }
13938 
13939 /*
13940 ** Process time function arguments.  argv[0] is a date-time stamp.
13941 ** argv[1] and following are modifiers.  Parse them all and write
13942 ** the resulting time into the DateTime structure p.  Return 0
13943 ** on success and 1 if there are any errors.
13944 **
13945 ** If there are zero parameters (if even argv[0] is undefined)
13946 ** then assume a default value of "now" for argv[0].
13947 */
isDate(sqlite3_context * context,int argc,sqlite3_value ** argv,DateTime * p)13948 static int isDate(
13949   sqlite3_context *context,
13950   int argc,
13951   sqlite3_value **argv,
13952   DateTime *p
13953 ){
13954   int i;
13955   const unsigned char *z;
13956   int eType;
13957   memset(p, 0, sizeof(*p));
13958   if( argc==0 ){
13959     setDateTimeToCurrent(context, p);
13960   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
13961                    || eType==SQLITE_INTEGER ){
13962     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
13963     p->validJD = 1;
13964   }else{
13965     z = sqlite3_value_text(argv[0]);
13966     if( !z || parseDateOrTime(context, (char*)z, p) ){
13967       return 1;
13968     }
13969   }
13970   for(i=1; i<argc; i++){
13971     z = sqlite3_value_text(argv[i]);
13972     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
13973   }
13974   return 0;
13975 }
13976 
13977 
13978 /*
13979 ** The following routines implement the various date and time functions
13980 ** of SQLite.
13981 */
13982 
13983 /*
13984 **    julianday( TIMESTRING, MOD, MOD, ...)
13985 **
13986 ** Return the julian day number of the date specified in the arguments
13987 */
juliandayFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)13988 static void juliandayFunc(
13989   sqlite3_context *context,
13990   int argc,
13991   sqlite3_value **argv
13992 ){
13993   DateTime x;
13994   if( isDate(context, argc, argv, &x)==0 ){
13995     computeJD(&x);
13996     sqlite3_result_double(context, x.iJD/86400000.0);
13997   }
13998 }
13999 
14000 /*
14001 **    datetime( TIMESTRING, MOD, MOD, ...)
14002 **
14003 ** Return YYYY-MM-DD HH:MM:SS
14004 */
datetimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)14005 static void datetimeFunc(
14006   sqlite3_context *context,
14007   int argc,
14008   sqlite3_value **argv
14009 ){
14010   DateTime x;
14011   if( isDate(context, argc, argv, &x)==0 ){
14012     char zBuf[100];
14013     computeYMD_HMS(&x);
14014     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14015                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14016     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14017   }
14018 }
14019 
14020 /*
14021 **    time( TIMESTRING, MOD, MOD, ...)
14022 **
14023 ** Return HH:MM:SS
14024 */
timeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)14025 static void timeFunc(
14026   sqlite3_context *context,
14027   int argc,
14028   sqlite3_value **argv
14029 ){
14030   DateTime x;
14031   if( isDate(context, argc, argv, &x)==0 ){
14032     char zBuf[100];
14033     computeHMS(&x);
14034     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14035     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14036   }
14037 }
14038 
14039 /*
14040 **    date( TIMESTRING, MOD, MOD, ...)
14041 **
14042 ** Return YYYY-MM-DD
14043 */
dateFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)14044 static void dateFunc(
14045   sqlite3_context *context,
14046   int argc,
14047   sqlite3_value **argv
14048 ){
14049   DateTime x;
14050   if( isDate(context, argc, argv, &x)==0 ){
14051     char zBuf[100];
14052     computeYMD(&x);
14053     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14054     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14055   }
14056 }
14057 
14058 /*
14059 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14060 **
14061 ** Return a string described by FORMAT.  Conversions as follows:
14062 **
14063 **   %d  day of month
14064 **   %f  ** fractional seconds  SS.SSS
14065 **   %H  hour 00-24
14066 **   %j  day of year 000-366
14067 **   %J  ** Julian day number
14068 **   %m  month 01-12
14069 **   %M  minute 00-59
14070 **   %s  seconds since 1970-01-01
14071 **   %S  seconds 00-59
14072 **   %w  day of week 0-6  sunday==0
14073 **   %W  week of year 00-53
14074 **   %Y  year 0000-9999
14075 **   %%  %
14076 */
strftimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)14077 static void strftimeFunc(
14078   sqlite3_context *context,
14079   int argc,
14080   sqlite3_value **argv
14081 ){
14082   DateTime x;
14083   u64 n;
14084   size_t i,j;
14085   char *z;
14086   sqlite3 *db;
14087   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14088   char zBuf[100];
14089   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14090   db = sqlite3_context_db_handle(context);
14091   for(i=0, n=1; zFmt[i]; i++, n++){
14092     if( zFmt[i]=='%' ){
14093       switch( zFmt[i+1] ){
14094         case 'd':
14095         case 'H':
14096         case 'm':
14097         case 'M':
14098         case 'S':
14099         case 'W':
14100           n++;
14101           /* fall thru */
14102         case 'w':
14103         case '%':
14104           break;
14105         case 'f':
14106           n += 8;
14107           break;
14108         case 'j':
14109           n += 3;
14110           break;
14111         case 'Y':
14112           n += 8;
14113           break;
14114         case 's':
14115         case 'J':
14116           n += 50;
14117           break;
14118         default:
14119           return;  /* ERROR.  return a NULL */
14120       }
14121       i++;
14122     }
14123   }
14124   testcase( n==sizeof(zBuf)-1 );
14125   testcase( n==sizeof(zBuf) );
14126   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14127   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14128   if( n<sizeof(zBuf) ){
14129     z = zBuf;
14130   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14131     sqlite3_result_error_toobig(context);
14132     return;
14133   }else{
14134     z = sqlite3DbMallocRaw(db, (int)n);
14135     if( z==0 ){
14136       sqlite3_result_error_nomem(context);
14137       return;
14138     }
14139   }
14140   computeJD(&x);
14141   computeYMD_HMS(&x);
14142   for(i=j=0; zFmt[i]; i++){
14143     if( zFmt[i]!='%' ){
14144       z[j++] = zFmt[i];
14145     }else{
14146       i++;
14147       switch( zFmt[i] ){
14148         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14149         case 'f': {
14150           double s = x.s;
14151           if( s>59.999 ) s = 59.999;
14152           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14153           j += sqlite3Strlen30(&z[j]);
14154           break;
14155         }
14156         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14157         case 'W': /* Fall thru */
14158         case 'j': {
14159           int nDay;             /* Number of days since 1st day of year */
14160           DateTime y = x;
14161           y.validJD = 0;
14162           y.M = 1;
14163           y.D = 1;
14164           computeJD(&y);
14165           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14166           if( zFmt[i]=='W' ){
14167             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14168             wd = (int)(((x.iJD+43200000)/86400000)%7);
14169             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14170             j += 2;
14171           }else{
14172             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14173             j += 3;
14174           }
14175           break;
14176         }
14177         case 'J': {
14178           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14179           j+=sqlite3Strlen30(&z[j]);
14180           break;
14181         }
14182         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14183         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14184         case 's': {
14185           sqlite3_snprintf(30,&z[j],"%lld",
14186                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14187           j += sqlite3Strlen30(&z[j]);
14188           break;
14189         }
14190         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14191         case 'w': {
14192           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14193           break;
14194         }
14195         case 'Y': {
14196           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14197           break;
14198         }
14199         default:   z[j++] = '%'; break;
14200       }
14201     }
14202   }
14203   z[j] = 0;
14204   sqlite3_result_text(context, z, -1,
14205                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14206 }
14207 
14208 /*
14209 ** current_time()
14210 **
14211 ** This function returns the same value as time('now').
14212 */
ctimeFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)14213 static void ctimeFunc(
14214   sqlite3_context *context,
14215   int NotUsed,
14216   sqlite3_value **NotUsed2
14217 ){
14218   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14219   timeFunc(context, 0, 0);
14220 }
14221 
14222 /*
14223 ** current_date()
14224 **
14225 ** This function returns the same value as date('now').
14226 */
cdateFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)14227 static void cdateFunc(
14228   sqlite3_context *context,
14229   int NotUsed,
14230   sqlite3_value **NotUsed2
14231 ){
14232   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14233   dateFunc(context, 0, 0);
14234 }
14235 
14236 /*
14237 ** current_timestamp()
14238 **
14239 ** This function returns the same value as datetime('now').
14240 */
ctimestampFunc(sqlite3_context * context,int NotUsed,sqlite3_value ** NotUsed2)14241 static void ctimestampFunc(
14242   sqlite3_context *context,
14243   int NotUsed,
14244   sqlite3_value **NotUsed2
14245 ){
14246   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14247   datetimeFunc(context, 0, 0);
14248 }
14249 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14250 
14251 #ifdef SQLITE_OMIT_DATETIME_FUNCS
14252 /*
14253 ** If the library is compiled to omit the full-scale date and time
14254 ** handling (to get a smaller binary), the following minimal version
14255 ** of the functions current_time(), current_date() and current_timestamp()
14256 ** are included instead. This is to support column declarations that
14257 ** include "DEFAULT CURRENT_TIME" etc.
14258 **
14259 ** This function uses the C-library functions time(), gmtime()
14260 ** and strftime(). The format string to pass to strftime() is supplied
14261 ** as the user-data for the function.
14262 */
currentTimeFunc(sqlite3_context * context,int argc,sqlite3_value ** argv)14263 static void currentTimeFunc(
14264   sqlite3_context *context,
14265   int argc,
14266   sqlite3_value **argv
14267 ){
14268   time_t t;
14269   char *zFormat = (char *)sqlite3_user_data(context);
14270   sqlite3 *db;
14271   sqlite3_int64 iT;
14272   char zBuf[20];
14273 
14274   UNUSED_PARAMETER(argc);
14275   UNUSED_PARAMETER(argv);
14276 
14277   db = sqlite3_context_db_handle(context);
14278   sqlite3OsCurrentTimeInt64(db->pVfs, &iT);
14279   t = iT/1000 - 10000*(sqlite3_int64)21086676;
14280 #ifdef HAVE_GMTIME_R
14281   {
14282     struct tm sNow;
14283     gmtime_r(&t, &sNow);
14284     strftime(zBuf, 20, zFormat, &sNow);
14285   }
14286 #else
14287   {
14288     struct tm *pTm;
14289     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14290     pTm = gmtime(&t);
14291     strftime(zBuf, 20, zFormat, pTm);
14292     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14293   }
14294 #endif
14295 
14296   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14297 }
14298 #endif
14299 
14300 /*
14301 ** This function registered all of the above C functions as SQL
14302 ** functions.  This should be the only routine in this file with
14303 ** external linkage.
14304 */
sqlite3RegisterDateTimeFunctions(void)14305 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14306   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14307 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14308     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14309     FUNCTION(date,             -1, 0, 0, dateFunc      ),
14310     FUNCTION(time,             -1, 0, 0, timeFunc      ),
14311     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14312     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14313     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14314     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14315     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14316 #else
14317     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14318     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14319     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14320 #endif
14321   };
14322   int i;
14323   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14324   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14325 
14326   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14327     sqlite3FuncDefInsert(pHash, &aFunc[i]);
14328   }
14329 }
14330 
14331 /************** End of date.c ************************************************/
14332 /************** Begin file os.c **********************************************/
14333 /*
14334 ** 2005 November 29
14335 **
14336 ** The author disclaims copyright to this source code.  In place of
14337 ** a legal notice, here is a blessing:
14338 **
14339 **    May you do good and not evil.
14340 **    May you find forgiveness for yourself and forgive others.
14341 **    May you share freely, never taking more than you give.
14342 **
14343 ******************************************************************************
14344 **
14345 ** This file contains OS interface code that is common to all
14346 ** architectures.
14347 */
14348 #define _SQLITE_OS_C_ 1
14349 #undef _SQLITE_OS_C_
14350 
14351 /*
14352 ** The default SQLite sqlite3_vfs implementations do not allocate
14353 ** memory (actually, os_unix.c allocates a small amount of memory
14354 ** from within OsOpen()), but some third-party implementations may.
14355 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14356 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14357 **
14358 ** The following functions are instrumented for malloc() failure
14359 ** testing:
14360 **
14361 **     sqlite3OsOpen()
14362 **     sqlite3OsRead()
14363 **     sqlite3OsWrite()
14364 **     sqlite3OsSync()
14365 **     sqlite3OsLock()
14366 **
14367 */
14368 #if defined(SQLITE_TEST)
14369 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14370   #define DO_OS_MALLOC_TEST(x)                                       \
14371   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14372     void *pTstAlloc = sqlite3Malloc(10);                             \
14373     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14374     sqlite3_free(pTstAlloc);                                         \
14375   }
14376 #else
14377   #define DO_OS_MALLOC_TEST(x)
14378 #endif
14379 
14380 /*
14381 ** The following routines are convenience wrappers around methods
14382 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14383 ** of this would be completely automatic if SQLite were coded using
14384 ** C++ instead of plain old C.
14385 */
sqlite3OsClose(sqlite3_file * pId)14386 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14387   int rc = SQLITE_OK;
14388   if( pId->pMethods ){
14389     rc = pId->pMethods->xClose(pId);
14390     pId->pMethods = 0;
14391   }
14392   return rc;
14393 }
sqlite3OsRead(sqlite3_file * id,void * pBuf,int amt,i64 offset)14394 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14395   DO_OS_MALLOC_TEST(id);
14396   return id->pMethods->xRead(id, pBuf, amt, offset);
14397 }
sqlite3OsWrite(sqlite3_file * id,const void * pBuf,int amt,i64 offset)14398 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14399   DO_OS_MALLOC_TEST(id);
14400   return id->pMethods->xWrite(id, pBuf, amt, offset);
14401 }
sqlite3OsTruncate(sqlite3_file * id,i64 size)14402 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14403   return id->pMethods->xTruncate(id, size);
14404 }
sqlite3OsSync(sqlite3_file * id,int flags)14405 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14406   DO_OS_MALLOC_TEST(id);
14407   return id->pMethods->xSync(id, flags);
14408 }
sqlite3OsFileSize(sqlite3_file * id,i64 * pSize)14409 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14410   DO_OS_MALLOC_TEST(id);
14411   return id->pMethods->xFileSize(id, pSize);
14412 }
sqlite3OsLock(sqlite3_file * id,int lockType)14413 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14414   DO_OS_MALLOC_TEST(id);
14415   return id->pMethods->xLock(id, lockType);
14416 }
sqlite3OsUnlock(sqlite3_file * id,int lockType)14417 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14418   return id->pMethods->xUnlock(id, lockType);
14419 }
sqlite3OsCheckReservedLock(sqlite3_file * id,int * pResOut)14420 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14421   DO_OS_MALLOC_TEST(id);
14422   return id->pMethods->xCheckReservedLock(id, pResOut);
14423 }
sqlite3OsFileControl(sqlite3_file * id,int op,void * pArg)14424 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14425   return id->pMethods->xFileControl(id, op, pArg);
14426 }
sqlite3OsSectorSize(sqlite3_file * id)14427 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14428   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14429   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14430 }
sqlite3OsDeviceCharacteristics(sqlite3_file * id)14431 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14432   return id->pMethods->xDeviceCharacteristics(id);
14433 }
sqlite3OsShmLock(sqlite3_file * id,int offset,int n,int flags)14434 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14435   return id->pMethods->xShmLock(id, offset, n, flags);
14436 }
sqlite3OsShmBarrier(sqlite3_file * id)14437 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14438   id->pMethods->xShmBarrier(id);
14439 }
sqlite3OsShmUnmap(sqlite3_file * id,int deleteFlag)14440 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14441   return id->pMethods->xShmUnmap(id, deleteFlag);
14442 }
sqlite3OsShmMap(sqlite3_file * id,int iPage,int pgsz,int bExtend,void volatile ** pp)14443 SQLITE_PRIVATE int sqlite3OsShmMap(
14444   sqlite3_file *id,               /* Database file handle */
14445   int iPage,
14446   int pgsz,
14447   int bExtend,                    /* True to extend file if necessary */
14448   void volatile **pp              /* OUT: Pointer to mapping */
14449 ){
14450   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14451 }
14452 
14453 /*
14454 ** The next group of routines are convenience wrappers around the
14455 ** VFS methods.
14456 */
sqlite3OsOpen(sqlite3_vfs * pVfs,const char * zPath,sqlite3_file * pFile,int flags,int * pFlagsOut)14457 SQLITE_PRIVATE int sqlite3OsOpen(
14458   sqlite3_vfs *pVfs,
14459   const char *zPath,
14460   sqlite3_file *pFile,
14461   int flags,
14462   int *pFlagsOut
14463 ){
14464   int rc;
14465   DO_OS_MALLOC_TEST(0);
14466   /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14467   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14468   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14469   ** reaching the VFS. */
14470   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14471   assert( rc==SQLITE_OK || pFile->pMethods==0 );
14472   return rc;
14473 }
sqlite3OsDelete(sqlite3_vfs * pVfs,const char * zPath,int dirSync)14474 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14475   return pVfs->xDelete(pVfs, zPath, dirSync);
14476 }
sqlite3OsAccess(sqlite3_vfs * pVfs,const char * zPath,int flags,int * pResOut)14477 SQLITE_PRIVATE int sqlite3OsAccess(
14478   sqlite3_vfs *pVfs,
14479   const char *zPath,
14480   int flags,
14481   int *pResOut
14482 ){
14483   DO_OS_MALLOC_TEST(0);
14484   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14485 }
sqlite3OsFullPathname(sqlite3_vfs * pVfs,const char * zPath,int nPathOut,char * zPathOut)14486 SQLITE_PRIVATE int sqlite3OsFullPathname(
14487   sqlite3_vfs *pVfs,
14488   const char *zPath,
14489   int nPathOut,
14490   char *zPathOut
14491 ){
14492   zPathOut[0] = 0;
14493   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14494 }
14495 #ifndef SQLITE_OMIT_LOAD_EXTENSION
sqlite3OsDlOpen(sqlite3_vfs * pVfs,const char * zPath)14496 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14497   return pVfs->xDlOpen(pVfs, zPath);
14498 }
sqlite3OsDlError(sqlite3_vfs * pVfs,int nByte,char * zBufOut)14499 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14500   pVfs->xDlError(pVfs, nByte, zBufOut);
14501 }
sqlite3OsDlSym(sqlite3_vfs * pVfs,void * pHdle,const char * zSym)14502 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14503   return pVfs->xDlSym(pVfs, pHdle, zSym);
14504 }
sqlite3OsDlClose(sqlite3_vfs * pVfs,void * pHandle)14505 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14506   pVfs->xDlClose(pVfs, pHandle);
14507 }
14508 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
sqlite3OsRandomness(sqlite3_vfs * pVfs,int nByte,char * zBufOut)14509 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14510   return pVfs->xRandomness(pVfs, nByte, zBufOut);
14511 }
sqlite3OsSleep(sqlite3_vfs * pVfs,int nMicro)14512 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14513   return pVfs->xSleep(pVfs, nMicro);
14514 }
sqlite3OsCurrentTimeInt64(sqlite3_vfs * pVfs,sqlite3_int64 * pTimeOut)14515 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14516   int rc;
14517   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14518   ** method to get the current date and time if that method is available
14519   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14520   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14521   ** unavailable.
14522   */
14523   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14524     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14525   }else{
14526     double r;
14527     rc = pVfs->xCurrentTime(pVfs, &r);
14528     *pTimeOut = (sqlite3_int64)(r*86400000.0);
14529   }
14530   return rc;
14531 }
14532 
sqlite3OsOpenMalloc(sqlite3_vfs * pVfs,const char * zFile,sqlite3_file ** ppFile,int flags,int * pOutFlags)14533 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14534   sqlite3_vfs *pVfs,
14535   const char *zFile,
14536   sqlite3_file **ppFile,
14537   int flags,
14538   int *pOutFlags
14539 ){
14540   int rc = SQLITE_NOMEM;
14541   sqlite3_file *pFile;
14542   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
14543   if( pFile ){
14544     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14545     if( rc!=SQLITE_OK ){
14546       sqlite3_free(pFile);
14547     }else{
14548       *ppFile = pFile;
14549     }
14550   }
14551   return rc;
14552 }
sqlite3OsCloseFree(sqlite3_file * pFile)14553 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14554   int rc = SQLITE_OK;
14555   assert( pFile );
14556   rc = sqlite3OsClose(pFile);
14557   sqlite3_free(pFile);
14558   return rc;
14559 }
14560 
14561 /*
14562 ** This function is a wrapper around the OS specific implementation of
14563 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
14564 ** ability to simulate a malloc failure, so that the handling of an
14565 ** error in sqlite3_os_init() by the upper layers can be tested.
14566 */
sqlite3OsInit(void)14567 SQLITE_PRIVATE int sqlite3OsInit(void){
14568   void *p = sqlite3_malloc(10);
14569   if( p==0 ) return SQLITE_NOMEM;
14570   sqlite3_free(p);
14571   return sqlite3_os_init();
14572 }
14573 
14574 /*
14575 ** The list of all registered VFS implementations.
14576 */
14577 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14578 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14579 
14580 /*
14581 ** Locate a VFS by name.  If no name is given, simply return the
14582 ** first VFS on the list.
14583 */
sqlite3_vfs_find(const char * zVfs)14584 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14585   sqlite3_vfs *pVfs = 0;
14586 #if SQLITE_THREADSAFE
14587   sqlite3_mutex *mutex;
14588 #endif
14589 #ifndef SQLITE_OMIT_AUTOINIT
14590   int rc = sqlite3_initialize();
14591   if( rc ) return 0;
14592 #endif
14593 #if SQLITE_THREADSAFE
14594   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14595 #endif
14596   sqlite3_mutex_enter(mutex);
14597   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14598     if( zVfs==0 ) break;
14599     if( strcmp(zVfs, pVfs->zName)==0 ) break;
14600   }
14601   sqlite3_mutex_leave(mutex);
14602   return pVfs;
14603 }
14604 
14605 /*
14606 ** Unlink a VFS from the linked list
14607 */
vfsUnlink(sqlite3_vfs * pVfs)14608 static void vfsUnlink(sqlite3_vfs *pVfs){
14609   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14610   if( pVfs==0 ){
14611     /* No-op */
14612   }else if( vfsList==pVfs ){
14613     vfsList = pVfs->pNext;
14614   }else if( vfsList ){
14615     sqlite3_vfs *p = vfsList;
14616     while( p->pNext && p->pNext!=pVfs ){
14617       p = p->pNext;
14618     }
14619     if( p->pNext==pVfs ){
14620       p->pNext = pVfs->pNext;
14621     }
14622   }
14623 }
14624 
14625 /*
14626 ** Register a VFS with the system.  It is harmless to register the same
14627 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
14628 ** true.
14629 */
sqlite3_vfs_register(sqlite3_vfs * pVfs,int makeDflt)14630 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14631   sqlite3_mutex *mutex = 0;
14632 #ifndef SQLITE_OMIT_AUTOINIT
14633   int rc = sqlite3_initialize();
14634   if( rc ) return rc;
14635 #endif
14636   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14637   sqlite3_mutex_enter(mutex);
14638   vfsUnlink(pVfs);
14639   if( makeDflt || vfsList==0 ){
14640     pVfs->pNext = vfsList;
14641     vfsList = pVfs;
14642   }else{
14643     pVfs->pNext = vfsList->pNext;
14644     vfsList->pNext = pVfs;
14645   }
14646   assert(vfsList);
14647   sqlite3_mutex_leave(mutex);
14648   return SQLITE_OK;
14649 }
14650 
14651 /*
14652 ** Unregister a VFS so that it is no longer accessible.
14653 */
sqlite3_vfs_unregister(sqlite3_vfs * pVfs)14654 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
14655 #if SQLITE_THREADSAFE
14656   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14657 #endif
14658   sqlite3_mutex_enter(mutex);
14659   vfsUnlink(pVfs);
14660   sqlite3_mutex_leave(mutex);
14661   return SQLITE_OK;
14662 }
14663 
14664 /************** End of os.c **************************************************/
14665 /************** Begin file fault.c *******************************************/
14666 /*
14667 ** 2008 Jan 22
14668 **
14669 ** The author disclaims copyright to this source code.  In place of
14670 ** a legal notice, here is a blessing:
14671 **
14672 **    May you do good and not evil.
14673 **    May you find forgiveness for yourself and forgive others.
14674 **    May you share freely, never taking more than you give.
14675 **
14676 *************************************************************************
14677 **
14678 ** This file contains code to support the concept of "benign"
14679 ** malloc failures (when the xMalloc() or xRealloc() method of the
14680 ** sqlite3_mem_methods structure fails to allocate a block of memory
14681 ** and returns 0).
14682 **
14683 ** Most malloc failures are non-benign. After they occur, SQLite
14684 ** abandons the current operation and returns an error code (usually
14685 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
14686 ** fatal. For example, if a malloc fails while resizing a hash table, this
14687 ** is completely recoverable simply by not carrying out the resize. The
14688 ** hash table will continue to function normally.  So a malloc failure
14689 ** during a hash table resize is a benign fault.
14690 */
14691 
14692 
14693 #ifndef SQLITE_OMIT_BUILTIN_TEST
14694 
14695 /*
14696 ** Global variables.
14697 */
14698 typedef struct BenignMallocHooks BenignMallocHooks;
14699 static SQLITE_WSD struct BenignMallocHooks {
14700   void (*xBenignBegin)(void);
14701   void (*xBenignEnd)(void);
14702 } sqlite3Hooks = { 0, 0 };
14703 
14704 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
14705 ** structure.  If writable static data is unsupported on the target,
14706 ** we have to locate the state vector at run-time.  In the more common
14707 ** case where writable static data is supported, wsdHooks can refer directly
14708 ** to the "sqlite3Hooks" state vector declared above.
14709 */
14710 #ifdef SQLITE_OMIT_WSD
14711 # define wsdHooksInit \
14712   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
14713 # define wsdHooks x[0]
14714 #else
14715 # define wsdHooksInit
14716 # define wsdHooks sqlite3Hooks
14717 #endif
14718 
14719 
14720 /*
14721 ** Register hooks to call when sqlite3BeginBenignMalloc() and
14722 ** sqlite3EndBenignMalloc() are called, respectively.
14723 */
sqlite3BenignMallocHooks(void (* xBenignBegin)(void),void (* xBenignEnd)(void))14724 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
14725   void (*xBenignBegin)(void),
14726   void (*xBenignEnd)(void)
14727 ){
14728   wsdHooksInit;
14729   wsdHooks.xBenignBegin = xBenignBegin;
14730   wsdHooks.xBenignEnd = xBenignEnd;
14731 }
14732 
14733 /*
14734 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
14735 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
14736 ** indicates that subsequent malloc failures are non-benign.
14737 */
sqlite3BeginBenignMalloc(void)14738 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
14739   wsdHooksInit;
14740   if( wsdHooks.xBenignBegin ){
14741     wsdHooks.xBenignBegin();
14742   }
14743 }
sqlite3EndBenignMalloc(void)14744 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
14745   wsdHooksInit;
14746   if( wsdHooks.xBenignEnd ){
14747     wsdHooks.xBenignEnd();
14748   }
14749 }
14750 
14751 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
14752 
14753 /************** End of fault.c ***********************************************/
14754 /************** Begin file mem0.c ********************************************/
14755 /*
14756 ** 2008 October 28
14757 **
14758 ** The author disclaims copyright to this source code.  In place of
14759 ** a legal notice, here is a blessing:
14760 **
14761 **    May you do good and not evil.
14762 **    May you find forgiveness for yourself and forgive others.
14763 **    May you share freely, never taking more than you give.
14764 **
14765 *************************************************************************
14766 **
14767 ** This file contains a no-op memory allocation drivers for use when
14768 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
14769 ** here always fail.  SQLite will not operate with these drivers.  These
14770 ** are merely placeholders.  Real drivers must be substituted using
14771 ** sqlite3_config() before SQLite will operate.
14772 */
14773 
14774 /*
14775 ** This version of the memory allocator is the default.  It is
14776 ** used when no other memory allocator is specified using compile-time
14777 ** macros.
14778 */
14779 #ifdef SQLITE_ZERO_MALLOC
14780 
14781 /*
14782 ** No-op versions of all memory allocation routines
14783 */
sqlite3MemMalloc(int nByte)14784 static void *sqlite3MemMalloc(int nByte){ return 0; }
sqlite3MemFree(void * pPrior)14785 static void sqlite3MemFree(void *pPrior){ return; }
sqlite3MemRealloc(void * pPrior,int nByte)14786 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
sqlite3MemSize(void * pPrior)14787 static int sqlite3MemSize(void *pPrior){ return 0; }
sqlite3MemRoundup(int n)14788 static int sqlite3MemRoundup(int n){ return n; }
sqlite3MemInit(void * NotUsed)14789 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
sqlite3MemShutdown(void * NotUsed)14790 static void sqlite3MemShutdown(void *NotUsed){ return; }
14791 
14792 /*
14793 ** This routine is the only routine in this file with external linkage.
14794 **
14795 ** Populate the low-level memory allocation function pointers in
14796 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14797 */
sqlite3MemSetDefault(void)14798 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14799   static const sqlite3_mem_methods defaultMethods = {
14800      sqlite3MemMalloc,
14801      sqlite3MemFree,
14802      sqlite3MemRealloc,
14803      sqlite3MemSize,
14804      sqlite3MemRoundup,
14805      sqlite3MemInit,
14806      sqlite3MemShutdown,
14807      0
14808   };
14809   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14810 }
14811 
14812 #endif /* SQLITE_ZERO_MALLOC */
14813 
14814 /************** End of mem0.c ************************************************/
14815 /************** Begin file mem1.c ********************************************/
14816 /*
14817 ** 2007 August 14
14818 **
14819 ** The author disclaims copyright to this source code.  In place of
14820 ** a legal notice, here is a blessing:
14821 **
14822 **    May you do good and not evil.
14823 **    May you find forgiveness for yourself and forgive others.
14824 **    May you share freely, never taking more than you give.
14825 **
14826 *************************************************************************
14827 **
14828 ** This file contains low-level memory allocation drivers for when
14829 ** SQLite will use the standard C-library malloc/realloc/free interface
14830 ** to obtain the memory it needs.
14831 **
14832 ** This file contains implementations of the low-level memory allocation
14833 ** routines specified in the sqlite3_mem_methods object.
14834 */
14835 
14836 /*
14837 ** This version of the memory allocator is the default.  It is
14838 ** used when no other memory allocator is specified using compile-time
14839 ** macros.
14840 */
14841 #ifdef SQLITE_SYSTEM_MALLOC
14842 
14843 /*
14844 ** Like malloc(), but remember the size of the allocation
14845 ** so that we can find it later using sqlite3MemSize().
14846 **
14847 ** For this low-level routine, we are guaranteed that nByte>0 because
14848 ** cases of nByte<=0 will be intercepted and dealt with by higher level
14849 ** routines.
14850 */
sqlite3MemMalloc(int nByte)14851 static void *sqlite3MemMalloc(int nByte){
14852   sqlite3_int64 *p;
14853   assert( nByte>0 );
14854   nByte = ROUND8(nByte);
14855   p = malloc( nByte+8 );
14856   if( p ){
14857     p[0] = nByte;
14858     p++;
14859   }else{
14860     testcase( sqlite3GlobalConfig.xLog!=0 );
14861     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
14862   }
14863   return (void *)p;
14864 }
14865 
14866 /*
14867 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
14868 ** or sqlite3MemRealloc().
14869 **
14870 ** For this low-level routine, we already know that pPrior!=0 since
14871 ** cases where pPrior==0 will have been intecepted and dealt with
14872 ** by higher-level routines.
14873 */
sqlite3MemFree(void * pPrior)14874 static void sqlite3MemFree(void *pPrior){
14875   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14876   assert( pPrior!=0 );
14877   p--;
14878   free(p);
14879 }
14880 
14881 /*
14882 ** Report the allocated size of a prior return from xMalloc()
14883 ** or xRealloc().
14884 */
sqlite3MemSize(void * pPrior)14885 static int sqlite3MemSize(void *pPrior){
14886   sqlite3_int64 *p;
14887   if( pPrior==0 ) return 0;
14888   p = (sqlite3_int64*)pPrior;
14889   p--;
14890   return (int)p[0];
14891 }
14892 
14893 /*
14894 ** Like realloc().  Resize an allocation previously obtained from
14895 ** sqlite3MemMalloc().
14896 **
14897 ** For this low-level interface, we know that pPrior!=0.  Cases where
14898 ** pPrior==0 while have been intercepted by higher-level routine and
14899 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
14900 ** cases where nByte<=0 will have been intercepted by higher-level
14901 ** routines and redirected to xFree.
14902 */
sqlite3MemRealloc(void * pPrior,int nByte)14903 static void *sqlite3MemRealloc(void *pPrior, int nByte){
14904   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
14905   assert( pPrior!=0 && nByte>0 );
14906   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
14907   p--;
14908   p = realloc(p, nByte+8 );
14909   if( p ){
14910     p[0] = nByte;
14911     p++;
14912   }else{
14913     testcase( sqlite3GlobalConfig.xLog!=0 );
14914     sqlite3_log(SQLITE_NOMEM,
14915       "failed memory resize %u to %u bytes",
14916       sqlite3MemSize(pPrior), nByte);
14917   }
14918   return (void*)p;
14919 }
14920 
14921 /*
14922 ** Round up a request size to the next valid allocation size.
14923 */
sqlite3MemRoundup(int n)14924 static int sqlite3MemRoundup(int n){
14925   return ROUND8(n);
14926 }
14927 
14928 /*
14929 ** Initialize this module.
14930 */
sqlite3MemInit(void * NotUsed)14931 static int sqlite3MemInit(void *NotUsed){
14932   UNUSED_PARAMETER(NotUsed);
14933   return SQLITE_OK;
14934 }
14935 
14936 /*
14937 ** Deinitialize this module.
14938 */
sqlite3MemShutdown(void * NotUsed)14939 static void sqlite3MemShutdown(void *NotUsed){
14940   UNUSED_PARAMETER(NotUsed);
14941   return;
14942 }
14943 
14944 /*
14945 ** This routine is the only routine in this file with external linkage.
14946 **
14947 ** Populate the low-level memory allocation function pointers in
14948 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
14949 */
sqlite3MemSetDefault(void)14950 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
14951   static const sqlite3_mem_methods defaultMethods = {
14952      sqlite3MemMalloc,
14953      sqlite3MemFree,
14954      sqlite3MemRealloc,
14955      sqlite3MemSize,
14956      sqlite3MemRoundup,
14957      sqlite3MemInit,
14958      sqlite3MemShutdown,
14959      0
14960   };
14961   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
14962 }
14963 
14964 #endif /* SQLITE_SYSTEM_MALLOC */
14965 
14966 /************** End of mem1.c ************************************************/
14967 /************** Begin file mem2.c ********************************************/
14968 /*
14969 ** 2007 August 15
14970 **
14971 ** The author disclaims copyright to this source code.  In place of
14972 ** a legal notice, here is a blessing:
14973 **
14974 **    May you do good and not evil.
14975 **    May you find forgiveness for yourself and forgive others.
14976 **    May you share freely, never taking more than you give.
14977 **
14978 *************************************************************************
14979 **
14980 ** This file contains low-level memory allocation drivers for when
14981 ** SQLite will use the standard C-library malloc/realloc/free interface
14982 ** to obtain the memory it needs while adding lots of additional debugging
14983 ** information to each allocation in order to help detect and fix memory
14984 ** leaks and memory usage errors.
14985 **
14986 ** This file contains implementations of the low-level memory allocation
14987 ** routines specified in the sqlite3_mem_methods object.
14988 */
14989 
14990 /*
14991 ** This version of the memory allocator is used only if the
14992 ** SQLITE_MEMDEBUG macro is defined
14993 */
14994 #ifdef SQLITE_MEMDEBUG
14995 
14996 /*
14997 ** The backtrace functionality is only available with GLIBC
14998 */
14999 #ifdef __GLIBC__
15000   extern int backtrace(void**,int);
15001   extern void backtrace_symbols_fd(void*const*,int,int);
15002 #else
15003 # define backtrace(A,B) 1
15004 # define backtrace_symbols_fd(A,B,C)
15005 #endif
15006 /* #include <stdio.h> */
15007 
15008 /*
15009 ** Each memory allocation looks like this:
15010 **
15011 **  ------------------------------------------------------------------------
15012 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15013 **  ------------------------------------------------------------------------
15014 **
15015 ** The application code sees only a pointer to the allocation.  We have
15016 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15017 ** MemBlockHdr tells us the size of the allocation and the number of
15018 ** backtrace pointers.  There is also a guard word at the end of the
15019 ** MemBlockHdr.
15020 */
15021 struct MemBlockHdr {
15022   i64 iSize;                          /* Size of this allocation */
15023   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15024   char nBacktrace;                    /* Number of backtraces on this alloc */
15025   char nBacktraceSlots;               /* Available backtrace slots */
15026   u8 nTitle;                          /* Bytes of title; includes '\0' */
15027   u8 eType;                           /* Allocation type code */
15028   int iForeGuard;                     /* Guard word for sanity */
15029 };
15030 
15031 /*
15032 ** Guard words
15033 */
15034 #define FOREGUARD 0x80F5E153
15035 #define REARGUARD 0xE4676B53
15036 
15037 /*
15038 ** Number of malloc size increments to track.
15039 */
15040 #define NCSIZE  1000
15041 
15042 /*
15043 ** All of the static variables used by this module are collected
15044 ** into a single structure named "mem".  This is to keep the
15045 ** static variables organized and to reduce namespace pollution
15046 ** when this module is combined with other in the amalgamation.
15047 */
15048 static struct {
15049 
15050   /*
15051   ** Mutex to control access to the memory allocation subsystem.
15052   */
15053   sqlite3_mutex *mutex;
15054 
15055   /*
15056   ** Head and tail of a linked list of all outstanding allocations
15057   */
15058   struct MemBlockHdr *pFirst;
15059   struct MemBlockHdr *pLast;
15060 
15061   /*
15062   ** The number of levels of backtrace to save in new allocations.
15063   */
15064   int nBacktrace;
15065   void (*xBacktrace)(int, int, void **);
15066 
15067   /*
15068   ** Title text to insert in front of each block
15069   */
15070   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15071   char zTitle[100];  /* The title text */
15072 
15073   /*
15074   ** sqlite3MallocDisallow() increments the following counter.
15075   ** sqlite3MallocAllow() decrements it.
15076   */
15077   int disallow; /* Do not allow memory allocation */
15078 
15079   /*
15080   ** Gather statistics on the sizes of memory allocations.
15081   ** nAlloc[i] is the number of allocation attempts of i*8
15082   ** bytes.  i==NCSIZE is the number of allocation attempts for
15083   ** sizes more than NCSIZE*8 bytes.
15084   */
15085   int nAlloc[NCSIZE];      /* Total number of allocations */
15086   int nCurrent[NCSIZE];    /* Current number of allocations */
15087   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15088 
15089 } mem;
15090 
15091 
15092 /*
15093 ** Adjust memory usage statistics
15094 */
adjustStats(int iSize,int increment)15095 static void adjustStats(int iSize, int increment){
15096   int i = ROUND8(iSize)/8;
15097   if( i>NCSIZE-1 ){
15098     i = NCSIZE - 1;
15099   }
15100   if( increment>0 ){
15101     mem.nAlloc[i]++;
15102     mem.nCurrent[i]++;
15103     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15104       mem.mxCurrent[i] = mem.nCurrent[i];
15105     }
15106   }else{
15107     mem.nCurrent[i]--;
15108     assert( mem.nCurrent[i]>=0 );
15109   }
15110 }
15111 
15112 /*
15113 ** Given an allocation, find the MemBlockHdr for that allocation.
15114 **
15115 ** This routine checks the guards at either end of the allocation and
15116 ** if they are incorrect it asserts.
15117 */
sqlite3MemsysGetHeader(void * pAllocation)15118 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15119   struct MemBlockHdr *p;
15120   int *pInt;
15121   u8 *pU8;
15122   int nReserve;
15123 
15124   p = (struct MemBlockHdr*)pAllocation;
15125   p--;
15126   assert( p->iForeGuard==(int)FOREGUARD );
15127   nReserve = ROUND8(p->iSize);
15128   pInt = (int*)pAllocation;
15129   pU8 = (u8*)pAllocation;
15130   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15131   /* This checks any of the "extra" bytes allocated due
15132   ** to rounding up to an 8 byte boundary to ensure
15133   ** they haven't been overwritten.
15134   */
15135   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15136   return p;
15137 }
15138 
15139 /*
15140 ** Return the number of bytes currently allocated at address p.
15141 */
sqlite3MemSize(void * p)15142 static int sqlite3MemSize(void *p){
15143   struct MemBlockHdr *pHdr;
15144   if( !p ){
15145     return 0;
15146   }
15147   pHdr = sqlite3MemsysGetHeader(p);
15148   return pHdr->iSize;
15149 }
15150 
15151 /*
15152 ** Initialize the memory allocation subsystem.
15153 */
sqlite3MemInit(void * NotUsed)15154 static int sqlite3MemInit(void *NotUsed){
15155   UNUSED_PARAMETER(NotUsed);
15156   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15157   if( !sqlite3GlobalConfig.bMemstat ){
15158     /* If memory status is enabled, then the malloc.c wrapper will already
15159     ** hold the STATIC_MEM mutex when the routines here are invoked. */
15160     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15161   }
15162   return SQLITE_OK;
15163 }
15164 
15165 /*
15166 ** Deinitialize the memory allocation subsystem.
15167 */
sqlite3MemShutdown(void * NotUsed)15168 static void sqlite3MemShutdown(void *NotUsed){
15169   UNUSED_PARAMETER(NotUsed);
15170   mem.mutex = 0;
15171 }
15172 
15173 /*
15174 ** Round up a request size to the next valid allocation size.
15175 */
sqlite3MemRoundup(int n)15176 static int sqlite3MemRoundup(int n){
15177   return ROUND8(n);
15178 }
15179 
15180 /*
15181 ** Fill a buffer with pseudo-random bytes.  This is used to preset
15182 ** the content of a new memory allocation to unpredictable values and
15183 ** to clear the content of a freed allocation to unpredictable values.
15184 */
randomFill(char * pBuf,int nByte)15185 static void randomFill(char *pBuf, int nByte){
15186   unsigned int x, y, r;
15187   x = SQLITE_PTR_TO_INT(pBuf);
15188   y = nByte | 1;
15189   while( nByte >= 4 ){
15190     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15191     y = y*1103515245 + 12345;
15192     r = x ^ y;
15193     *(int*)pBuf = r;
15194     pBuf += 4;
15195     nByte -= 4;
15196   }
15197   while( nByte-- > 0 ){
15198     x = (x>>1) ^ (-(x&1) & 0xd0000001);
15199     y = y*1103515245 + 12345;
15200     r = x ^ y;
15201     *(pBuf++) = r & 0xff;
15202   }
15203 }
15204 
15205 /*
15206 ** Allocate nByte bytes of memory.
15207 */
sqlite3MemMalloc(int nByte)15208 static void *sqlite3MemMalloc(int nByte){
15209   struct MemBlockHdr *pHdr;
15210   void **pBt;
15211   char *z;
15212   int *pInt;
15213   void *p = 0;
15214   int totalSize;
15215   int nReserve;
15216   sqlite3_mutex_enter(mem.mutex);
15217   assert( mem.disallow==0 );
15218   nReserve = ROUND8(nByte);
15219   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15220                mem.nBacktrace*sizeof(void*) + mem.nTitle;
15221   p = malloc(totalSize);
15222   if( p ){
15223     z = p;
15224     pBt = (void**)&z[mem.nTitle];
15225     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15226     pHdr->pNext = 0;
15227     pHdr->pPrev = mem.pLast;
15228     if( mem.pLast ){
15229       mem.pLast->pNext = pHdr;
15230     }else{
15231       mem.pFirst = pHdr;
15232     }
15233     mem.pLast = pHdr;
15234     pHdr->iForeGuard = FOREGUARD;
15235     pHdr->eType = MEMTYPE_HEAP;
15236     pHdr->nBacktraceSlots = mem.nBacktrace;
15237     pHdr->nTitle = mem.nTitle;
15238     if( mem.nBacktrace ){
15239       void *aAddr[40];
15240       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15241       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15242       assert(pBt[0]);
15243       if( mem.xBacktrace ){
15244         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15245       }
15246     }else{
15247       pHdr->nBacktrace = 0;
15248     }
15249     if( mem.nTitle ){
15250       memcpy(z, mem.zTitle, mem.nTitle);
15251     }
15252     pHdr->iSize = nByte;
15253     adjustStats(nByte, +1);
15254     pInt = (int*)&pHdr[1];
15255     pInt[nReserve/sizeof(int)] = REARGUARD;
15256     randomFill((char*)pInt, nByte);
15257     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15258     p = (void*)pInt;
15259   }
15260   sqlite3_mutex_leave(mem.mutex);
15261   return p;
15262 }
15263 
15264 /*
15265 ** Free memory.
15266 */
sqlite3MemFree(void * pPrior)15267 static void sqlite3MemFree(void *pPrior){
15268   struct MemBlockHdr *pHdr;
15269   void **pBt;
15270   char *z;
15271   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
15272        || mem.mutex!=0 );
15273   pHdr = sqlite3MemsysGetHeader(pPrior);
15274   pBt = (void**)pHdr;
15275   pBt -= pHdr->nBacktraceSlots;
15276   sqlite3_mutex_enter(mem.mutex);
15277   if( pHdr->pPrev ){
15278     assert( pHdr->pPrev->pNext==pHdr );
15279     pHdr->pPrev->pNext = pHdr->pNext;
15280   }else{
15281     assert( mem.pFirst==pHdr );
15282     mem.pFirst = pHdr->pNext;
15283   }
15284   if( pHdr->pNext ){
15285     assert( pHdr->pNext->pPrev==pHdr );
15286     pHdr->pNext->pPrev = pHdr->pPrev;
15287   }else{
15288     assert( mem.pLast==pHdr );
15289     mem.pLast = pHdr->pPrev;
15290   }
15291   z = (char*)pBt;
15292   z -= pHdr->nTitle;
15293   adjustStats(pHdr->iSize, -1);
15294   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15295                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
15296   free(z);
15297   sqlite3_mutex_leave(mem.mutex);
15298 }
15299 
15300 /*
15301 ** Change the size of an existing memory allocation.
15302 **
15303 ** For this debugging implementation, we *always* make a copy of the
15304 ** allocation into a new place in memory.  In this way, if the
15305 ** higher level code is using pointer to the old allocation, it is
15306 ** much more likely to break and we are much more liking to find
15307 ** the error.
15308 */
sqlite3MemRealloc(void * pPrior,int nByte)15309 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15310   struct MemBlockHdr *pOldHdr;
15311   void *pNew;
15312   assert( mem.disallow==0 );
15313   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15314   pOldHdr = sqlite3MemsysGetHeader(pPrior);
15315   pNew = sqlite3MemMalloc(nByte);
15316   if( pNew ){
15317     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15318     if( nByte>pOldHdr->iSize ){
15319       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15320     }
15321     sqlite3MemFree(pPrior);
15322   }
15323   return pNew;
15324 }
15325 
15326 /*
15327 ** Populate the low-level memory allocation function pointers in
15328 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15329 */
sqlite3MemSetDefault(void)15330 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15331   static const sqlite3_mem_methods defaultMethods = {
15332      sqlite3MemMalloc,
15333      sqlite3MemFree,
15334      sqlite3MemRealloc,
15335      sqlite3MemSize,
15336      sqlite3MemRoundup,
15337      sqlite3MemInit,
15338      sqlite3MemShutdown,
15339      0
15340   };
15341   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15342 }
15343 
15344 /*
15345 ** Set the "type" of an allocation.
15346 */
sqlite3MemdebugSetType(void * p,u8 eType)15347 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15348   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15349     struct MemBlockHdr *pHdr;
15350     pHdr = sqlite3MemsysGetHeader(p);
15351     assert( pHdr->iForeGuard==FOREGUARD );
15352     pHdr->eType = eType;
15353   }
15354 }
15355 
15356 /*
15357 ** Return TRUE if the mask of type in eType matches the type of the
15358 ** allocation p.  Also return true if p==NULL.
15359 **
15360 ** This routine is designed for use within an assert() statement, to
15361 ** verify the type of an allocation.  For example:
15362 **
15363 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15364 */
sqlite3MemdebugHasType(void * p,u8 eType)15365 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15366   int rc = 1;
15367   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15368     struct MemBlockHdr *pHdr;
15369     pHdr = sqlite3MemsysGetHeader(p);
15370     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15371     if( (pHdr->eType&eType)==0 ){
15372       rc = 0;
15373     }
15374   }
15375   return rc;
15376 }
15377 
15378 /*
15379 ** Return TRUE if the mask of type in eType matches no bits of the type of the
15380 ** allocation p.  Also return true if p==NULL.
15381 **
15382 ** This routine is designed for use within an assert() statement, to
15383 ** verify the type of an allocation.  For example:
15384 **
15385 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15386 */
sqlite3MemdebugNoType(void * p,u8 eType)15387 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15388   int rc = 1;
15389   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15390     struct MemBlockHdr *pHdr;
15391     pHdr = sqlite3MemsysGetHeader(p);
15392     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15393     if( (pHdr->eType&eType)!=0 ){
15394       rc = 0;
15395     }
15396   }
15397   return rc;
15398 }
15399 
15400 /*
15401 ** Set the number of backtrace levels kept for each allocation.
15402 ** A value of zero turns off backtracing.  The number is always rounded
15403 ** up to a multiple of 2.
15404 */
sqlite3MemdebugBacktrace(int depth)15405 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15406   if( depth<0 ){ depth = 0; }
15407   if( depth>20 ){ depth = 20; }
15408   depth = (depth+1)&0xfe;
15409   mem.nBacktrace = depth;
15410 }
15411 
sqlite3MemdebugBacktraceCallback(void (* xBacktrace)(int,int,void **))15412 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15413   mem.xBacktrace = xBacktrace;
15414 }
15415 
15416 /*
15417 ** Set the title string for subsequent allocations.
15418 */
sqlite3MemdebugSettitle(const char * zTitle)15419 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15420   unsigned int n = sqlite3Strlen30(zTitle) + 1;
15421   sqlite3_mutex_enter(mem.mutex);
15422   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15423   memcpy(mem.zTitle, zTitle, n);
15424   mem.zTitle[n] = 0;
15425   mem.nTitle = ROUND8(n);
15426   sqlite3_mutex_leave(mem.mutex);
15427 }
15428 
sqlite3MemdebugSync()15429 SQLITE_PRIVATE void sqlite3MemdebugSync(){
15430   struct MemBlockHdr *pHdr;
15431   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15432     void **pBt = (void**)pHdr;
15433     pBt -= pHdr->nBacktraceSlots;
15434     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15435   }
15436 }
15437 
15438 /*
15439 ** Open the file indicated and write a log of all unfreed memory
15440 ** allocations into that log.
15441 */
sqlite3MemdebugDump(const char * zFilename)15442 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15443   FILE *out;
15444   struct MemBlockHdr *pHdr;
15445   void **pBt;
15446   int i;
15447   out = fopen(zFilename, "w");
15448   if( out==0 ){
15449     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15450                     zFilename);
15451     return;
15452   }
15453   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15454     char *z = (char*)pHdr;
15455     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15456     fprintf(out, "**** %lld bytes at %p from %s ****\n",
15457             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15458     if( pHdr->nBacktrace ){
15459       fflush(out);
15460       pBt = (void**)pHdr;
15461       pBt -= pHdr->nBacktraceSlots;
15462       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15463       fprintf(out, "\n");
15464     }
15465   }
15466   fprintf(out, "COUNTS:\n");
15467   for(i=0; i<NCSIZE-1; i++){
15468     if( mem.nAlloc[i] ){
15469       fprintf(out, "   %5d: %10d %10d %10d\n",
15470             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15471     }
15472   }
15473   if( mem.nAlloc[NCSIZE-1] ){
15474     fprintf(out, "   %5d: %10d %10d %10d\n",
15475              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15476              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15477   }
15478   fclose(out);
15479 }
15480 
15481 /*
15482 ** Return the number of times sqlite3MemMalloc() has been called.
15483 */
sqlite3MemdebugMallocCount()15484 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15485   int i;
15486   int nTotal = 0;
15487   for(i=0; i<NCSIZE; i++){
15488     nTotal += mem.nAlloc[i];
15489   }
15490   return nTotal;
15491 }
15492 
15493 
15494 #endif /* SQLITE_MEMDEBUG */
15495 
15496 /************** End of mem2.c ************************************************/
15497 /************** Begin file mem3.c ********************************************/
15498 /*
15499 ** 2007 October 14
15500 **
15501 ** The author disclaims copyright to this source code.  In place of
15502 ** a legal notice, here is a blessing:
15503 **
15504 **    May you do good and not evil.
15505 **    May you find forgiveness for yourself and forgive others.
15506 **    May you share freely, never taking more than you give.
15507 **
15508 *************************************************************************
15509 ** This file contains the C functions that implement a memory
15510 ** allocation subsystem for use by SQLite.
15511 **
15512 ** This version of the memory allocation subsystem omits all
15513 ** use of malloc(). The SQLite user supplies a block of memory
15514 ** before calling sqlite3_initialize() from which allocations
15515 ** are made and returned by the xMalloc() and xRealloc()
15516 ** implementations. Once sqlite3_initialize() has been called,
15517 ** the amount of memory available to SQLite is fixed and cannot
15518 ** be changed.
15519 **
15520 ** This version of the memory allocation subsystem is included
15521 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
15522 */
15523 
15524 /*
15525 ** This version of the memory allocator is only built into the library
15526 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
15527 ** mean that the library will use a memory-pool by default, just that
15528 ** it is available. The mempool allocator is activated by calling
15529 ** sqlite3_config().
15530 */
15531 #ifdef SQLITE_ENABLE_MEMSYS3
15532 
15533 /*
15534 ** Maximum size (in Mem3Blocks) of a "small" chunk.
15535 */
15536 #define MX_SMALL 10
15537 
15538 
15539 /*
15540 ** Number of freelist hash slots
15541 */
15542 #define N_HASH  61
15543 
15544 /*
15545 ** A memory allocation (also called a "chunk") consists of two or
15546 ** more blocks where each block is 8 bytes.  The first 8 bytes are
15547 ** a header that is not returned to the user.
15548 **
15549 ** A chunk is two or more blocks that is either checked out or
15550 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
15551 ** size of the allocation in blocks if the allocation is free.
15552 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
15553 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
15554 ** is true if the previous chunk is checked out and false if the
15555 ** previous chunk is free.  The u.hdr.prevSize field is the size of
15556 ** the previous chunk in blocks if the previous chunk is on the
15557 ** freelist. If the previous chunk is checked out, then
15558 ** u.hdr.prevSize can be part of the data for that chunk and should
15559 ** not be read or written.
15560 **
15561 ** We often identify a chunk by its index in mem3.aPool[].  When
15562 ** this is done, the chunk index refers to the second block of
15563 ** the chunk.  In this way, the first chunk has an index of 1.
15564 ** A chunk index of 0 means "no such chunk" and is the equivalent
15565 ** of a NULL pointer.
15566 **
15567 ** The second block of free chunks is of the form u.list.  The
15568 ** two fields form a double-linked list of chunks of related sizes.
15569 ** Pointers to the head of the list are stored in mem3.aiSmall[]
15570 ** for smaller chunks and mem3.aiHash[] for larger chunks.
15571 **
15572 ** The second block of a chunk is user data if the chunk is checked
15573 ** out.  If a chunk is checked out, the user data may extend into
15574 ** the u.hdr.prevSize value of the following chunk.
15575 */
15576 typedef struct Mem3Block Mem3Block;
15577 struct Mem3Block {
15578   union {
15579     struct {
15580       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
15581       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
15582     } hdr;
15583     struct {
15584       u32 next;       /* Index in mem3.aPool[] of next free chunk */
15585       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
15586     } list;
15587   } u;
15588 };
15589 
15590 /*
15591 ** All of the static variables used by this module are collected
15592 ** into a single structure named "mem3".  This is to keep the
15593 ** static variables organized and to reduce namespace pollution
15594 ** when this module is combined with other in the amalgamation.
15595 */
15596 static SQLITE_WSD struct Mem3Global {
15597   /*
15598   ** Memory available for allocation. nPool is the size of the array
15599   ** (in Mem3Blocks) pointed to by aPool less 2.
15600   */
15601   u32 nPool;
15602   Mem3Block *aPool;
15603 
15604   /*
15605   ** True if we are evaluating an out-of-memory callback.
15606   */
15607   int alarmBusy;
15608 
15609   /*
15610   ** Mutex to control access to the memory allocation subsystem.
15611   */
15612   sqlite3_mutex *mutex;
15613 
15614   /*
15615   ** The minimum amount of free space that we have seen.
15616   */
15617   u32 mnMaster;
15618 
15619   /*
15620   ** iMaster is the index of the master chunk.  Most new allocations
15621   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
15622   ** of the current master.  iMaster is 0 if there is not master chunk.
15623   ** The master chunk is not in either the aiHash[] or aiSmall[].
15624   */
15625   u32 iMaster;
15626   u32 szMaster;
15627 
15628   /*
15629   ** Array of lists of free blocks according to the block size
15630   ** for smaller chunks, or a hash on the block size for larger
15631   ** chunks.
15632   */
15633   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
15634   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
15635 } mem3 = { 97535575 };
15636 
15637 #define mem3 GLOBAL(struct Mem3Global, mem3)
15638 
15639 /*
15640 ** Unlink the chunk at mem3.aPool[i] from list it is currently
15641 ** on.  *pRoot is the list that i is a member of.
15642 */
memsys3UnlinkFromList(u32 i,u32 * pRoot)15643 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
15644   u32 next = mem3.aPool[i].u.list.next;
15645   u32 prev = mem3.aPool[i].u.list.prev;
15646   assert( sqlite3_mutex_held(mem3.mutex) );
15647   if( prev==0 ){
15648     *pRoot = next;
15649   }else{
15650     mem3.aPool[prev].u.list.next = next;
15651   }
15652   if( next ){
15653     mem3.aPool[next].u.list.prev = prev;
15654   }
15655   mem3.aPool[i].u.list.next = 0;
15656   mem3.aPool[i].u.list.prev = 0;
15657 }
15658 
15659 /*
15660 ** Unlink the chunk at index i from
15661 ** whatever list is currently a member of.
15662 */
memsys3Unlink(u32 i)15663 static void memsys3Unlink(u32 i){
15664   u32 size, hash;
15665   assert( sqlite3_mutex_held(mem3.mutex) );
15666   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15667   assert( i>=1 );
15668   size = mem3.aPool[i-1].u.hdr.size4x/4;
15669   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15670   assert( size>=2 );
15671   if( size <= MX_SMALL ){
15672     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
15673   }else{
15674     hash = size % N_HASH;
15675     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15676   }
15677 }
15678 
15679 /*
15680 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
15681 ** at *pRoot.
15682 */
memsys3LinkIntoList(u32 i,u32 * pRoot)15683 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
15684   assert( sqlite3_mutex_held(mem3.mutex) );
15685   mem3.aPool[i].u.list.next = *pRoot;
15686   mem3.aPool[i].u.list.prev = 0;
15687   if( *pRoot ){
15688     mem3.aPool[*pRoot].u.list.prev = i;
15689   }
15690   *pRoot = i;
15691 }
15692 
15693 /*
15694 ** Link the chunk at index i into either the appropriate
15695 ** small chunk list, or into the large chunk hash table.
15696 */
memsys3Link(u32 i)15697 static void memsys3Link(u32 i){
15698   u32 size, hash;
15699   assert( sqlite3_mutex_held(mem3.mutex) );
15700   assert( i>=1 );
15701   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
15702   size = mem3.aPool[i-1].u.hdr.size4x/4;
15703   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
15704   assert( size>=2 );
15705   if( size <= MX_SMALL ){
15706     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
15707   }else{
15708     hash = size % N_HASH;
15709     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
15710   }
15711 }
15712 
15713 /*
15714 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
15715 ** will already be held (obtained by code in malloc.c) if
15716 ** sqlite3GlobalConfig.bMemStat is true.
15717 */
memsys3Enter(void)15718 static void memsys3Enter(void){
15719   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
15720     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15721   }
15722   sqlite3_mutex_enter(mem3.mutex);
15723 }
memsys3Leave(void)15724 static void memsys3Leave(void){
15725   sqlite3_mutex_leave(mem3.mutex);
15726 }
15727 
15728 /*
15729 ** Called when we are unable to satisfy an allocation of nBytes.
15730 */
memsys3OutOfMemory(int nByte)15731 static void memsys3OutOfMemory(int nByte){
15732   if( !mem3.alarmBusy ){
15733     mem3.alarmBusy = 1;
15734     assert( sqlite3_mutex_held(mem3.mutex) );
15735     sqlite3_mutex_leave(mem3.mutex);
15736     sqlite3_release_memory(nByte);
15737     sqlite3_mutex_enter(mem3.mutex);
15738     mem3.alarmBusy = 0;
15739   }
15740 }
15741 
15742 
15743 /*
15744 ** Chunk i is a free chunk that has been unlinked.  Adjust its
15745 ** size parameters for check-out and return a pointer to the
15746 ** user portion of the chunk.
15747 */
memsys3Checkout(u32 i,u32 nBlock)15748 static void *memsys3Checkout(u32 i, u32 nBlock){
15749   u32 x;
15750   assert( sqlite3_mutex_held(mem3.mutex) );
15751   assert( i>=1 );
15752   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
15753   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
15754   x = mem3.aPool[i-1].u.hdr.size4x;
15755   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
15756   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
15757   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
15758   return &mem3.aPool[i];
15759 }
15760 
15761 /*
15762 ** Carve a piece off of the end of the mem3.iMaster free chunk.
15763 ** Return a pointer to the new allocation.  Or, if the master chunk
15764 ** is not large enough, return 0.
15765 */
memsys3FromMaster(u32 nBlock)15766 static void *memsys3FromMaster(u32 nBlock){
15767   assert( sqlite3_mutex_held(mem3.mutex) );
15768   assert( mem3.szMaster>=nBlock );
15769   if( nBlock>=mem3.szMaster-1 ){
15770     /* Use the entire master */
15771     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
15772     mem3.iMaster = 0;
15773     mem3.szMaster = 0;
15774     mem3.mnMaster = 0;
15775     return p;
15776   }else{
15777     /* Split the master block.  Return the tail. */
15778     u32 newi, x;
15779     newi = mem3.iMaster + mem3.szMaster - nBlock;
15780     assert( newi > mem3.iMaster+1 );
15781     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
15782     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
15783     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
15784     mem3.szMaster -= nBlock;
15785     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
15786     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15787     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15788     if( mem3.szMaster < mem3.mnMaster ){
15789       mem3.mnMaster = mem3.szMaster;
15790     }
15791     return (void*)&mem3.aPool[newi];
15792   }
15793 }
15794 
15795 /*
15796 ** *pRoot is the head of a list of free chunks of the same size
15797 ** or same size hash.  In other words, *pRoot is an entry in either
15798 ** mem3.aiSmall[] or mem3.aiHash[].
15799 **
15800 ** This routine examines all entries on the given list and tries
15801 ** to coalesce each entries with adjacent free chunks.
15802 **
15803 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
15804 ** the current mem3.iMaster with the new larger chunk.  In order for
15805 ** this mem3.iMaster replacement to work, the master chunk must be
15806 ** linked into the hash tables.  That is not the normal state of
15807 ** affairs, of course.  The calling routine must link the master
15808 ** chunk before invoking this routine, then must unlink the (possibly
15809 ** changed) master chunk once this routine has finished.
15810 */
memsys3Merge(u32 * pRoot)15811 static void memsys3Merge(u32 *pRoot){
15812   u32 iNext, prev, size, i, x;
15813 
15814   assert( sqlite3_mutex_held(mem3.mutex) );
15815   for(i=*pRoot; i>0; i=iNext){
15816     iNext = mem3.aPool[i].u.list.next;
15817     size = mem3.aPool[i-1].u.hdr.size4x;
15818     assert( (size&1)==0 );
15819     if( (size&2)==0 ){
15820       memsys3UnlinkFromList(i, pRoot);
15821       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
15822       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
15823       if( prev==iNext ){
15824         iNext = mem3.aPool[prev].u.list.next;
15825       }
15826       memsys3Unlink(prev);
15827       size = i + size/4 - prev;
15828       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
15829       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
15830       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
15831       memsys3Link(prev);
15832       i = prev;
15833     }else{
15834       size /= 4;
15835     }
15836     if( size>mem3.szMaster ){
15837       mem3.iMaster = i;
15838       mem3.szMaster = size;
15839     }
15840   }
15841 }
15842 
15843 /*
15844 ** Return a block of memory of at least nBytes in size.
15845 ** Return NULL if unable.
15846 **
15847 ** This function assumes that the necessary mutexes, if any, are
15848 ** already held by the caller. Hence "Unsafe".
15849 */
memsys3MallocUnsafe(int nByte)15850 static void *memsys3MallocUnsafe(int nByte){
15851   u32 i;
15852   u32 nBlock;
15853   u32 toFree;
15854 
15855   assert( sqlite3_mutex_held(mem3.mutex) );
15856   assert( sizeof(Mem3Block)==8 );
15857   if( nByte<=12 ){
15858     nBlock = 2;
15859   }else{
15860     nBlock = (nByte + 11)/8;
15861   }
15862   assert( nBlock>=2 );
15863 
15864   /* STEP 1:
15865   ** Look for an entry of the correct size in either the small
15866   ** chunk table or in the large chunk hash table.  This is
15867   ** successful most of the time (about 9 times out of 10).
15868   */
15869   if( nBlock <= MX_SMALL ){
15870     i = mem3.aiSmall[nBlock-2];
15871     if( i>0 ){
15872       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
15873       return memsys3Checkout(i, nBlock);
15874     }
15875   }else{
15876     int hash = nBlock % N_HASH;
15877     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
15878       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
15879         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
15880         return memsys3Checkout(i, nBlock);
15881       }
15882     }
15883   }
15884 
15885   /* STEP 2:
15886   ** Try to satisfy the allocation by carving a piece off of the end
15887   ** of the master chunk.  This step usually works if step 1 fails.
15888   */
15889   if( mem3.szMaster>=nBlock ){
15890     return memsys3FromMaster(nBlock);
15891   }
15892 
15893 
15894   /* STEP 3:
15895   ** Loop through the entire memory pool.  Coalesce adjacent free
15896   ** chunks.  Recompute the master chunk as the largest free chunk.
15897   ** Then try again to satisfy the allocation by carving a piece off
15898   ** of the end of the master chunk.  This step happens very
15899   ** rarely (we hope!)
15900   */
15901   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
15902     memsys3OutOfMemory(toFree);
15903     if( mem3.iMaster ){
15904       memsys3Link(mem3.iMaster);
15905       mem3.iMaster = 0;
15906       mem3.szMaster = 0;
15907     }
15908     for(i=0; i<N_HASH; i++){
15909       memsys3Merge(&mem3.aiHash[i]);
15910     }
15911     for(i=0; i<MX_SMALL-1; i++){
15912       memsys3Merge(&mem3.aiSmall[i]);
15913     }
15914     if( mem3.szMaster ){
15915       memsys3Unlink(mem3.iMaster);
15916       if( mem3.szMaster>=nBlock ){
15917         return memsys3FromMaster(nBlock);
15918       }
15919     }
15920   }
15921 
15922   /* If none of the above worked, then we fail. */
15923   return 0;
15924 }
15925 
15926 /*
15927 ** Free an outstanding memory allocation.
15928 **
15929 ** This function assumes that the necessary mutexes, if any, are
15930 ** already held by the caller. Hence "Unsafe".
15931 */
memsys3FreeUnsafe(void * pOld)15932 static void memsys3FreeUnsafe(void *pOld){
15933   Mem3Block *p = (Mem3Block*)pOld;
15934   int i;
15935   u32 size, x;
15936   assert( sqlite3_mutex_held(mem3.mutex) );
15937   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
15938   i = p - mem3.aPool;
15939   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
15940   size = mem3.aPool[i-1].u.hdr.size4x/4;
15941   assert( i+size<=mem3.nPool+1 );
15942   mem3.aPool[i-1].u.hdr.size4x &= ~1;
15943   mem3.aPool[i+size-1].u.hdr.prevSize = size;
15944   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
15945   memsys3Link(i);
15946 
15947   /* Try to expand the master using the newly freed chunk */
15948   if( mem3.iMaster ){
15949     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
15950       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
15951       mem3.iMaster -= size;
15952       mem3.szMaster += size;
15953       memsys3Unlink(mem3.iMaster);
15954       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15955       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15956       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15957     }
15958     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
15959     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
15960       memsys3Unlink(mem3.iMaster+mem3.szMaster);
15961       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
15962       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
15963       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
15964     }
15965   }
15966 }
15967 
15968 /*
15969 ** Return the size of an outstanding allocation, in bytes.  The
15970 ** size returned omits the 8-byte header overhead.  This only
15971 ** works for chunks that are currently checked out.
15972 */
memsys3Size(void * p)15973 static int memsys3Size(void *p){
15974   Mem3Block *pBlock;
15975   if( p==0 ) return 0;
15976   pBlock = (Mem3Block*)p;
15977   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
15978   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
15979 }
15980 
15981 /*
15982 ** Round up a request size to the next valid allocation size.
15983 */
memsys3Roundup(int n)15984 static int memsys3Roundup(int n){
15985   if( n<=12 ){
15986     return 12;
15987   }else{
15988     return ((n+11)&~7) - 4;
15989   }
15990 }
15991 
15992 /*
15993 ** Allocate nBytes of memory.
15994 */
memsys3Malloc(int nBytes)15995 static void *memsys3Malloc(int nBytes){
15996   sqlite3_int64 *p;
15997   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
15998   memsys3Enter();
15999   p = memsys3MallocUnsafe(nBytes);
16000   memsys3Leave();
16001   return (void*)p;
16002 }
16003 
16004 /*
16005 ** Free memory.
16006 */
memsys3Free(void * pPrior)16007 static void memsys3Free(void *pPrior){
16008   assert( pPrior );
16009   memsys3Enter();
16010   memsys3FreeUnsafe(pPrior);
16011   memsys3Leave();
16012 }
16013 
16014 /*
16015 ** Change the size of an existing memory allocation
16016 */
memsys3Realloc(void * pPrior,int nBytes)16017 static void *memsys3Realloc(void *pPrior, int nBytes){
16018   int nOld;
16019   void *p;
16020   if( pPrior==0 ){
16021     return sqlite3_malloc(nBytes);
16022   }
16023   if( nBytes<=0 ){
16024     sqlite3_free(pPrior);
16025     return 0;
16026   }
16027   nOld = memsys3Size(pPrior);
16028   if( nBytes<=nOld && nBytes>=nOld-128 ){
16029     return pPrior;
16030   }
16031   memsys3Enter();
16032   p = memsys3MallocUnsafe(nBytes);
16033   if( p ){
16034     if( nOld<nBytes ){
16035       memcpy(p, pPrior, nOld);
16036     }else{
16037       memcpy(p, pPrior, nBytes);
16038     }
16039     memsys3FreeUnsafe(pPrior);
16040   }
16041   memsys3Leave();
16042   return p;
16043 }
16044 
16045 /*
16046 ** Initialize this module.
16047 */
memsys3Init(void * NotUsed)16048 static int memsys3Init(void *NotUsed){
16049   UNUSED_PARAMETER(NotUsed);
16050   if( !sqlite3GlobalConfig.pHeap ){
16051     return SQLITE_ERROR;
16052   }
16053 
16054   /* Store a pointer to the memory block in global structure mem3. */
16055   assert( sizeof(Mem3Block)==8 );
16056   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16057   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16058 
16059   /* Initialize the master block. */
16060   mem3.szMaster = mem3.nPool;
16061   mem3.mnMaster = mem3.szMaster;
16062   mem3.iMaster = 1;
16063   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16064   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16065   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16066 
16067   return SQLITE_OK;
16068 }
16069 
16070 /*
16071 ** Deinitialize this module.
16072 */
memsys3Shutdown(void * NotUsed)16073 static void memsys3Shutdown(void *NotUsed){
16074   UNUSED_PARAMETER(NotUsed);
16075   mem3.mutex = 0;
16076   return;
16077 }
16078 
16079 
16080 
16081 /*
16082 ** Open the file indicated and write a log of all unfreed memory
16083 ** allocations into that log.
16084 */
sqlite3Memsys3Dump(const char * zFilename)16085 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16086 #ifdef SQLITE_DEBUG
16087   FILE *out;
16088   u32 i, j;
16089   u32 size;
16090   if( zFilename==0 || zFilename[0]==0 ){
16091     out = stdout;
16092   }else{
16093     out = fopen(zFilename, "w");
16094     if( out==0 ){
16095       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16096                       zFilename);
16097       return;
16098     }
16099   }
16100   memsys3Enter();
16101   fprintf(out, "CHUNKS:\n");
16102   for(i=1; i<=mem3.nPool; i+=size/4){
16103     size = mem3.aPool[i-1].u.hdr.size4x;
16104     if( size/4<=1 ){
16105       fprintf(out, "%p size error\n", &mem3.aPool[i]);
16106       assert( 0 );
16107       break;
16108     }
16109     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16110       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16111       assert( 0 );
16112       break;
16113     }
16114     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16115       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16116       assert( 0 );
16117       break;
16118     }
16119     if( size&1 ){
16120       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16121     }else{
16122       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16123                   i==mem3.iMaster ? " **master**" : "");
16124     }
16125   }
16126   for(i=0; i<MX_SMALL-1; i++){
16127     if( mem3.aiSmall[i]==0 ) continue;
16128     fprintf(out, "small(%2d):", i);
16129     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16130       fprintf(out, " %p(%d)", &mem3.aPool[j],
16131               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16132     }
16133     fprintf(out, "\n");
16134   }
16135   for(i=0; i<N_HASH; i++){
16136     if( mem3.aiHash[i]==0 ) continue;
16137     fprintf(out, "hash(%2d):", i);
16138     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16139       fprintf(out, " %p(%d)", &mem3.aPool[j],
16140               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16141     }
16142     fprintf(out, "\n");
16143   }
16144   fprintf(out, "master=%d\n", mem3.iMaster);
16145   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16146   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16147   sqlite3_mutex_leave(mem3.mutex);
16148   if( out==stdout ){
16149     fflush(stdout);
16150   }else{
16151     fclose(out);
16152   }
16153 #else
16154   UNUSED_PARAMETER(zFilename);
16155 #endif
16156 }
16157 
16158 /*
16159 ** This routine is the only routine in this file with external
16160 ** linkage.
16161 **
16162 ** Populate the low-level memory allocation function pointers in
16163 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16164 ** arguments specify the block of memory to manage.
16165 **
16166 ** This routine is only called by sqlite3_config(), and therefore
16167 ** is not required to be threadsafe (it is not).
16168 */
sqlite3MemGetMemsys3(void)16169 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16170   static const sqlite3_mem_methods mempoolMethods = {
16171      memsys3Malloc,
16172      memsys3Free,
16173      memsys3Realloc,
16174      memsys3Size,
16175      memsys3Roundup,
16176      memsys3Init,
16177      memsys3Shutdown,
16178      0
16179   };
16180   return &mempoolMethods;
16181 }
16182 
16183 #endif /* SQLITE_ENABLE_MEMSYS3 */
16184 
16185 /************** End of mem3.c ************************************************/
16186 /************** Begin file mem5.c ********************************************/
16187 /*
16188 ** 2007 October 14
16189 **
16190 ** The author disclaims copyright to this source code.  In place of
16191 ** a legal notice, here is a blessing:
16192 **
16193 **    May you do good and not evil.
16194 **    May you find forgiveness for yourself and forgive others.
16195 **    May you share freely, never taking more than you give.
16196 **
16197 *************************************************************************
16198 ** This file contains the C functions that implement a memory
16199 ** allocation subsystem for use by SQLite.
16200 **
16201 ** This version of the memory allocation subsystem omits all
16202 ** use of malloc(). The application gives SQLite a block of memory
16203 ** before calling sqlite3_initialize() from which allocations
16204 ** are made and returned by the xMalloc() and xRealloc()
16205 ** implementations. Once sqlite3_initialize() has been called,
16206 ** the amount of memory available to SQLite is fixed and cannot
16207 ** be changed.
16208 **
16209 ** This version of the memory allocation subsystem is included
16210 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16211 **
16212 ** This memory allocator uses the following algorithm:
16213 **
16214 **   1.  All memory allocations sizes are rounded up to a power of 2.
16215 **
16216 **   2.  If two adjacent free blocks are the halves of a larger block,
16217 **       then the two blocks are coalesed into the single larger block.
16218 **
16219 **   3.  New memory is allocated from the first available free block.
16220 **
16221 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16222 ** Concerning Dynamic Storage Allocation". Journal of the Association for
16223 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16224 **
16225 ** Let n be the size of the largest allocation divided by the minimum
16226 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
16227 ** be the maximum amount of memory ever outstanding at one time.  Let
16228 ** N be the total amount of memory available for allocation.  Robson
16229 ** proved that this memory allocator will never breakdown due to
16230 ** fragmentation as long as the following constraint holds:
16231 **
16232 **      N >=  M*(1 + log2(n)/2) - n + 1
16233 **
16234 ** The sqlite3_status() logic tracks the maximum values of n and M so
16235 ** that an application can, at any time, verify this constraint.
16236 */
16237 
16238 /*
16239 ** This version of the memory allocator is used only when
16240 ** SQLITE_ENABLE_MEMSYS5 is defined.
16241 */
16242 #ifdef SQLITE_ENABLE_MEMSYS5
16243 
16244 /*
16245 ** A minimum allocation is an instance of the following structure.
16246 ** Larger allocations are an array of these structures where the
16247 ** size of the array is a power of 2.
16248 **
16249 ** The size of this object must be a power of two.  That fact is
16250 ** verified in memsys5Init().
16251 */
16252 typedef struct Mem5Link Mem5Link;
16253 struct Mem5Link {
16254   int next;       /* Index of next free chunk */
16255   int prev;       /* Index of previous free chunk */
16256 };
16257 
16258 /*
16259 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16260 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
16261 ** it is not actually possible to reach this limit.
16262 */
16263 #define LOGMAX 30
16264 
16265 /*
16266 ** Masks used for mem5.aCtrl[] elements.
16267 */
16268 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16269 #define CTRL_FREE     0x20    /* True if not checked out */
16270 
16271 /*
16272 ** All of the static variables used by this module are collected
16273 ** into a single structure named "mem5".  This is to keep the
16274 ** static variables organized and to reduce namespace pollution
16275 ** when this module is combined with other in the amalgamation.
16276 */
16277 static SQLITE_WSD struct Mem5Global {
16278   /*
16279   ** Memory available for allocation
16280   */
16281   int szAtom;      /* Smallest possible allocation in bytes */
16282   int nBlock;      /* Number of szAtom sized blocks in zPool */
16283   u8 *zPool;       /* Memory available to be allocated */
16284 
16285   /*
16286   ** Mutex to control access to the memory allocation subsystem.
16287   */
16288   sqlite3_mutex *mutex;
16289 
16290   /*
16291   ** Performance statistics
16292   */
16293   u64 nAlloc;         /* Total number of calls to malloc */
16294   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16295   u64 totalExcess;    /* Total internal fragmentation */
16296   u32 currentOut;     /* Current checkout, including internal fragmentation */
16297   u32 currentCount;   /* Current number of distinct checkouts */
16298   u32 maxOut;         /* Maximum instantaneous currentOut */
16299   u32 maxCount;       /* Maximum instantaneous currentCount */
16300   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16301 
16302   /*
16303   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16304   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16305   ** and so forth.
16306   */
16307   int aiFreelist[LOGMAX+1];
16308 
16309   /*
16310   ** Space for tracking which blocks are checked out and the size
16311   ** of each block.  One byte per block.
16312   */
16313   u8 *aCtrl;
16314 
16315 } mem5;
16316 
16317 /*
16318 ** Access the static variable through a macro for SQLITE_OMIT_WSD
16319 */
16320 #define mem5 GLOBAL(struct Mem5Global, mem5)
16321 
16322 /*
16323 ** Assuming mem5.zPool is divided up into an array of Mem5Link
16324 ** structures, return a pointer to the idx-th such lik.
16325 */
16326 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16327 
16328 /*
16329 ** Unlink the chunk at mem5.aPool[i] from list it is currently
16330 ** on.  It should be found on mem5.aiFreelist[iLogsize].
16331 */
memsys5Unlink(int i,int iLogsize)16332 static void memsys5Unlink(int i, int iLogsize){
16333   int next, prev;
16334   assert( i>=0 && i<mem5.nBlock );
16335   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16336   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16337 
16338   next = MEM5LINK(i)->next;
16339   prev = MEM5LINK(i)->prev;
16340   if( prev<0 ){
16341     mem5.aiFreelist[iLogsize] = next;
16342   }else{
16343     MEM5LINK(prev)->next = next;
16344   }
16345   if( next>=0 ){
16346     MEM5LINK(next)->prev = prev;
16347   }
16348 }
16349 
16350 /*
16351 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16352 ** free list.
16353 */
memsys5Link(int i,int iLogsize)16354 static void memsys5Link(int i, int iLogsize){
16355   int x;
16356   assert( sqlite3_mutex_held(mem5.mutex) );
16357   assert( i>=0 && i<mem5.nBlock );
16358   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16359   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16360 
16361   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16362   MEM5LINK(i)->prev = -1;
16363   if( x>=0 ){
16364     assert( x<mem5.nBlock );
16365     MEM5LINK(x)->prev = i;
16366   }
16367   mem5.aiFreelist[iLogsize] = i;
16368 }
16369 
16370 /*
16371 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16372 ** will already be held (obtained by code in malloc.c) if
16373 ** sqlite3GlobalConfig.bMemStat is true.
16374 */
memsys5Enter(void)16375 static void memsys5Enter(void){
16376   sqlite3_mutex_enter(mem5.mutex);
16377 }
memsys5Leave(void)16378 static void memsys5Leave(void){
16379   sqlite3_mutex_leave(mem5.mutex);
16380 }
16381 
16382 /*
16383 ** Return the size of an outstanding allocation, in bytes.  The
16384 ** size returned omits the 8-byte header overhead.  This only
16385 ** works for chunks that are currently checked out.
16386 */
memsys5Size(void * p)16387 static int memsys5Size(void *p){
16388   int iSize = 0;
16389   if( p ){
16390     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16391     assert( i>=0 && i<mem5.nBlock );
16392     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16393   }
16394   return iSize;
16395 }
16396 
16397 /*
16398 ** Find the first entry on the freelist iLogsize.  Unlink that
16399 ** entry and return its index.
16400 */
memsys5UnlinkFirst(int iLogsize)16401 static int memsys5UnlinkFirst(int iLogsize){
16402   int i;
16403   int iFirst;
16404 
16405   assert( iLogsize>=0 && iLogsize<=LOGMAX );
16406   i = iFirst = mem5.aiFreelist[iLogsize];
16407   assert( iFirst>=0 );
16408   while( i>0 ){
16409     if( i<iFirst ) iFirst = i;
16410     i = MEM5LINK(i)->next;
16411   }
16412   memsys5Unlink(iFirst, iLogsize);
16413   return iFirst;
16414 }
16415 
16416 /*
16417 ** Return a block of memory of at least nBytes in size.
16418 ** Return NULL if unable.  Return NULL if nBytes==0.
16419 **
16420 ** The caller guarantees that nByte positive.
16421 **
16422 ** The caller has obtained a mutex prior to invoking this
16423 ** routine so there is never any chance that two or more
16424 ** threads can be in this routine at the same time.
16425 */
memsys5MallocUnsafe(int nByte)16426 static void *memsys5MallocUnsafe(int nByte){
16427   int i;           /* Index of a mem5.aPool[] slot */
16428   int iBin;        /* Index into mem5.aiFreelist[] */
16429   int iFullSz;     /* Size of allocation rounded up to power of 2 */
16430   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16431 
16432   /* nByte must be a positive */
16433   assert( nByte>0 );
16434 
16435   /* Keep track of the maximum allocation request.  Even unfulfilled
16436   ** requests are counted */
16437   if( (u32)nByte>mem5.maxRequest ){
16438     mem5.maxRequest = nByte;
16439   }
16440 
16441   /* Abort if the requested allocation size is larger than the largest
16442   ** power of two that we can represent using 32-bit signed integers.
16443   */
16444   if( nByte > 0x40000000 ){
16445     return 0;
16446   }
16447 
16448   /* Round nByte up to the next valid power of two */
16449   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16450 
16451   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16452   ** block.  If not, then split a block of the next larger power of
16453   ** two in order to create a new free block of size iLogsize.
16454   */
16455   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16456   if( iBin>LOGMAX ){
16457     testcase( sqlite3GlobalConfig.xLog!=0 );
16458     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16459     return 0;
16460   }
16461   i = memsys5UnlinkFirst(iBin);
16462   while( iBin>iLogsize ){
16463     int newSize;
16464 
16465     iBin--;
16466     newSize = 1 << iBin;
16467     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16468     memsys5Link(i+newSize, iBin);
16469   }
16470   mem5.aCtrl[i] = iLogsize;
16471 
16472   /* Update allocator performance statistics. */
16473   mem5.nAlloc++;
16474   mem5.totalAlloc += iFullSz;
16475   mem5.totalExcess += iFullSz - nByte;
16476   mem5.currentCount++;
16477   mem5.currentOut += iFullSz;
16478   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16479   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16480 
16481   /* Return a pointer to the allocated memory. */
16482   return (void*)&mem5.zPool[i*mem5.szAtom];
16483 }
16484 
16485 /*
16486 ** Free an outstanding memory allocation.
16487 */
memsys5FreeUnsafe(void * pOld)16488 static void memsys5FreeUnsafe(void *pOld){
16489   u32 size, iLogsize;
16490   int iBlock;
16491 
16492   /* Set iBlock to the index of the block pointed to by pOld in
16493   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16494   */
16495   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16496 
16497   /* Check that the pointer pOld points to a valid, non-free block. */
16498   assert( iBlock>=0 && iBlock<mem5.nBlock );
16499   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16500   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16501 
16502   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16503   size = 1<<iLogsize;
16504   assert( iBlock+size-1<(u32)mem5.nBlock );
16505 
16506   mem5.aCtrl[iBlock] |= CTRL_FREE;
16507   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16508   assert( mem5.currentCount>0 );
16509   assert( mem5.currentOut>=(size*mem5.szAtom) );
16510   mem5.currentCount--;
16511   mem5.currentOut -= size*mem5.szAtom;
16512   assert( mem5.currentOut>0 || mem5.currentCount==0 );
16513   assert( mem5.currentCount>0 || mem5.currentOut==0 );
16514 
16515   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16516   while( ALWAYS(iLogsize<LOGMAX) ){
16517     int iBuddy;
16518     if( (iBlock>>iLogsize) & 1 ){
16519       iBuddy = iBlock - size;
16520     }else{
16521       iBuddy = iBlock + size;
16522     }
16523     assert( iBuddy>=0 );
16524     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
16525     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
16526     memsys5Unlink(iBuddy, iLogsize);
16527     iLogsize++;
16528     if( iBuddy<iBlock ){
16529       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
16530       mem5.aCtrl[iBlock] = 0;
16531       iBlock = iBuddy;
16532     }else{
16533       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
16534       mem5.aCtrl[iBuddy] = 0;
16535     }
16536     size *= 2;
16537   }
16538   memsys5Link(iBlock, iLogsize);
16539 }
16540 
16541 /*
16542 ** Allocate nBytes of memory
16543 */
memsys5Malloc(int nBytes)16544 static void *memsys5Malloc(int nBytes){
16545   sqlite3_int64 *p = 0;
16546   if( nBytes>0 ){
16547     memsys5Enter();
16548     p = memsys5MallocUnsafe(nBytes);
16549     memsys5Leave();
16550   }
16551   return (void*)p;
16552 }
16553 
16554 /*
16555 ** Free memory.
16556 **
16557 ** The outer layer memory allocator prevents this routine from
16558 ** being called with pPrior==0.
16559 */
memsys5Free(void * pPrior)16560 static void memsys5Free(void *pPrior){
16561   assert( pPrior!=0 );
16562   memsys5Enter();
16563   memsys5FreeUnsafe(pPrior);
16564   memsys5Leave();
16565 }
16566 
16567 /*
16568 ** Change the size of an existing memory allocation.
16569 **
16570 ** The outer layer memory allocator prevents this routine from
16571 ** being called with pPrior==0.
16572 **
16573 ** nBytes is always a value obtained from a prior call to
16574 ** memsys5Round().  Hence nBytes is always a non-negative power
16575 ** of two.  If nBytes==0 that means that an oversize allocation
16576 ** (an allocation larger than 0x40000000) was requested and this
16577 ** routine should return 0 without freeing pPrior.
16578 */
memsys5Realloc(void * pPrior,int nBytes)16579 static void *memsys5Realloc(void *pPrior, int nBytes){
16580   int nOld;
16581   void *p;
16582   assert( pPrior!=0 );
16583   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
16584   assert( nBytes>=0 );
16585   if( nBytes==0 ){
16586     return 0;
16587   }
16588   nOld = memsys5Size(pPrior);
16589   if( nBytes<=nOld ){
16590     return pPrior;
16591   }
16592   memsys5Enter();
16593   p = memsys5MallocUnsafe(nBytes);
16594   if( p ){
16595     memcpy(p, pPrior, nOld);
16596     memsys5FreeUnsafe(pPrior);
16597   }
16598   memsys5Leave();
16599   return p;
16600 }
16601 
16602 /*
16603 ** Round up a request size to the next valid allocation size.  If
16604 ** the allocation is too large to be handled by this allocation system,
16605 ** return 0.
16606 **
16607 ** All allocations must be a power of two and must be expressed by a
16608 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
16609 ** or 1073741824 bytes.
16610 */
memsys5Roundup(int n)16611 static int memsys5Roundup(int n){
16612   int iFullSz;
16613   if( n > 0x40000000 ) return 0;
16614   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
16615   return iFullSz;
16616 }
16617 
16618 /*
16619 ** Return the ceiling of the logarithm base 2 of iValue.
16620 **
16621 ** Examples:   memsys5Log(1) -> 0
16622 **             memsys5Log(2) -> 1
16623 **             memsys5Log(4) -> 2
16624 **             memsys5Log(5) -> 3
16625 **             memsys5Log(8) -> 3
16626 **             memsys5Log(9) -> 4
16627 */
memsys5Log(int iValue)16628 static int memsys5Log(int iValue){
16629   int iLog;
16630   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
16631   return iLog;
16632 }
16633 
16634 /*
16635 ** Initialize the memory allocator.
16636 **
16637 ** This routine is not threadsafe.  The caller must be holding a mutex
16638 ** to prevent multiple threads from entering at the same time.
16639 */
memsys5Init(void * NotUsed)16640 static int memsys5Init(void *NotUsed){
16641   int ii;            /* Loop counter */
16642   int nByte;         /* Number of bytes of memory available to this allocator */
16643   u8 *zByte;         /* Memory usable by this allocator */
16644   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
16645   int iOffset;       /* An offset into mem5.aCtrl[] */
16646 
16647   UNUSED_PARAMETER(NotUsed);
16648 
16649   /* For the purposes of this routine, disable the mutex */
16650   mem5.mutex = 0;
16651 
16652   /* The size of a Mem5Link object must be a power of two.  Verify that
16653   ** this is case.
16654   */
16655   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
16656 
16657   nByte = sqlite3GlobalConfig.nHeap;
16658   zByte = (u8*)sqlite3GlobalConfig.pHeap;
16659   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
16660 
16661   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
16662   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
16663   mem5.szAtom = (1<<nMinLog);
16664   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
16665     mem5.szAtom = mem5.szAtom << 1;
16666   }
16667 
16668   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
16669   mem5.zPool = zByte;
16670   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
16671 
16672   for(ii=0; ii<=LOGMAX; ii++){
16673     mem5.aiFreelist[ii] = -1;
16674   }
16675 
16676   iOffset = 0;
16677   for(ii=LOGMAX; ii>=0; ii--){
16678     int nAlloc = (1<<ii);
16679     if( (iOffset+nAlloc)<=mem5.nBlock ){
16680       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
16681       memsys5Link(iOffset, ii);
16682       iOffset += nAlloc;
16683     }
16684     assert((iOffset+nAlloc)>mem5.nBlock);
16685   }
16686 
16687   /* If a mutex is required for normal operation, allocate one */
16688   if( sqlite3GlobalConfig.bMemstat==0 ){
16689     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16690   }
16691 
16692   return SQLITE_OK;
16693 }
16694 
16695 /*
16696 ** Deinitialize this module.
16697 */
memsys5Shutdown(void * NotUsed)16698 static void memsys5Shutdown(void *NotUsed){
16699   UNUSED_PARAMETER(NotUsed);
16700   mem5.mutex = 0;
16701   return;
16702 }
16703 
16704 #ifdef SQLITE_TEST
16705 /*
16706 ** Open the file indicated and write a log of all unfreed memory
16707 ** allocations into that log.
16708 */
sqlite3Memsys5Dump(const char * zFilename)16709 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
16710   FILE *out;
16711   int i, j, n;
16712   int nMinLog;
16713 
16714   if( zFilename==0 || zFilename[0]==0 ){
16715     out = stdout;
16716   }else{
16717     out = fopen(zFilename, "w");
16718     if( out==0 ){
16719       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16720                       zFilename);
16721       return;
16722     }
16723   }
16724   memsys5Enter();
16725   nMinLog = memsys5Log(mem5.szAtom);
16726   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
16727     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
16728     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
16729   }
16730   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
16731   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
16732   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
16733   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
16734   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
16735   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
16736   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
16737   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
16738   memsys5Leave();
16739   if( out==stdout ){
16740     fflush(stdout);
16741   }else{
16742     fclose(out);
16743   }
16744 }
16745 #endif
16746 
16747 /*
16748 ** This routine is the only routine in this file with external
16749 ** linkage. It returns a pointer to a static sqlite3_mem_methods
16750 ** struct populated with the memsys5 methods.
16751 */
sqlite3MemGetMemsys5(void)16752 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
16753   static const sqlite3_mem_methods memsys5Methods = {
16754      memsys5Malloc,
16755      memsys5Free,
16756      memsys5Realloc,
16757      memsys5Size,
16758      memsys5Roundup,
16759      memsys5Init,
16760      memsys5Shutdown,
16761      0
16762   };
16763   return &memsys5Methods;
16764 }
16765 
16766 #endif /* SQLITE_ENABLE_MEMSYS5 */
16767 
16768 /************** End of mem5.c ************************************************/
16769 /************** Begin file mutex.c *******************************************/
16770 /*
16771 ** 2007 August 14
16772 **
16773 ** The author disclaims copyright to this source code.  In place of
16774 ** a legal notice, here is a blessing:
16775 **
16776 **    May you do good and not evil.
16777 **    May you find forgiveness for yourself and forgive others.
16778 **    May you share freely, never taking more than you give.
16779 **
16780 *************************************************************************
16781 ** This file contains the C functions that implement mutexes.
16782 **
16783 ** This file contains code that is common across all mutex implementations.
16784 */
16785 
16786 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
16787 /*
16788 ** For debugging purposes, record when the mutex subsystem is initialized
16789 ** and uninitialized so that we can assert() if there is an attempt to
16790 ** allocate a mutex while the system is uninitialized.
16791 */
16792 static SQLITE_WSD int mutexIsInit = 0;
16793 #endif /* SQLITE_DEBUG */
16794 
16795 
16796 #ifndef SQLITE_MUTEX_OMIT
16797 /*
16798 ** Initialize the mutex system.
16799 */
sqlite3MutexInit(void)16800 SQLITE_PRIVATE int sqlite3MutexInit(void){
16801   int rc = SQLITE_OK;
16802   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
16803     /* If the xMutexAlloc method has not been set, then the user did not
16804     ** install a mutex implementation via sqlite3_config() prior to
16805     ** sqlite3_initialize() being called. This block copies pointers to
16806     ** the default implementation into the sqlite3GlobalConfig structure.
16807     */
16808     sqlite3_mutex_methods const *pFrom;
16809     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
16810 
16811     if( sqlite3GlobalConfig.bCoreMutex ){
16812       pFrom = sqlite3DefaultMutex();
16813     }else{
16814       pFrom = sqlite3NoopMutex();
16815     }
16816     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
16817     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
16818            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
16819     pTo->xMutexAlloc = pFrom->xMutexAlloc;
16820   }
16821   rc = sqlite3GlobalConfig.mutex.xMutexInit();
16822 
16823 #ifdef SQLITE_DEBUG
16824   GLOBAL(int, mutexIsInit) = 1;
16825 #endif
16826 
16827   return rc;
16828 }
16829 
16830 /*
16831 ** Shutdown the mutex system. This call frees resources allocated by
16832 ** sqlite3MutexInit().
16833 */
sqlite3MutexEnd(void)16834 SQLITE_PRIVATE int sqlite3MutexEnd(void){
16835   int rc = SQLITE_OK;
16836   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
16837     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
16838   }
16839 
16840 #ifdef SQLITE_DEBUG
16841   GLOBAL(int, mutexIsInit) = 0;
16842 #endif
16843 
16844   return rc;
16845 }
16846 
16847 /*
16848 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
16849 */
sqlite3_mutex_alloc(int id)16850 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
16851 #ifndef SQLITE_OMIT_AUTOINIT
16852   if( sqlite3_initialize() ) return 0;
16853 #endif
16854   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16855 }
16856 
sqlite3MutexAlloc(int id)16857 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
16858   if( !sqlite3GlobalConfig.bCoreMutex ){
16859     return 0;
16860   }
16861   assert( GLOBAL(int, mutexIsInit) );
16862   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
16863 }
16864 
16865 /*
16866 ** Free a dynamic mutex.
16867 */
sqlite3_mutex_free(sqlite3_mutex * p)16868 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
16869   if( p ){
16870     sqlite3GlobalConfig.mutex.xMutexFree(p);
16871   }
16872 }
16873 
16874 /*
16875 ** Obtain the mutex p. If some other thread already has the mutex, block
16876 ** until it can be obtained.
16877 */
sqlite3_mutex_enter(sqlite3_mutex * p)16878 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
16879   if( p ){
16880     sqlite3GlobalConfig.mutex.xMutexEnter(p);
16881   }
16882 }
16883 
16884 /*
16885 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
16886 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
16887 */
sqlite3_mutex_try(sqlite3_mutex * p)16888 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
16889   int rc = SQLITE_OK;
16890   if( p ){
16891     return sqlite3GlobalConfig.mutex.xMutexTry(p);
16892   }
16893   return rc;
16894 }
16895 
16896 /*
16897 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
16898 ** entered by the same thread.  The behavior is undefined if the mutex
16899 ** is not currently entered. If a NULL pointer is passed as an argument
16900 ** this function is a no-op.
16901 */
sqlite3_mutex_leave(sqlite3_mutex * p)16902 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
16903   if( p ){
16904     sqlite3GlobalConfig.mutex.xMutexLeave(p);
16905   }
16906 }
16907 
16908 #ifndef NDEBUG
16909 /*
16910 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
16911 ** intended for use inside assert() statements.
16912 */
sqlite3_mutex_held(sqlite3_mutex * p)16913 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
16914   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
16915 }
sqlite3_mutex_notheld(sqlite3_mutex * p)16916 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
16917   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
16918 }
16919 #endif
16920 
16921 #endif /* SQLITE_MUTEX_OMIT */
16922 
16923 /************** End of mutex.c ***********************************************/
16924 /************** Begin file mutex_noop.c **************************************/
16925 /*
16926 ** 2008 October 07
16927 **
16928 ** The author disclaims copyright to this source code.  In place of
16929 ** a legal notice, here is a blessing:
16930 **
16931 **    May you do good and not evil.
16932 **    May you find forgiveness for yourself and forgive others.
16933 **    May you share freely, never taking more than you give.
16934 **
16935 *************************************************************************
16936 ** This file contains the C functions that implement mutexes.
16937 **
16938 ** This implementation in this file does not provide any mutual
16939 ** exclusion and is thus suitable for use only in applications
16940 ** that use SQLite in a single thread.  The routines defined
16941 ** here are place-holders.  Applications can substitute working
16942 ** mutex routines at start-time using the
16943 **
16944 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
16945 **
16946 ** interface.
16947 **
16948 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
16949 ** that does error checking on mutexes to make sure they are being
16950 ** called correctly.
16951 */
16952 
16953 #ifndef SQLITE_MUTEX_OMIT
16954 
16955 #ifndef SQLITE_DEBUG
16956 /*
16957 ** Stub routines for all mutex methods.
16958 **
16959 ** This routines provide no mutual exclusion or error checking.
16960 */
noopMutexInit(void)16961 static int noopMutexInit(void){ return SQLITE_OK; }
noopMutexEnd(void)16962 static int noopMutexEnd(void){ return SQLITE_OK; }
noopMutexAlloc(int id)16963 static sqlite3_mutex *noopMutexAlloc(int id){
16964   UNUSED_PARAMETER(id);
16965   return (sqlite3_mutex*)8;
16966 }
noopMutexFree(sqlite3_mutex * p)16967 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
noopMutexEnter(sqlite3_mutex * p)16968 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
noopMutexTry(sqlite3_mutex * p)16969 static int noopMutexTry(sqlite3_mutex *p){
16970   UNUSED_PARAMETER(p);
16971   return SQLITE_OK;
16972 }
noopMutexLeave(sqlite3_mutex * p)16973 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
16974 
sqlite3NoopMutex(void)16975 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
16976   static const sqlite3_mutex_methods sMutex = {
16977     noopMutexInit,
16978     noopMutexEnd,
16979     noopMutexAlloc,
16980     noopMutexFree,
16981     noopMutexEnter,
16982     noopMutexTry,
16983     noopMutexLeave,
16984 
16985     0,
16986     0,
16987   };
16988 
16989   return &sMutex;
16990 }
16991 #endif /* !SQLITE_DEBUG */
16992 
16993 #ifdef SQLITE_DEBUG
16994 /*
16995 ** In this implementation, error checking is provided for testing
16996 ** and debugging purposes.  The mutexes still do not provide any
16997 ** mutual exclusion.
16998 */
16999 
17000 /*
17001 ** The mutex object
17002 */
17003 typedef struct sqlite3_debug_mutex {
17004   int id;     /* The mutex type */
17005   int cnt;    /* Number of entries without a matching leave */
17006 } sqlite3_debug_mutex;
17007 
17008 /*
17009 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17010 ** intended for use inside assert() statements.
17011 */
debugMutexHeld(sqlite3_mutex * pX)17012 static int debugMutexHeld(sqlite3_mutex *pX){
17013   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17014   return p==0 || p->cnt>0;
17015 }
debugMutexNotheld(sqlite3_mutex * pX)17016 static int debugMutexNotheld(sqlite3_mutex *pX){
17017   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17018   return p==0 || p->cnt==0;
17019 }
17020 
17021 /*
17022 ** Initialize and deinitialize the mutex subsystem.
17023 */
debugMutexInit(void)17024 static int debugMutexInit(void){ return SQLITE_OK; }
debugMutexEnd(void)17025 static int debugMutexEnd(void){ return SQLITE_OK; }
17026 
17027 /*
17028 ** The sqlite3_mutex_alloc() routine allocates a new
17029 ** mutex and returns a pointer to it.  If it returns NULL
17030 ** that means that a mutex could not be allocated.
17031 */
debugMutexAlloc(int id)17032 static sqlite3_mutex *debugMutexAlloc(int id){
17033   static sqlite3_debug_mutex aStatic[6];
17034   sqlite3_debug_mutex *pNew = 0;
17035   switch( id ){
17036     case SQLITE_MUTEX_FAST:
17037     case SQLITE_MUTEX_RECURSIVE: {
17038       pNew = sqlite3Malloc(sizeof(*pNew));
17039       if( pNew ){
17040         pNew->id = id;
17041         pNew->cnt = 0;
17042       }
17043       break;
17044     }
17045     default: {
17046       assert( id-2 >= 0 );
17047       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17048       pNew = &aStatic[id-2];
17049       pNew->id = id;
17050       break;
17051     }
17052   }
17053   return (sqlite3_mutex*)pNew;
17054 }
17055 
17056 /*
17057 ** This routine deallocates a previously allocated mutex.
17058 */
debugMutexFree(sqlite3_mutex * pX)17059 static void debugMutexFree(sqlite3_mutex *pX){
17060   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17061   assert( p->cnt==0 );
17062   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17063   sqlite3_free(p);
17064 }
17065 
17066 /*
17067 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17068 ** to enter a mutex.  If another thread is already within the mutex,
17069 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17070 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17071 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17072 ** be entered multiple times by the same thread.  In such cases the,
17073 ** mutex must be exited an equal number of times before another thread
17074 ** can enter.  If the same thread tries to enter any other kind of mutex
17075 ** more than once, the behavior is undefined.
17076 */
debugMutexEnter(sqlite3_mutex * pX)17077 static void debugMutexEnter(sqlite3_mutex *pX){
17078   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17079   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17080   p->cnt++;
17081 }
debugMutexTry(sqlite3_mutex * pX)17082 static int debugMutexTry(sqlite3_mutex *pX){
17083   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17084   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17085   p->cnt++;
17086   return SQLITE_OK;
17087 }
17088 
17089 /*
17090 ** The sqlite3_mutex_leave() routine exits a mutex that was
17091 ** previously entered by the same thread.  The behavior
17092 ** is undefined if the mutex is not currently entered or
17093 ** is not currently allocated.  SQLite will never do either.
17094 */
debugMutexLeave(sqlite3_mutex * pX)17095 static void debugMutexLeave(sqlite3_mutex *pX){
17096   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17097   assert( debugMutexHeld(pX) );
17098   p->cnt--;
17099   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17100 }
17101 
sqlite3NoopMutex(void)17102 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17103   static const sqlite3_mutex_methods sMutex = {
17104     debugMutexInit,
17105     debugMutexEnd,
17106     debugMutexAlloc,
17107     debugMutexFree,
17108     debugMutexEnter,
17109     debugMutexTry,
17110     debugMutexLeave,
17111 
17112     debugMutexHeld,
17113     debugMutexNotheld
17114   };
17115 
17116   return &sMutex;
17117 }
17118 #endif /* SQLITE_DEBUG */
17119 
17120 /*
17121 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17122 ** is used regardless of the run-time threadsafety setting.
17123 */
17124 #ifdef SQLITE_MUTEX_NOOP
sqlite3DefaultMutex(void)17125 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17126   return sqlite3NoopMutex();
17127 }
17128 #endif /* SQLITE_MUTEX_NOOP */
17129 #endif /* SQLITE_MUTEX_OMIT */
17130 
17131 /************** End of mutex_noop.c ******************************************/
17132 /************** Begin file mutex_os2.c ***************************************/
17133 /*
17134 ** 2007 August 28
17135 **
17136 ** The author disclaims copyright to this source code.  In place of
17137 ** a legal notice, here is a blessing:
17138 **
17139 **    May you do good and not evil.
17140 **    May you find forgiveness for yourself and forgive others.
17141 **    May you share freely, never taking more than you give.
17142 **
17143 *************************************************************************
17144 ** This file contains the C functions that implement mutexes for OS/2
17145 */
17146 
17147 /*
17148 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17149 ** See the mutex.h file for details.
17150 */
17151 #ifdef SQLITE_MUTEX_OS2
17152 
17153 /********************** OS/2 Mutex Implementation **********************
17154 **
17155 ** This implementation of mutexes is built using the OS/2 API.
17156 */
17157 
17158 /*
17159 ** The mutex object
17160 ** Each recursive mutex is an instance of the following structure.
17161 */
17162 struct sqlite3_mutex {
17163   HMTX mutex;       /* Mutex controlling the lock */
17164   int  id;          /* Mutex type */
17165 #ifdef SQLITE_DEBUG
17166  int   trace;       /* True to trace changes */
17167 #endif
17168 };
17169 
17170 #ifdef SQLITE_DEBUG
17171 #define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17172 #else
17173 #define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17174 #endif
17175 
17176 /*
17177 ** Initialize and deinitialize the mutex subsystem.
17178 */
os2MutexInit(void)17179 static int os2MutexInit(void){ return SQLITE_OK; }
os2MutexEnd(void)17180 static int os2MutexEnd(void){ return SQLITE_OK; }
17181 
17182 /*
17183 ** The sqlite3_mutex_alloc() routine allocates a new
17184 ** mutex and returns a pointer to it.  If it returns NULL
17185 ** that means that a mutex could not be allocated.
17186 ** SQLite will unwind its stack and return an error.  The argument
17187 ** to sqlite3_mutex_alloc() is one of these integer constants:
17188 **
17189 ** <ul>
17190 ** <li>  SQLITE_MUTEX_FAST
17191 ** <li>  SQLITE_MUTEX_RECURSIVE
17192 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17193 ** <li>  SQLITE_MUTEX_STATIC_MEM
17194 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17195 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17196 ** <li>  SQLITE_MUTEX_STATIC_LRU
17197 ** <li>  SQLITE_MUTEX_STATIC_LRU2
17198 ** </ul>
17199 **
17200 ** The first two constants cause sqlite3_mutex_alloc() to create
17201 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17202 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17203 ** The mutex implementation does not need to make a distinction
17204 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17205 ** not want to.  But SQLite will only request a recursive mutex in
17206 ** cases where it really needs one.  If a faster non-recursive mutex
17207 ** implementation is available on the host platform, the mutex subsystem
17208 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17209 **
17210 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17211 ** a pointer to a static preexisting mutex.  Six static mutexes are
17212 ** used by the current version of SQLite.  Future versions of SQLite
17213 ** may add additional static mutexes.  Static mutexes are for internal
17214 ** use by SQLite only.  Applications that use SQLite mutexes should
17215 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17216 ** SQLITE_MUTEX_RECURSIVE.
17217 **
17218 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17219 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17220 ** returns a different mutex on every call.  But for the static
17221 ** mutex types, the same mutex is returned on every call that has
17222 ** the same type number.
17223 */
os2MutexAlloc(int iType)17224 static sqlite3_mutex *os2MutexAlloc(int iType){
17225   sqlite3_mutex *p = NULL;
17226   switch( iType ){
17227     case SQLITE_MUTEX_FAST:
17228     case SQLITE_MUTEX_RECURSIVE: {
17229       p = sqlite3MallocZero( sizeof(*p) );
17230       if( p ){
17231         p->id = iType;
17232         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17233           sqlite3_free( p );
17234           p = NULL;
17235         }
17236       }
17237       break;
17238     }
17239     default: {
17240       static volatile int isInit = 0;
17241       static sqlite3_mutex staticMutexes[6] = {
17242         SQLITE3_MUTEX_INITIALIZER,
17243         SQLITE3_MUTEX_INITIALIZER,
17244         SQLITE3_MUTEX_INITIALIZER,
17245         SQLITE3_MUTEX_INITIALIZER,
17246         SQLITE3_MUTEX_INITIALIZER,
17247         SQLITE3_MUTEX_INITIALIZER,
17248       };
17249       if ( !isInit ){
17250         APIRET rc;
17251         PTIB ptib;
17252         PPIB ppib;
17253         HMTX mutex;
17254         char name[32];
17255         DosGetInfoBlocks( &ptib, &ppib );
17256         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17257                           ppib->pib_ulpid );
17258         while( !isInit ){
17259           mutex = 0;
17260           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17261           if( rc == NO_ERROR ){
17262             unsigned int i;
17263             if( !isInit ){
17264               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17265                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17266               }
17267               isInit = 1;
17268             }
17269             DosCloseMutexSem( mutex );
17270           }else if( rc == ERROR_DUPLICATE_NAME ){
17271             DosSleep( 1 );
17272           }else{
17273             return p;
17274           }
17275         }
17276       }
17277       assert( iType-2 >= 0 );
17278       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17279       p = &staticMutexes[iType-2];
17280       p->id = iType;
17281       break;
17282     }
17283   }
17284   return p;
17285 }
17286 
17287 
17288 /*
17289 ** This routine deallocates a previously allocated mutex.
17290 ** SQLite is careful to deallocate every mutex that it allocates.
17291 */
os2MutexFree(sqlite3_mutex * p)17292 static void os2MutexFree(sqlite3_mutex *p){
17293 #ifdef SQLITE_DEBUG
17294   TID tid;
17295   PID pid;
17296   ULONG ulCount;
17297   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17298   assert( ulCount==0 );
17299   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17300 #endif
17301   DosCloseMutexSem( p->mutex );
17302   sqlite3_free( p );
17303 }
17304 
17305 #ifdef SQLITE_DEBUG
17306 /*
17307 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17308 ** intended for use inside assert() statements.
17309 */
os2MutexHeld(sqlite3_mutex * p)17310 static int os2MutexHeld(sqlite3_mutex *p){
17311   TID tid;
17312   PID pid;
17313   ULONG ulCount;
17314   PTIB ptib;
17315   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17316   if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17317     return 0;
17318   DosGetInfoBlocks(&ptib, NULL);
17319   return tid==ptib->tib_ptib2->tib2_ultid;
17320 }
os2MutexNotheld(sqlite3_mutex * p)17321 static int os2MutexNotheld(sqlite3_mutex *p){
17322   TID tid;
17323   PID pid;
17324   ULONG ulCount;
17325   PTIB ptib;
17326   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17327   if( ulCount==0 )
17328     return 1;
17329   DosGetInfoBlocks(&ptib, NULL);
17330   return tid!=ptib->tib_ptib2->tib2_ultid;
17331 }
os2MutexTrace(sqlite3_mutex * p,char * pAction)17332 static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17333   TID   tid;
17334   PID   pid;
17335   ULONG ulCount;
17336   DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17337   printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17338 }
17339 #endif
17340 
17341 /*
17342 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17343 ** to enter a mutex.  If another thread is already within the mutex,
17344 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17345 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17346 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17347 ** be entered multiple times by the same thread.  In such cases the,
17348 ** mutex must be exited an equal number of times before another thread
17349 ** can enter.  If the same thread tries to enter any other kind of mutex
17350 ** more than once, the behavior is undefined.
17351 */
os2MutexEnter(sqlite3_mutex * p)17352 static void os2MutexEnter(sqlite3_mutex *p){
17353   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17354   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17355 #ifdef SQLITE_DEBUG
17356   if( p->trace ) os2MutexTrace(p, "enter");
17357 #endif
17358 }
os2MutexTry(sqlite3_mutex * p)17359 static int os2MutexTry(sqlite3_mutex *p){
17360   int rc = SQLITE_BUSY;
17361   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17362   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17363     rc = SQLITE_OK;
17364 #ifdef SQLITE_DEBUG
17365     if( p->trace ) os2MutexTrace(p, "try");
17366 #endif
17367   }
17368   return rc;
17369 }
17370 
17371 /*
17372 ** The sqlite3_mutex_leave() routine exits a mutex that was
17373 ** previously entered by the same thread.  The behavior
17374 ** is undefined if the mutex is not currently entered or
17375 ** is not currently allocated.  SQLite will never do either.
17376 */
os2MutexLeave(sqlite3_mutex * p)17377 static void os2MutexLeave(sqlite3_mutex *p){
17378   assert( os2MutexHeld(p) );
17379   DosReleaseMutexSem(p->mutex);
17380 #ifdef SQLITE_DEBUG
17381   if( p->trace ) os2MutexTrace(p, "leave");
17382 #endif
17383 }
17384 
sqlite3DefaultMutex(void)17385 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17386   static const sqlite3_mutex_methods sMutex = {
17387     os2MutexInit,
17388     os2MutexEnd,
17389     os2MutexAlloc,
17390     os2MutexFree,
17391     os2MutexEnter,
17392     os2MutexTry,
17393     os2MutexLeave,
17394 #ifdef SQLITE_DEBUG
17395     os2MutexHeld,
17396     os2MutexNotheld
17397 #else
17398     0,
17399     0
17400 #endif
17401   };
17402 
17403   return &sMutex;
17404 }
17405 #endif /* SQLITE_MUTEX_OS2 */
17406 
17407 /************** End of mutex_os2.c *******************************************/
17408 /************** Begin file mutex_unix.c **************************************/
17409 /*
17410 ** 2007 August 28
17411 **
17412 ** The author disclaims copyright to this source code.  In place of
17413 ** a legal notice, here is a blessing:
17414 **
17415 **    May you do good and not evil.
17416 **    May you find forgiveness for yourself and forgive others.
17417 **    May you share freely, never taking more than you give.
17418 **
17419 *************************************************************************
17420 ** This file contains the C functions that implement mutexes for pthreads
17421 */
17422 
17423 /*
17424 ** The code in this file is only used if we are compiling threadsafe
17425 ** under unix with pthreads.
17426 **
17427 ** Note that this implementation requires a version of pthreads that
17428 ** supports recursive mutexes.
17429 */
17430 #ifdef SQLITE_MUTEX_PTHREADS
17431 
17432 #include <pthread.h>
17433 
17434 /*
17435 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17436 ** are necessary under two condidtions:  (1) Debug builds and (2) using
17437 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
17438 */
17439 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17440 # define SQLITE_MUTEX_NREF 1
17441 #else
17442 # define SQLITE_MUTEX_NREF 0
17443 #endif
17444 
17445 /*
17446 ** Each recursive mutex is an instance of the following structure.
17447 */
17448 struct sqlite3_mutex {
17449   pthread_mutex_t mutex;     /* Mutex controlling the lock */
17450 #if SQLITE_MUTEX_NREF
17451   int id;                    /* Mutex type */
17452   volatile int nRef;         /* Number of entrances */
17453   volatile pthread_t owner;  /* Thread that is within this mutex */
17454   int trace;                 /* True to trace changes */
17455 #endif
17456 };
17457 #if SQLITE_MUTEX_NREF
17458 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17459 #else
17460 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17461 #endif
17462 
17463 /*
17464 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17465 ** intended for use only inside assert() statements.  On some platforms,
17466 ** there might be race conditions that can cause these routines to
17467 ** deliver incorrect results.  In particular, if pthread_equal() is
17468 ** not an atomic operation, then these routines might delivery
17469 ** incorrect results.  On most platforms, pthread_equal() is a
17470 ** comparison of two integers and is therefore atomic.  But we are
17471 ** told that HPUX is not such a platform.  If so, then these routines
17472 ** will not always work correctly on HPUX.
17473 **
17474 ** On those platforms where pthread_equal() is not atomic, SQLite
17475 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17476 ** make sure no assert() statements are evaluated and hence these
17477 ** routines are never called.
17478 */
17479 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
pthreadMutexHeld(sqlite3_mutex * p)17480 static int pthreadMutexHeld(sqlite3_mutex *p){
17481   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17482 }
pthreadMutexNotheld(sqlite3_mutex * p)17483 static int pthreadMutexNotheld(sqlite3_mutex *p){
17484   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17485 }
17486 #endif
17487 
17488 /*
17489 ** Initialize and deinitialize the mutex subsystem.
17490 */
pthreadMutexInit(void)17491 static int pthreadMutexInit(void){ return SQLITE_OK; }
pthreadMutexEnd(void)17492 static int pthreadMutexEnd(void){ return SQLITE_OK; }
17493 
17494 /*
17495 ** The sqlite3_mutex_alloc() routine allocates a new
17496 ** mutex and returns a pointer to it.  If it returns NULL
17497 ** that means that a mutex could not be allocated.  SQLite
17498 ** will unwind its stack and return an error.  The argument
17499 ** to sqlite3_mutex_alloc() is one of these integer constants:
17500 **
17501 ** <ul>
17502 ** <li>  SQLITE_MUTEX_FAST
17503 ** <li>  SQLITE_MUTEX_RECURSIVE
17504 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17505 ** <li>  SQLITE_MUTEX_STATIC_MEM
17506 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17507 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17508 ** <li>  SQLITE_MUTEX_STATIC_LRU
17509 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17510 ** </ul>
17511 **
17512 ** The first two constants cause sqlite3_mutex_alloc() to create
17513 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17514 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17515 ** The mutex implementation does not need to make a distinction
17516 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17517 ** not want to.  But SQLite will only request a recursive mutex in
17518 ** cases where it really needs one.  If a faster non-recursive mutex
17519 ** implementation is available on the host platform, the mutex subsystem
17520 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17521 **
17522 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17523 ** a pointer to a static preexisting mutex.  Six static mutexes are
17524 ** used by the current version of SQLite.  Future versions of SQLite
17525 ** may add additional static mutexes.  Static mutexes are for internal
17526 ** use by SQLite only.  Applications that use SQLite mutexes should
17527 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17528 ** SQLITE_MUTEX_RECURSIVE.
17529 **
17530 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17531 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17532 ** returns a different mutex on every call.  But for the static
17533 ** mutex types, the same mutex is returned on every call that has
17534 ** the same type number.
17535 */
pthreadMutexAlloc(int iType)17536 static sqlite3_mutex *pthreadMutexAlloc(int iType){
17537   static sqlite3_mutex staticMutexes[] = {
17538     SQLITE3_MUTEX_INITIALIZER,
17539     SQLITE3_MUTEX_INITIALIZER,
17540     SQLITE3_MUTEX_INITIALIZER,
17541     SQLITE3_MUTEX_INITIALIZER,
17542     SQLITE3_MUTEX_INITIALIZER,
17543     SQLITE3_MUTEX_INITIALIZER
17544   };
17545   sqlite3_mutex *p;
17546   switch( iType ){
17547     case SQLITE_MUTEX_RECURSIVE: {
17548       p = sqlite3MallocZero( sizeof(*p) );
17549       if( p ){
17550 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17551         /* If recursive mutexes are not available, we will have to
17552         ** build our own.  See below. */
17553         pthread_mutex_init(&p->mutex, 0);
17554 #else
17555         /* Use a recursive mutex if it is available */
17556         pthread_mutexattr_t recursiveAttr;
17557         pthread_mutexattr_init(&recursiveAttr);
17558         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
17559         pthread_mutex_init(&p->mutex, &recursiveAttr);
17560         pthread_mutexattr_destroy(&recursiveAttr);
17561 #endif
17562 #if SQLITE_MUTEX_NREF
17563         p->id = iType;
17564 #endif
17565       }
17566       break;
17567     }
17568     case SQLITE_MUTEX_FAST: {
17569       p = sqlite3MallocZero( sizeof(*p) );
17570       if( p ){
17571 #if SQLITE_MUTEX_NREF
17572         p->id = iType;
17573 #endif
17574         pthread_mutex_init(&p->mutex, 0);
17575       }
17576       break;
17577     }
17578     default: {
17579       assert( iType-2 >= 0 );
17580       assert( iType-2 < ArraySize(staticMutexes) );
17581       p = &staticMutexes[iType-2];
17582 #if SQLITE_MUTEX_NREF
17583       p->id = iType;
17584 #endif
17585       break;
17586     }
17587   }
17588   return p;
17589 }
17590 
17591 
17592 /*
17593 ** This routine deallocates a previously
17594 ** allocated mutex.  SQLite is careful to deallocate every
17595 ** mutex that it allocates.
17596 */
pthreadMutexFree(sqlite3_mutex * p)17597 static void pthreadMutexFree(sqlite3_mutex *p){
17598   assert( p->nRef==0 );
17599   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17600   pthread_mutex_destroy(&p->mutex);
17601   sqlite3_free(p);
17602 }
17603 
17604 /*
17605 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17606 ** to enter a mutex.  If another thread is already within the mutex,
17607 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17608 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17609 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17610 ** be entered multiple times by the same thread.  In such cases the,
17611 ** mutex must be exited an equal number of times before another thread
17612 ** can enter.  If the same thread tries to enter any other kind of mutex
17613 ** more than once, the behavior is undefined.
17614 */
pthreadMutexEnter(sqlite3_mutex * p)17615 static void pthreadMutexEnter(sqlite3_mutex *p){
17616   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17617 
17618 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17619   /* If recursive mutexes are not available, then we have to grow
17620   ** our own.  This implementation assumes that pthread_equal()
17621   ** is atomic - that it cannot be deceived into thinking self
17622   ** and p->owner are equal if p->owner changes between two values
17623   ** that are not equal to self while the comparison is taking place.
17624   ** This implementation also assumes a coherent cache - that
17625   ** separate processes cannot read different values from the same
17626   ** address at the same time.  If either of these two conditions
17627   ** are not met, then the mutexes will fail and problems will result.
17628   */
17629   {
17630     pthread_t self = pthread_self();
17631     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17632       p->nRef++;
17633     }else{
17634       pthread_mutex_lock(&p->mutex);
17635       assert( p->nRef==0 );
17636       p->owner = self;
17637       p->nRef = 1;
17638     }
17639   }
17640 #else
17641   /* Use the built-in recursive mutexes if they are available.
17642   */
17643   pthread_mutex_lock(&p->mutex);
17644 #if SQLITE_MUTEX_NREF
17645   assert( p->nRef>0 || p->owner==0 );
17646   p->owner = pthread_self();
17647   p->nRef++;
17648 #endif
17649 #endif
17650 
17651 #ifdef SQLITE_DEBUG
17652   if( p->trace ){
17653     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17654   }
17655 #endif
17656 }
pthreadMutexTry(sqlite3_mutex * p)17657 static int pthreadMutexTry(sqlite3_mutex *p){
17658   int rc;
17659   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
17660 
17661 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17662   /* If recursive mutexes are not available, then we have to grow
17663   ** our own.  This implementation assumes that pthread_equal()
17664   ** is atomic - that it cannot be deceived into thinking self
17665   ** and p->owner are equal if p->owner changes between two values
17666   ** that are not equal to self while the comparison is taking place.
17667   ** This implementation also assumes a coherent cache - that
17668   ** separate processes cannot read different values from the same
17669   ** address at the same time.  If either of these two conditions
17670   ** are not met, then the mutexes will fail and problems will result.
17671   */
17672   {
17673     pthread_t self = pthread_self();
17674     if( p->nRef>0 && pthread_equal(p->owner, self) ){
17675       p->nRef++;
17676       rc = SQLITE_OK;
17677     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
17678       assert( p->nRef==0 );
17679       p->owner = self;
17680       p->nRef = 1;
17681       rc = SQLITE_OK;
17682     }else{
17683       rc = SQLITE_BUSY;
17684     }
17685   }
17686 #else
17687   /* Use the built-in recursive mutexes if they are available.
17688   */
17689   if( pthread_mutex_trylock(&p->mutex)==0 ){
17690 #if SQLITE_MUTEX_NREF
17691     p->owner = pthread_self();
17692     p->nRef++;
17693 #endif
17694     rc = SQLITE_OK;
17695   }else{
17696     rc = SQLITE_BUSY;
17697   }
17698 #endif
17699 
17700 #ifdef SQLITE_DEBUG
17701   if( rc==SQLITE_OK && p->trace ){
17702     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17703   }
17704 #endif
17705   return rc;
17706 }
17707 
17708 /*
17709 ** The sqlite3_mutex_leave() routine exits a mutex that was
17710 ** previously entered by the same thread.  The behavior
17711 ** is undefined if the mutex is not currently entered or
17712 ** is not currently allocated.  SQLite will never do either.
17713 */
pthreadMutexLeave(sqlite3_mutex * p)17714 static void pthreadMutexLeave(sqlite3_mutex *p){
17715   assert( pthreadMutexHeld(p) );
17716 #if SQLITE_MUTEX_NREF
17717   p->nRef--;
17718   if( p->nRef==0 ) p->owner = 0;
17719 #endif
17720   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
17721 
17722 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17723   if( p->nRef==0 ){
17724     pthread_mutex_unlock(&p->mutex);
17725   }
17726 #else
17727   pthread_mutex_unlock(&p->mutex);
17728 #endif
17729 
17730 #ifdef SQLITE_DEBUG
17731   if( p->trace ){
17732     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
17733   }
17734 #endif
17735 }
17736 
sqlite3DefaultMutex(void)17737 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17738   static const sqlite3_mutex_methods sMutex = {
17739     pthreadMutexInit,
17740     pthreadMutexEnd,
17741     pthreadMutexAlloc,
17742     pthreadMutexFree,
17743     pthreadMutexEnter,
17744     pthreadMutexTry,
17745     pthreadMutexLeave,
17746 #ifdef SQLITE_DEBUG
17747     pthreadMutexHeld,
17748     pthreadMutexNotheld
17749 #else
17750     0,
17751     0
17752 #endif
17753   };
17754 
17755   return &sMutex;
17756 }
17757 
17758 #endif /* SQLITE_MUTEX_PTHREAD */
17759 
17760 /************** End of mutex_unix.c ******************************************/
17761 /************** Begin file mutex_w32.c ***************************************/
17762 /*
17763 ** 2007 August 14
17764 **
17765 ** The author disclaims copyright to this source code.  In place of
17766 ** a legal notice, here is a blessing:
17767 **
17768 **    May you do good and not evil.
17769 **    May you find forgiveness for yourself and forgive others.
17770 **    May you share freely, never taking more than you give.
17771 **
17772 *************************************************************************
17773 ** This file contains the C functions that implement mutexes for win32
17774 */
17775 
17776 /*
17777 ** The code in this file is only used if we are compiling multithreaded
17778 ** on a win32 system.
17779 */
17780 #ifdef SQLITE_MUTEX_W32
17781 
17782 /*
17783 ** Each recursive mutex is an instance of the following structure.
17784 */
17785 struct sqlite3_mutex {
17786   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
17787   int id;                    /* Mutex type */
17788 #ifdef SQLITE_DEBUG
17789   volatile int nRef;         /* Number of enterances */
17790   volatile DWORD owner;      /* Thread holding this mutex */
17791   int trace;                 /* True to trace changes */
17792 #endif
17793 };
17794 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
17795 #ifdef SQLITE_DEBUG
17796 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
17797 #else
17798 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
17799 #endif
17800 
17801 /*
17802 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
17803 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
17804 **
17805 ** Here is an interesting observation:  Win95, Win98, and WinME lack
17806 ** the LockFileEx() API.  But we can still statically link against that
17807 ** API as long as we don't call it win running Win95/98/ME.  A call to
17808 ** this routine is used to determine if the host is Win95/98/ME or
17809 ** WinNT/2K/XP so that we will know whether or not we can safely call
17810 ** the LockFileEx() API.
17811 **
17812 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
17813 ** which is only available if your application was compiled with
17814 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
17815 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
17816 ** this out as well.
17817 */
17818 #if 0
17819 #if SQLITE_OS_WINCE
17820 # define mutexIsNT()  (1)
17821 #else
mutexIsNT(void)17822   static int mutexIsNT(void){
17823     static int osType = 0;
17824     if( osType==0 ){
17825       OSVERSIONINFO sInfo;
17826       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
17827       GetVersionEx(&sInfo);
17828       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
17829     }
17830     return osType==2;
17831   }
17832 #endif /* SQLITE_OS_WINCE */
17833 #endif
17834 
17835 #ifdef SQLITE_DEBUG
17836 /*
17837 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17838 ** intended for use only inside assert() statements.
17839 */
winMutexHeld(sqlite3_mutex * p)17840 static int winMutexHeld(sqlite3_mutex *p){
17841   return p->nRef!=0 && p->owner==GetCurrentThreadId();
17842 }
winMutexNotheld2(sqlite3_mutex * p,DWORD tid)17843 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
17844   return p->nRef==0 || p->owner!=tid;
17845 }
winMutexNotheld(sqlite3_mutex * p)17846 static int winMutexNotheld(sqlite3_mutex *p){
17847   DWORD tid = GetCurrentThreadId();
17848   return winMutexNotheld2(p, tid);
17849 }
17850 #endif
17851 
17852 
17853 /*
17854 ** Initialize and deinitialize the mutex subsystem.
17855 */
17856 static sqlite3_mutex winMutex_staticMutexes[6] = {
17857   SQLITE3_MUTEX_INITIALIZER,
17858   SQLITE3_MUTEX_INITIALIZER,
17859   SQLITE3_MUTEX_INITIALIZER,
17860   SQLITE3_MUTEX_INITIALIZER,
17861   SQLITE3_MUTEX_INITIALIZER,
17862   SQLITE3_MUTEX_INITIALIZER
17863 };
17864 static int winMutex_isInit = 0;
17865 /* As winMutexInit() and winMutexEnd() are called as part
17866 ** of the sqlite3_initialize and sqlite3_shutdown()
17867 ** processing, the "interlocked" magic is probably not
17868 ** strictly necessary.
17869 */
17870 static long winMutex_lock = 0;
17871 
winMutexInit(void)17872 static int winMutexInit(void){
17873   /* The first to increment to 1 does actual initialization */
17874   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
17875     int i;
17876     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17877       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
17878     }
17879     winMutex_isInit = 1;
17880   }else{
17881     /* Someone else is in the process of initing the static mutexes */
17882     while( !winMutex_isInit ){
17883       Sleep(1);
17884     }
17885   }
17886   return SQLITE_OK;
17887 }
17888 
winMutexEnd(void)17889 static int winMutexEnd(void){
17890   /* The first to decrement to 0 does actual shutdown
17891   ** (which should be the last to shutdown.) */
17892   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
17893     if( winMutex_isInit==1 ){
17894       int i;
17895       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
17896         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
17897       }
17898       winMutex_isInit = 0;
17899     }
17900   }
17901   return SQLITE_OK;
17902 }
17903 
17904 /*
17905 ** The sqlite3_mutex_alloc() routine allocates a new
17906 ** mutex and returns a pointer to it.  If it returns NULL
17907 ** that means that a mutex could not be allocated.  SQLite
17908 ** will unwind its stack and return an error.  The argument
17909 ** to sqlite3_mutex_alloc() is one of these integer constants:
17910 **
17911 ** <ul>
17912 ** <li>  SQLITE_MUTEX_FAST
17913 ** <li>  SQLITE_MUTEX_RECURSIVE
17914 ** <li>  SQLITE_MUTEX_STATIC_MASTER
17915 ** <li>  SQLITE_MUTEX_STATIC_MEM
17916 ** <li>  SQLITE_MUTEX_STATIC_MEM2
17917 ** <li>  SQLITE_MUTEX_STATIC_PRNG
17918 ** <li>  SQLITE_MUTEX_STATIC_LRU
17919 ** <li>  SQLITE_MUTEX_STATIC_PMEM
17920 ** </ul>
17921 **
17922 ** The first two constants cause sqlite3_mutex_alloc() to create
17923 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17924 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17925 ** The mutex implementation does not need to make a distinction
17926 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17927 ** not want to.  But SQLite will only request a recursive mutex in
17928 ** cases where it really needs one.  If a faster non-recursive mutex
17929 ** implementation is available on the host platform, the mutex subsystem
17930 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
17931 **
17932 ** The other allowed parameters to sqlite3_mutex_alloc() each return
17933 ** a pointer to a static preexisting mutex.  Six static mutexes are
17934 ** used by the current version of SQLite.  Future versions of SQLite
17935 ** may add additional static mutexes.  Static mutexes are for internal
17936 ** use by SQLite only.  Applications that use SQLite mutexes should
17937 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17938 ** SQLITE_MUTEX_RECURSIVE.
17939 **
17940 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17941 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17942 ** returns a different mutex on every call.  But for the static
17943 ** mutex types, the same mutex is returned on every call that has
17944 ** the same type number.
17945 */
winMutexAlloc(int iType)17946 static sqlite3_mutex *winMutexAlloc(int iType){
17947   sqlite3_mutex *p;
17948 
17949   switch( iType ){
17950     case SQLITE_MUTEX_FAST:
17951     case SQLITE_MUTEX_RECURSIVE: {
17952       p = sqlite3MallocZero( sizeof(*p) );
17953       if( p ){
17954 #ifdef SQLITE_DEBUG
17955         p->id = iType;
17956 #endif
17957         InitializeCriticalSection(&p->mutex);
17958       }
17959       break;
17960     }
17961     default: {
17962       assert( winMutex_isInit==1 );
17963       assert( iType-2 >= 0 );
17964       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
17965       p = &winMutex_staticMutexes[iType-2];
17966 #ifdef SQLITE_DEBUG
17967       p->id = iType;
17968 #endif
17969       break;
17970     }
17971   }
17972   return p;
17973 }
17974 
17975 
17976 /*
17977 ** This routine deallocates a previously
17978 ** allocated mutex.  SQLite is careful to deallocate every
17979 ** mutex that it allocates.
17980 */
winMutexFree(sqlite3_mutex * p)17981 static void winMutexFree(sqlite3_mutex *p){
17982   assert( p );
17983   assert( p->nRef==0 && p->owner==0 );
17984   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17985   DeleteCriticalSection(&p->mutex);
17986   sqlite3_free(p);
17987 }
17988 
17989 /*
17990 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17991 ** to enter a mutex.  If another thread is already within the mutex,
17992 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17993 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17994 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17995 ** be entered multiple times by the same thread.  In such cases the,
17996 ** mutex must be exited an equal number of times before another thread
17997 ** can enter.  If the same thread tries to enter any other kind of mutex
17998 ** more than once, the behavior is undefined.
17999 */
winMutexEnter(sqlite3_mutex * p)18000 static void winMutexEnter(sqlite3_mutex *p){
18001 #ifdef SQLITE_DEBUG
18002   DWORD tid = GetCurrentThreadId();
18003   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18004 #endif
18005   EnterCriticalSection(&p->mutex);
18006 #ifdef SQLITE_DEBUG
18007   assert( p->nRef>0 || p->owner==0 );
18008   p->owner = tid;
18009   p->nRef++;
18010   if( p->trace ){
18011     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18012   }
18013 #endif
18014 }
winMutexTry(sqlite3_mutex * p)18015 static int winMutexTry(sqlite3_mutex *p){
18016 #ifndef NDEBUG
18017   DWORD tid = GetCurrentThreadId();
18018 #endif
18019   int rc = SQLITE_BUSY;
18020   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18021   /*
18022   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18023   ** is used it is merely an optimization.  So it is OK for it to always
18024   ** fail.
18025   **
18026   ** The TryEnterCriticalSection() interface is only available on WinNT.
18027   ** And some windows compilers complain if you try to use it without
18028   ** first doing some #defines that prevent SQLite from building on Win98.
18029   ** For that reason, we will omit this optimization for now.  See
18030   ** ticket #2685.
18031   */
18032 #if 0
18033   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18034     p->owner = tid;
18035     p->nRef++;
18036     rc = SQLITE_OK;
18037   }
18038 #else
18039   UNUSED_PARAMETER(p);
18040 #endif
18041 #ifdef SQLITE_DEBUG
18042   if( rc==SQLITE_OK && p->trace ){
18043     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18044   }
18045 #endif
18046   return rc;
18047 }
18048 
18049 /*
18050 ** The sqlite3_mutex_leave() routine exits a mutex that was
18051 ** previously entered by the same thread.  The behavior
18052 ** is undefined if the mutex is not currently entered or
18053 ** is not currently allocated.  SQLite will never do either.
18054 */
winMutexLeave(sqlite3_mutex * p)18055 static void winMutexLeave(sqlite3_mutex *p){
18056 #ifndef NDEBUG
18057   DWORD tid = GetCurrentThreadId();
18058   assert( p->nRef>0 );
18059   assert( p->owner==tid );
18060   p->nRef--;
18061   if( p->nRef==0 ) p->owner = 0;
18062   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18063 #endif
18064   LeaveCriticalSection(&p->mutex);
18065 #ifdef SQLITE_DEBUG
18066   if( p->trace ){
18067     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18068   }
18069 #endif
18070 }
18071 
sqlite3DefaultMutex(void)18072 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18073   static const sqlite3_mutex_methods sMutex = {
18074     winMutexInit,
18075     winMutexEnd,
18076     winMutexAlloc,
18077     winMutexFree,
18078     winMutexEnter,
18079     winMutexTry,
18080     winMutexLeave,
18081 #ifdef SQLITE_DEBUG
18082     winMutexHeld,
18083     winMutexNotheld
18084 #else
18085     0,
18086     0
18087 #endif
18088   };
18089 
18090   return &sMutex;
18091 }
18092 #endif /* SQLITE_MUTEX_W32 */
18093 
18094 /************** End of mutex_w32.c *******************************************/
18095 /************** Begin file malloc.c ******************************************/
18096 /*
18097 ** 2001 September 15
18098 **
18099 ** The author disclaims copyright to this source code.  In place of
18100 ** a legal notice, here is a blessing:
18101 **
18102 **    May you do good and not evil.
18103 **    May you find forgiveness for yourself and forgive others.
18104 **    May you share freely, never taking more than you give.
18105 **
18106 *************************************************************************
18107 **
18108 ** Memory allocation functions used throughout sqlite.
18109 */
18110 /* #include <stdarg.h> */
18111 
18112 /*
18113 ** Attempt to release up to n bytes of non-essential memory currently
18114 ** held by SQLite. An example of non-essential memory is memory used to
18115 ** cache database pages that are not currently in use.
18116 */
sqlite3_release_memory(int n)18117 SQLITE_API int sqlite3_release_memory(int n){
18118 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18119   return sqlite3PcacheReleaseMemory(n);
18120 #else
18121   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18122   ** is a no-op returning zero if SQLite is not compiled with
18123   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18124   UNUSED_PARAMETER(n);
18125   return 0;
18126 #endif
18127 }
18128 
18129 /*
18130 ** An instance of the following object records the location of
18131 ** each unused scratch buffer.
18132 */
18133 typedef struct ScratchFreeslot {
18134   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18135 } ScratchFreeslot;
18136 
18137 /*
18138 ** State information local to the memory allocation subsystem.
18139 */
18140 static SQLITE_WSD struct Mem0Global {
18141   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18142 
18143   /*
18144   ** The alarm callback and its arguments.  The mem0.mutex lock will
18145   ** be held while the callback is running.  Recursive calls into
18146   ** the memory subsystem are allowed, but no new callbacks will be
18147   ** issued.
18148   */
18149   sqlite3_int64 alarmThreshold;
18150   void (*alarmCallback)(void*, sqlite3_int64,int);
18151   void *alarmArg;
18152 
18153   /*
18154   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18155   ** (so that a range test can be used to determine if an allocation
18156   ** being freed came from pScratch) and a pointer to the list of
18157   ** unused scratch allocations.
18158   */
18159   void *pScratchEnd;
18160   ScratchFreeslot *pScratchFree;
18161   u32 nScratchFree;
18162 
18163   /*
18164   ** True if heap is nearly "full" where "full" is defined by the
18165   ** sqlite3_soft_heap_limit() setting.
18166   */
18167   int nearlyFull;
18168 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18169 
18170 #define mem0 GLOBAL(struct Mem0Global, mem0)
18171 
18172 /*
18173 ** This routine runs when the memory allocator sees that the
18174 ** total memory allocation is about to exceed the soft heap
18175 ** limit.
18176 */
softHeapLimitEnforcer(void * NotUsed,sqlite3_int64 NotUsed2,int allocSize)18177 static void softHeapLimitEnforcer(
18178   void *NotUsed,
18179   sqlite3_int64 NotUsed2,
18180   int allocSize
18181 ){
18182   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18183   sqlite3_release_memory(allocSize);
18184 }
18185 
18186 /*
18187 ** Change the alarm callback
18188 */
sqlite3MemoryAlarm(void (* xCallback)(void * pArg,sqlite3_int64 used,int N),void * pArg,sqlite3_int64 iThreshold)18189 static int sqlite3MemoryAlarm(
18190   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18191   void *pArg,
18192   sqlite3_int64 iThreshold
18193 ){
18194   int nUsed;
18195   sqlite3_mutex_enter(mem0.mutex);
18196   mem0.alarmCallback = xCallback;
18197   mem0.alarmArg = pArg;
18198   mem0.alarmThreshold = iThreshold;
18199   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18200   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18201   sqlite3_mutex_leave(mem0.mutex);
18202   return SQLITE_OK;
18203 }
18204 
18205 #ifndef SQLITE_OMIT_DEPRECATED
18206 /*
18207 ** Deprecated external interface.  Internal/core SQLite code
18208 ** should call sqlite3MemoryAlarm.
18209 */
sqlite3_memory_alarm(void (* xCallback)(void * pArg,sqlite3_int64 used,int N),void * pArg,sqlite3_int64 iThreshold)18210 SQLITE_API int sqlite3_memory_alarm(
18211   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18212   void *pArg,
18213   sqlite3_int64 iThreshold
18214 ){
18215   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18216 }
18217 #endif
18218 
18219 /*
18220 ** Set the soft heap-size limit for the library. Passing a zero or
18221 ** negative value indicates no limit.
18222 */
sqlite3_soft_heap_limit64(sqlite3_int64 n)18223 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18224   sqlite3_int64 priorLimit;
18225   sqlite3_int64 excess;
18226 #ifndef SQLITE_OMIT_AUTOINIT
18227   sqlite3_initialize();
18228 #endif
18229   sqlite3_mutex_enter(mem0.mutex);
18230   priorLimit = mem0.alarmThreshold;
18231   sqlite3_mutex_leave(mem0.mutex);
18232   if( n<0 ) return priorLimit;
18233   if( n>0 ){
18234     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18235   }else{
18236     sqlite3MemoryAlarm(0, 0, 0);
18237   }
18238   excess = sqlite3_memory_used() - n;
18239   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18240   return priorLimit;
18241 }
sqlite3_soft_heap_limit(int n)18242 SQLITE_API void sqlite3_soft_heap_limit(int n){
18243   if( n<0 ) n = 0;
18244   sqlite3_soft_heap_limit64(n);
18245 }
18246 
18247 /*
18248 ** Initialize the memory allocation subsystem.
18249 */
sqlite3MallocInit(void)18250 SQLITE_PRIVATE int sqlite3MallocInit(void){
18251   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18252     sqlite3MemSetDefault();
18253   }
18254   memset(&mem0, 0, sizeof(mem0));
18255   if( sqlite3GlobalConfig.bCoreMutex ){
18256     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18257   }
18258   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18259       && sqlite3GlobalConfig.nScratch>0 ){
18260     int i, n, sz;
18261     ScratchFreeslot *pSlot;
18262     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18263     sqlite3GlobalConfig.szScratch = sz;
18264     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18265     n = sqlite3GlobalConfig.nScratch;
18266     mem0.pScratchFree = pSlot;
18267     mem0.nScratchFree = n;
18268     for(i=0; i<n-1; i++){
18269       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18270       pSlot = pSlot->pNext;
18271     }
18272     pSlot->pNext = 0;
18273     mem0.pScratchEnd = (void*)&pSlot[1];
18274   }else{
18275     mem0.pScratchEnd = 0;
18276     sqlite3GlobalConfig.pScratch = 0;
18277     sqlite3GlobalConfig.szScratch = 0;
18278     sqlite3GlobalConfig.nScratch = 0;
18279   }
18280   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18281       || sqlite3GlobalConfig.nPage<1 ){
18282     sqlite3GlobalConfig.pPage = 0;
18283     sqlite3GlobalConfig.szPage = 0;
18284     sqlite3GlobalConfig.nPage = 0;
18285   }
18286   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18287 }
18288 
18289 /*
18290 ** Return true if the heap is currently under memory pressure - in other
18291 ** words if the amount of heap used is close to the limit set by
18292 ** sqlite3_soft_heap_limit().
18293 */
sqlite3HeapNearlyFull(void)18294 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18295   return mem0.nearlyFull;
18296 }
18297 
18298 /*
18299 ** Deinitialize the memory allocation subsystem.
18300 */
sqlite3MallocEnd(void)18301 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18302   if( sqlite3GlobalConfig.m.xShutdown ){
18303     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18304   }
18305   memset(&mem0, 0, sizeof(mem0));
18306 }
18307 
18308 /*
18309 ** Return the amount of memory currently checked out.
18310 */
sqlite3_memory_used(void)18311 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18312   int n, mx;
18313   sqlite3_int64 res;
18314   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18315   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18316   return res;
18317 }
18318 
18319 /*
18320 ** Return the maximum amount of memory that has ever been
18321 ** checked out since either the beginning of this process
18322 ** or since the most recent reset.
18323 */
sqlite3_memory_highwater(int resetFlag)18324 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18325   int n, mx;
18326   sqlite3_int64 res;
18327   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18328   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18329   return res;
18330 }
18331 
18332 /*
18333 ** Trigger the alarm
18334 */
sqlite3MallocAlarm(int nByte)18335 static void sqlite3MallocAlarm(int nByte){
18336   void (*xCallback)(void*,sqlite3_int64,int);
18337   sqlite3_int64 nowUsed;
18338   void *pArg;
18339   if( mem0.alarmCallback==0 ) return;
18340   xCallback = mem0.alarmCallback;
18341   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18342   pArg = mem0.alarmArg;
18343   mem0.alarmCallback = 0;
18344   sqlite3_mutex_leave(mem0.mutex);
18345   xCallback(pArg, nowUsed, nByte);
18346   sqlite3_mutex_enter(mem0.mutex);
18347   mem0.alarmCallback = xCallback;
18348   mem0.alarmArg = pArg;
18349 }
18350 
18351 /*
18352 ** Do a memory allocation with statistics and alarms.  Assume the
18353 ** lock is already held.
18354 */
mallocWithAlarm(int n,void ** pp)18355 static int mallocWithAlarm(int n, void **pp){
18356   int nFull;
18357   void *p;
18358   assert( sqlite3_mutex_held(mem0.mutex) );
18359   nFull = sqlite3GlobalConfig.m.xRoundup(n);
18360   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18361   if( mem0.alarmCallback!=0 ){
18362     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18363     if( nUsed >= mem0.alarmThreshold - nFull ){
18364       mem0.nearlyFull = 1;
18365       sqlite3MallocAlarm(nFull);
18366     }else{
18367       mem0.nearlyFull = 0;
18368     }
18369   }
18370   p = sqlite3GlobalConfig.m.xMalloc(nFull);
18371 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18372   if( p==0 && mem0.alarmCallback ){
18373     sqlite3MallocAlarm(nFull);
18374     p = sqlite3GlobalConfig.m.xMalloc(nFull);
18375   }
18376 #endif
18377   if( p ){
18378     nFull = sqlite3MallocSize(p);
18379     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18380     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18381   }
18382   *pp = p;
18383   return nFull;
18384 }
18385 
18386 /*
18387 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
18388 ** assumes the memory subsystem has already been initialized.
18389 */
sqlite3Malloc(int n)18390 SQLITE_PRIVATE void *sqlite3Malloc(int n){
18391   void *p;
18392   if( n<=0               /* IMP: R-65312-04917 */
18393    || n>=0x7fffff00
18394   ){
18395     /* A memory allocation of a number of bytes which is near the maximum
18396     ** signed integer value might cause an integer overflow inside of the
18397     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18398     ** 255 bytes of overhead.  SQLite itself will never use anything near
18399     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18400     p = 0;
18401   }else if( sqlite3GlobalConfig.bMemstat ){
18402     sqlite3_mutex_enter(mem0.mutex);
18403     mallocWithAlarm(n, &p);
18404     sqlite3_mutex_leave(mem0.mutex);
18405   }else{
18406     p = sqlite3GlobalConfig.m.xMalloc(n);
18407   }
18408   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18409   return p;
18410 }
18411 
18412 /*
18413 ** This version of the memory allocation is for use by the application.
18414 ** First make sure the memory subsystem is initialized, then do the
18415 ** allocation.
18416 */
sqlite3_malloc(int n)18417 SQLITE_API void *sqlite3_malloc(int n){
18418 #ifndef SQLITE_OMIT_AUTOINIT
18419   if( sqlite3_initialize() ) return 0;
18420 #endif
18421   return sqlite3Malloc(n);
18422 }
18423 
18424 /*
18425 ** Each thread may only have a single outstanding allocation from
18426 ** xScratchMalloc().  We verify this constraint in the single-threaded
18427 ** case by setting scratchAllocOut to 1 when an allocation
18428 ** is outstanding clearing it when the allocation is freed.
18429 */
18430 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18431 static int scratchAllocOut = 0;
18432 #endif
18433 
18434 
18435 /*
18436 ** Allocate memory that is to be used and released right away.
18437 ** This routine is similar to alloca() in that it is not intended
18438 ** for situations where the memory might be held long-term.  This
18439 ** routine is intended to get memory to old large transient data
18440 ** structures that would not normally fit on the stack of an
18441 ** embedded processor.
18442 */
sqlite3ScratchMalloc(int n)18443 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18444   void *p;
18445   assert( n>0 );
18446 
18447   sqlite3_mutex_enter(mem0.mutex);
18448   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18449     p = mem0.pScratchFree;
18450     mem0.pScratchFree = mem0.pScratchFree->pNext;
18451     mem0.nScratchFree--;
18452     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18453     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18454     sqlite3_mutex_leave(mem0.mutex);
18455   }else{
18456     if( sqlite3GlobalConfig.bMemstat ){
18457       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18458       n = mallocWithAlarm(n, &p);
18459       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18460       sqlite3_mutex_leave(mem0.mutex);
18461     }else{
18462       sqlite3_mutex_leave(mem0.mutex);
18463       p = sqlite3GlobalConfig.m.xMalloc(n);
18464     }
18465     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18466   }
18467   assert( sqlite3_mutex_notheld(mem0.mutex) );
18468 
18469 
18470 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18471   /* Verify that no more than two scratch allocations per thread
18472   ** are outstanding at one time.  (This is only checked in the
18473   ** single-threaded case since checking in the multi-threaded case
18474   ** would be much more complicated.) */
18475   assert( scratchAllocOut<=1 );
18476   if( p ) scratchAllocOut++;
18477 #endif
18478 
18479   return p;
18480 }
sqlite3ScratchFree(void * p)18481 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18482   if( p ){
18483 
18484 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18485     /* Verify that no more than two scratch allocation per thread
18486     ** is outstanding at one time.  (This is only checked in the
18487     ** single-threaded case since checking in the multi-threaded case
18488     ** would be much more complicated.) */
18489     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18490     scratchAllocOut--;
18491 #endif
18492 
18493     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18494       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18495       ScratchFreeslot *pSlot;
18496       pSlot = (ScratchFreeslot*)p;
18497       sqlite3_mutex_enter(mem0.mutex);
18498       pSlot->pNext = mem0.pScratchFree;
18499       mem0.pScratchFree = pSlot;
18500       mem0.nScratchFree++;
18501       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18502       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18503       sqlite3_mutex_leave(mem0.mutex);
18504     }else{
18505       /* Release memory back to the heap */
18506       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18507       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
18508       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18509       if( sqlite3GlobalConfig.bMemstat ){
18510         int iSize = sqlite3MallocSize(p);
18511         sqlite3_mutex_enter(mem0.mutex);
18512         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
18513         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
18514         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18515         sqlite3GlobalConfig.m.xFree(p);
18516         sqlite3_mutex_leave(mem0.mutex);
18517       }else{
18518         sqlite3GlobalConfig.m.xFree(p);
18519       }
18520     }
18521   }
18522 }
18523 
18524 /*
18525 ** TRUE if p is a lookaside memory allocation from db
18526 */
18527 #ifndef SQLITE_OMIT_LOOKASIDE
isLookaside(sqlite3 * db,void * p)18528 static int isLookaside(sqlite3 *db, void *p){
18529   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
18530 }
18531 #else
18532 #define isLookaside(A,B) 0
18533 #endif
18534 
18535 /*
18536 ** Return the size of a memory allocation previously obtained from
18537 ** sqlite3Malloc() or sqlite3_malloc().
18538 */
sqlite3MallocSize(void * p)18539 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
18540   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18541   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18542   return sqlite3GlobalConfig.m.xSize(p);
18543 }
sqlite3DbMallocSize(sqlite3 * db,void * p)18544 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
18545   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18546   if( db && isLookaside(db, p) ){
18547     return db->lookaside.sz;
18548   }else{
18549     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18550     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18551     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18552     return sqlite3GlobalConfig.m.xSize(p);
18553   }
18554 }
18555 
18556 /*
18557 ** Free memory previously obtained from sqlite3Malloc().
18558 */
sqlite3_free(void * p)18559 SQLITE_API void sqlite3_free(void *p){
18560   if( p==0 ) return;  /* IMP: R-49053-54554 */
18561   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
18562   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
18563   if( sqlite3GlobalConfig.bMemstat ){
18564     sqlite3_mutex_enter(mem0.mutex);
18565     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
18566     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
18567     sqlite3GlobalConfig.m.xFree(p);
18568     sqlite3_mutex_leave(mem0.mutex);
18569   }else{
18570     sqlite3GlobalConfig.m.xFree(p);
18571   }
18572 }
18573 
18574 /*
18575 ** Free memory that might be associated with a particular database
18576 ** connection.
18577 */
sqlite3DbFree(sqlite3 * db,void * p)18578 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
18579   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18580   if( db ){
18581     if( db->pnBytesFreed ){
18582       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
18583       return;
18584     }
18585     if( isLookaside(db, p) ){
18586       LookasideSlot *pBuf = (LookasideSlot*)p;
18587       pBuf->pNext = db->lookaside.pFree;
18588       db->lookaside.pFree = pBuf;
18589       db->lookaside.nOut--;
18590       return;
18591     }
18592   }
18593   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18594   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18595   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
18596   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18597   sqlite3_free(p);
18598 }
18599 
18600 /*
18601 ** Change the size of an existing memory allocation
18602 */
sqlite3Realloc(void * pOld,int nBytes)18603 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
18604   int nOld, nNew, nDiff;
18605   void *pNew;
18606   if( pOld==0 ){
18607     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
18608   }
18609   if( nBytes<=0 ){
18610     sqlite3_free(pOld); /* IMP: R-31593-10574 */
18611     return 0;
18612   }
18613   if( nBytes>=0x7fffff00 ){
18614     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
18615     return 0;
18616   }
18617   nOld = sqlite3MallocSize(pOld);
18618   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
18619   ** argument to xRealloc is always a value returned by a prior call to
18620   ** xRoundup. */
18621   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
18622   if( nOld==nNew ){
18623     pNew = pOld;
18624   }else if( sqlite3GlobalConfig.bMemstat ){
18625     sqlite3_mutex_enter(mem0.mutex);
18626     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
18627     nDiff = nNew - nOld;
18628     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
18629           mem0.alarmThreshold-nDiff ){
18630       sqlite3MallocAlarm(nDiff);
18631     }
18632     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
18633     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
18634     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18635     if( pNew==0 && mem0.alarmCallback ){
18636       sqlite3MallocAlarm(nBytes);
18637       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18638     }
18639     if( pNew ){
18640       nNew = sqlite3MallocSize(pNew);
18641       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
18642     }
18643     sqlite3_mutex_leave(mem0.mutex);
18644   }else{
18645     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
18646   }
18647   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
18648   return pNew;
18649 }
18650 
18651 /*
18652 ** The public interface to sqlite3Realloc.  Make sure that the memory
18653 ** subsystem is initialized prior to invoking sqliteRealloc.
18654 */
sqlite3_realloc(void * pOld,int n)18655 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
18656 #ifndef SQLITE_OMIT_AUTOINIT
18657   if( sqlite3_initialize() ) return 0;
18658 #endif
18659   return sqlite3Realloc(pOld, n);
18660 }
18661 
18662 
18663 /*
18664 ** Allocate and zero memory.
18665 */
sqlite3MallocZero(int n)18666 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
18667   void *p = sqlite3Malloc(n);
18668   if( p ){
18669     memset(p, 0, n);
18670   }
18671   return p;
18672 }
18673 
18674 /*
18675 ** Allocate and zero memory.  If the allocation fails, make
18676 ** the mallocFailed flag in the connection pointer.
18677 */
sqlite3DbMallocZero(sqlite3 * db,int n)18678 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
18679   void *p = sqlite3DbMallocRaw(db, n);
18680   if( p ){
18681     memset(p, 0, n);
18682   }
18683   return p;
18684 }
18685 
18686 /*
18687 ** Allocate and zero memory.  If the allocation fails, make
18688 ** the mallocFailed flag in the connection pointer.
18689 **
18690 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
18691 ** failure on the same database connection) then always return 0.
18692 ** Hence for a particular database connection, once malloc starts
18693 ** failing, it fails consistently until mallocFailed is reset.
18694 ** This is an important assumption.  There are many places in the
18695 ** code that do things like this:
18696 **
18697 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
18698 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
18699 **         if( b ) a[10] = 9;
18700 **
18701 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
18702 ** that all prior mallocs (ex: "a") worked too.
18703 */
sqlite3DbMallocRaw(sqlite3 * db,int n)18704 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
18705   void *p;
18706   assert( db==0 || sqlite3_mutex_held(db->mutex) );
18707   assert( db==0 || db->pnBytesFreed==0 );
18708 #ifndef SQLITE_OMIT_LOOKASIDE
18709   if( db ){
18710     LookasideSlot *pBuf;
18711     if( db->mallocFailed ){
18712       return 0;
18713     }
18714     if( db->lookaside.bEnabled ){
18715       if( n>db->lookaside.sz ){
18716         db->lookaside.anStat[1]++;
18717       }else if( (pBuf = db->lookaside.pFree)==0 ){
18718         db->lookaside.anStat[2]++;
18719       }else{
18720         db->lookaside.pFree = pBuf->pNext;
18721         db->lookaside.nOut++;
18722         db->lookaside.anStat[0]++;
18723         if( db->lookaside.nOut>db->lookaside.mxOut ){
18724           db->lookaside.mxOut = db->lookaside.nOut;
18725         }
18726         return (void*)pBuf;
18727       }
18728     }
18729   }
18730 #else
18731   if( db && db->mallocFailed ){
18732     return 0;
18733   }
18734 #endif
18735   p = sqlite3Malloc(n);
18736   if( !p && db ){
18737     db->mallocFailed = 1;
18738   }
18739   sqlite3MemdebugSetType(p, MEMTYPE_DB |
18740          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18741   return p;
18742 }
18743 
18744 /*
18745 ** Resize the block of memory pointed to by p to n bytes. If the
18746 ** resize fails, set the mallocFailed flag in the connection object.
18747 */
sqlite3DbRealloc(sqlite3 * db,void * p,int n)18748 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
18749   void *pNew = 0;
18750   assert( db!=0 );
18751   assert( sqlite3_mutex_held(db->mutex) );
18752   if( db->mallocFailed==0 ){
18753     if( p==0 ){
18754       return sqlite3DbMallocRaw(db, n);
18755     }
18756     if( isLookaside(db, p) ){
18757       if( n<=db->lookaside.sz ){
18758         return p;
18759       }
18760       pNew = sqlite3DbMallocRaw(db, n);
18761       if( pNew ){
18762         memcpy(pNew, p, db->lookaside.sz);
18763         sqlite3DbFree(db, p);
18764       }
18765     }else{
18766       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
18767       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
18768       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
18769       pNew = sqlite3_realloc(p, n);
18770       if( !pNew ){
18771         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
18772         db->mallocFailed = 1;
18773       }
18774       sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
18775             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
18776     }
18777   }
18778   return pNew;
18779 }
18780 
18781 /*
18782 ** Attempt to reallocate p.  If the reallocation fails, then free p
18783 ** and set the mallocFailed flag in the database connection.
18784 */
sqlite3DbReallocOrFree(sqlite3 * db,void * p,int n)18785 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
18786   void *pNew;
18787   pNew = sqlite3DbRealloc(db, p, n);
18788   if( !pNew ){
18789     sqlite3DbFree(db, p);
18790   }
18791   return pNew;
18792 }
18793 
18794 /*
18795 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
18796 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
18797 ** is because when memory debugging is turned on, these two functions are
18798 ** called via macros that record the current file and line number in the
18799 ** ThreadData structure.
18800 */
sqlite3DbStrDup(sqlite3 * db,const char * z)18801 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
18802   char *zNew;
18803   size_t n;
18804   if( z==0 ){
18805     return 0;
18806   }
18807   n = sqlite3Strlen30(z) + 1;
18808   assert( (n&0x7fffffff)==n );
18809   zNew = sqlite3DbMallocRaw(db, (int)n);
18810   if( zNew ){
18811     memcpy(zNew, z, n);
18812   }
18813   return zNew;
18814 }
sqlite3DbStrNDup(sqlite3 * db,const char * z,int n)18815 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
18816   char *zNew;
18817   if( z==0 ){
18818     return 0;
18819   }
18820   assert( (n&0x7fffffff)==n );
18821   zNew = sqlite3DbMallocRaw(db, n+1);
18822   if( zNew ){
18823     memcpy(zNew, z, n);
18824     zNew[n] = 0;
18825   }
18826   return zNew;
18827 }
18828 
18829 /*
18830 ** Create a string from the zFromat argument and the va_list that follows.
18831 ** Store the string in memory obtained from sqliteMalloc() and make *pz
18832 ** point to that string.
18833 */
sqlite3SetString(char ** pz,sqlite3 * db,const char * zFormat,...)18834 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
18835   va_list ap;
18836   char *z;
18837 
18838   va_start(ap, zFormat);
18839   z = sqlite3VMPrintf(db, zFormat, ap);
18840   va_end(ap);
18841   sqlite3DbFree(db, *pz);
18842   *pz = z;
18843 }
18844 
18845 
18846 /*
18847 ** This function must be called before exiting any API function (i.e.
18848 ** returning control to the user) that has called sqlite3_malloc or
18849 ** sqlite3_realloc.
18850 **
18851 ** The returned value is normally a copy of the second argument to this
18852 ** function. However, if a malloc() failure has occurred since the previous
18853 ** invocation SQLITE_NOMEM is returned instead.
18854 **
18855 ** If the first argument, db, is not NULL and a malloc() error has occurred,
18856 ** then the connection error-code (the value returned by sqlite3_errcode())
18857 ** is set to SQLITE_NOMEM.
18858 */
sqlite3ApiExit(sqlite3 * db,int rc)18859 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
18860   /* If the db handle is not NULL, then we must hold the connection handle
18861   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
18862   ** is unsafe, as is the call to sqlite3Error().
18863   */
18864   assert( !db || sqlite3_mutex_held(db->mutex) );
18865   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
18866     sqlite3Error(db, SQLITE_NOMEM, 0);
18867     db->mallocFailed = 0;
18868     rc = SQLITE_NOMEM;
18869   }
18870   return rc & (db ? db->errMask : 0xff);
18871 }
18872 
18873 /************** End of malloc.c **********************************************/
18874 /************** Begin file printf.c ******************************************/
18875 /*
18876 ** The "printf" code that follows dates from the 1980's.  It is in
18877 ** the public domain.  The original comments are included here for
18878 ** completeness.  They are very out-of-date but might be useful as
18879 ** an historical reference.  Most of the "enhancements" have been backed
18880 ** out so that the functionality is now the same as standard printf().
18881 **
18882 **************************************************************************
18883 **
18884 ** The following modules is an enhanced replacement for the "printf" subroutines
18885 ** found in the standard C library.  The following enhancements are
18886 ** supported:
18887 **
18888 **      +  Additional functions.  The standard set of "printf" functions
18889 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
18890 **         vsprintf.  This module adds the following:
18891 **
18892 **           *  snprintf -- Works like sprintf, but has an extra argument
18893 **                          which is the size of the buffer written to.
18894 **
18895 **           *  mprintf --  Similar to sprintf.  Writes output to memory
18896 **                          obtained from malloc.
18897 **
18898 **           *  xprintf --  Calls a function to dispose of output.
18899 **
18900 **           *  nprintf --  No output, but returns the number of characters
18901 **                          that would have been output by printf.
18902 **
18903 **           *  A v- version (ex: vsnprintf) of every function is also
18904 **              supplied.
18905 **
18906 **      +  A few extensions to the formatting notation are supported:
18907 **
18908 **           *  The "=" flag (similar to "-") causes the output to be
18909 **              be centered in the appropriately sized field.
18910 **
18911 **           *  The %b field outputs an integer in binary notation.
18912 **
18913 **           *  The %c field now accepts a precision.  The character output
18914 **              is repeated by the number of times the precision specifies.
18915 **
18916 **           *  The %' field works like %c, but takes as its character the
18917 **              next character of the format string, instead of the next
18918 **              argument.  For example,  printf("%.78'-")  prints 78 minus
18919 **              signs, the same as  printf("%.78c",'-').
18920 **
18921 **      +  When compiled using GCC on a SPARC, this version of printf is
18922 **         faster than the library printf for SUN OS 4.1.
18923 **
18924 **      +  All functions are fully reentrant.
18925 **
18926 */
18927 
18928 /*
18929 ** Conversion types fall into various categories as defined by the
18930 ** following enumeration.
18931 */
18932 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
18933 #define etFLOAT       2 /* Floating point.  %f */
18934 #define etEXP         3 /* Exponentional notation. %e and %E */
18935 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
18936 #define etSIZE        5 /* Return number of characters processed so far. %n */
18937 #define etSTRING      6 /* Strings. %s */
18938 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
18939 #define etPERCENT     8 /* Percent symbol. %% */
18940 #define etCHARX       9 /* Characters. %c */
18941 /* The rest are extensions, not normally found in printf() */
18942 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
18943 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
18944                           NULL pointers replaced by SQL NULL.  %Q */
18945 #define etTOKEN      12 /* a pointer to a Token structure */
18946 #define etSRCLIST    13 /* a pointer to a SrcList */
18947 #define etPOINTER    14 /* The %p conversion */
18948 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
18949 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
18950 
18951 #define etINVALID     0 /* Any unrecognized conversion type */
18952 
18953 
18954 /*
18955 ** An "etByte" is an 8-bit unsigned value.
18956 */
18957 typedef unsigned char etByte;
18958 
18959 /*
18960 ** Each builtin conversion character (ex: the 'd' in "%d") is described
18961 ** by an instance of the following structure
18962 */
18963 typedef struct et_info {   /* Information about each format field */
18964   char fmttype;            /* The format field code letter */
18965   etByte base;             /* The base for radix conversion */
18966   etByte flags;            /* One or more of FLAG_ constants below */
18967   etByte type;             /* Conversion paradigm */
18968   etByte charset;          /* Offset into aDigits[] of the digits string */
18969   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
18970 } et_info;
18971 
18972 /*
18973 ** Allowed values for et_info.flags
18974 */
18975 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
18976 #define FLAG_INTERN  2     /* True if for internal use only */
18977 #define FLAG_STRING  4     /* Allow infinity precision */
18978 
18979 
18980 /*
18981 ** The following table is searched linearly, so it is good to put the
18982 ** most frequently used conversion types first.
18983 */
18984 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
18985 static const char aPrefix[] = "-x0\000X0";
18986 static const et_info fmtinfo[] = {
18987   {  'd', 10, 1, etRADIX,      0,  0 },
18988   {  's',  0, 4, etSTRING,     0,  0 },
18989   {  'g',  0, 1, etGENERIC,    30, 0 },
18990   {  'z',  0, 4, etDYNSTRING,  0,  0 },
18991   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
18992   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
18993   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
18994   {  'c',  0, 0, etCHARX,      0,  0 },
18995   {  'o',  8, 0, etRADIX,      0,  2 },
18996   {  'u', 10, 0, etRADIX,      0,  0 },
18997   {  'x', 16, 0, etRADIX,      16, 1 },
18998   {  'X', 16, 0, etRADIX,      0,  4 },
18999 #ifndef SQLITE_OMIT_FLOATING_POINT
19000   {  'f',  0, 1, etFLOAT,      0,  0 },
19001   {  'e',  0, 1, etEXP,        30, 0 },
19002   {  'E',  0, 1, etEXP,        14, 0 },
19003   {  'G',  0, 1, etGENERIC,    14, 0 },
19004 #endif
19005   {  'i', 10, 1, etRADIX,      0,  0 },
19006   {  'n',  0, 0, etSIZE,       0,  0 },
19007   {  '%',  0, 0, etPERCENT,    0,  0 },
19008   {  'p', 16, 0, etPOINTER,    0,  1 },
19009 
19010 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19011 ** use only */
19012   {  'T',  0, 2, etTOKEN,      0,  0 },
19013   {  'S',  0, 2, etSRCLIST,    0,  0 },
19014   {  'r', 10, 3, etORDINAL,    0,  0 },
19015 };
19016 
19017 /*
19018 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19019 ** conversions will work.
19020 */
19021 #ifndef SQLITE_OMIT_FLOATING_POINT
19022 /*
19023 ** "*val" is a double such that 0.1 <= *val < 10.0
19024 ** Return the ascii code for the leading digit of *val, then
19025 ** multiply "*val" by 10.0 to renormalize.
19026 **
19027 ** Example:
19028 **     input:     *val = 3.14159
19029 **     output:    *val = 1.4159    function return = '3'
19030 **
19031 ** The counter *cnt is incremented each time.  After counter exceeds
19032 ** 16 (the number of significant digits in a 64-bit float) '0' is
19033 ** always returned.
19034 */
et_getdigit(LONGDOUBLE_TYPE * val,int * cnt)19035 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19036   int digit;
19037   LONGDOUBLE_TYPE d;
19038   if( (*cnt)++ >= 16 ) return '0';
19039   digit = (int)*val;
19040   d = digit;
19041   digit += '0';
19042   *val = (*val - d)*10.0;
19043   return (char)digit;
19044 }
19045 #endif /* SQLITE_OMIT_FLOATING_POINT */
19046 
19047 /*
19048 ** Append N space characters to the given string buffer.
19049 */
appendSpace(StrAccum * pAccum,int N)19050 static void appendSpace(StrAccum *pAccum, int N){
19051   static const char zSpaces[] = "                             ";
19052   while( N>=(int)sizeof(zSpaces)-1 ){
19053     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19054     N -= sizeof(zSpaces)-1;
19055   }
19056   if( N>0 ){
19057     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19058   }
19059 }
19060 
19061 /*
19062 ** On machines with a small stack size, you can redefine the
19063 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
19064 */
19065 #ifndef SQLITE_PRINT_BUF_SIZE
19066 # if defined(SQLITE_SMALL_STACK)
19067 #   define SQLITE_PRINT_BUF_SIZE 50
19068 # else
19069 #   define SQLITE_PRINT_BUF_SIZE 350
19070 # endif
19071 #endif
19072 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19073 
19074 /*
19075 ** The root program.  All variations call this core.
19076 **
19077 ** INPUTS:
19078 **   func   This is a pointer to a function taking three arguments
19079 **            1. A pointer to anything.  Same as the "arg" parameter.
19080 **            2. A pointer to the list of characters to be output
19081 **               (Note, this list is NOT null terminated.)
19082 **            3. An integer number of characters to be output.
19083 **               (Note: This number might be zero.)
19084 **
19085 **   arg    This is the pointer to anything which will be passed as the
19086 **          first argument to "func".  Use it for whatever you like.
19087 **
19088 **   fmt    This is the format string, as in the usual print.
19089 **
19090 **   ap     This is a pointer to a list of arguments.  Same as in
19091 **          vfprint.
19092 **
19093 ** OUTPUTS:
19094 **          The return value is the total number of characters sent to
19095 **          the function "func".  Returns -1 on a error.
19096 **
19097 ** Note that the order in which automatic variables are declared below
19098 ** seems to make a big difference in determining how fast this beast
19099 ** will run.
19100 */
sqlite3VXPrintf(StrAccum * pAccum,int useExtended,const char * fmt,va_list ap)19101 SQLITE_PRIVATE void sqlite3VXPrintf(
19102   StrAccum *pAccum,                  /* Accumulate results here */
19103   int useExtended,                   /* Allow extended %-conversions */
19104   const char *fmt,                   /* Format string */
19105   va_list ap                         /* arguments */
19106 ){
19107   int c;                     /* Next character in the format string */
19108   char *bufpt;               /* Pointer to the conversion buffer */
19109   int precision;             /* Precision of the current field */
19110   int length;                /* Length of the field */
19111   int idx;                   /* A general purpose loop counter */
19112   int width;                 /* Width of the current field */
19113   etByte flag_leftjustify;   /* True if "-" flag is present */
19114   etByte flag_plussign;      /* True if "+" flag is present */
19115   etByte flag_blanksign;     /* True if " " flag is present */
19116   etByte flag_alternateform; /* True if "#" flag is present */
19117   etByte flag_altform2;      /* True if "!" flag is present */
19118   etByte flag_zeropad;       /* True if field width constant starts with zero */
19119   etByte flag_long;          /* True if "l" flag is present */
19120   etByte flag_longlong;      /* True if the "ll" flag is present */
19121   etByte done;               /* Loop termination flag */
19122   sqlite_uint64 longvalue;   /* Value for integer types */
19123   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19124   const et_info *infop;      /* Pointer to the appropriate info structure */
19125   char buf[etBUFSIZE];       /* Conversion buffer */
19126   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19127   etByte xtype = 0;          /* Conversion paradigm */
19128   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
19129 #ifndef SQLITE_OMIT_FLOATING_POINT
19130   int  exp, e2;              /* exponent of real numbers */
19131   double rounder;            /* Used for rounding floating point values */
19132   etByte flag_dp;            /* True if decimal point should be shown */
19133   etByte flag_rtz;           /* True if trailing zeros should be removed */
19134   etByte flag_exp;           /* True to force display of the exponent */
19135   int nsd;                   /* Number of significant digits returned */
19136 #endif
19137 
19138   length = 0;
19139   bufpt = 0;
19140   for(; (c=(*fmt))!=0; ++fmt){
19141     if( c!='%' ){
19142       int amt;
19143       bufpt = (char *)fmt;
19144       amt = 1;
19145       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19146       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19147       if( c==0 ) break;
19148     }
19149     if( (c=(*++fmt))==0 ){
19150       sqlite3StrAccumAppend(pAccum, "%", 1);
19151       break;
19152     }
19153     /* Find out what flags are present */
19154     flag_leftjustify = flag_plussign = flag_blanksign =
19155      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19156     done = 0;
19157     do{
19158       switch( c ){
19159         case '-':   flag_leftjustify = 1;     break;
19160         case '+':   flag_plussign = 1;        break;
19161         case ' ':   flag_blanksign = 1;       break;
19162         case '#':   flag_alternateform = 1;   break;
19163         case '!':   flag_altform2 = 1;        break;
19164         case '0':   flag_zeropad = 1;         break;
19165         default:    done = 1;                 break;
19166       }
19167     }while( !done && (c=(*++fmt))!=0 );
19168     /* Get the field width */
19169     width = 0;
19170     if( c=='*' ){
19171       width = va_arg(ap,int);
19172       if( width<0 ){
19173         flag_leftjustify = 1;
19174         width = -width;
19175       }
19176       c = *++fmt;
19177     }else{
19178       while( c>='0' && c<='9' ){
19179         width = width*10 + c - '0';
19180         c = *++fmt;
19181       }
19182     }
19183     if( width > etBUFSIZE-10 ){
19184       width = etBUFSIZE-10;
19185     }
19186     /* Get the precision */
19187     if( c=='.' ){
19188       precision = 0;
19189       c = *++fmt;
19190       if( c=='*' ){
19191         precision = va_arg(ap,int);
19192         if( precision<0 ) precision = -precision;
19193         c = *++fmt;
19194       }else{
19195         while( c>='0' && c<='9' ){
19196           precision = precision*10 + c - '0';
19197           c = *++fmt;
19198         }
19199       }
19200     }else{
19201       precision = -1;
19202     }
19203     /* Get the conversion type modifier */
19204     if( c=='l' ){
19205       flag_long = 1;
19206       c = *++fmt;
19207       if( c=='l' ){
19208         flag_longlong = 1;
19209         c = *++fmt;
19210       }else{
19211         flag_longlong = 0;
19212       }
19213     }else{
19214       flag_long = flag_longlong = 0;
19215     }
19216     /* Fetch the info entry for the field */
19217     infop = &fmtinfo[0];
19218     xtype = etINVALID;
19219     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19220       if( c==fmtinfo[idx].fmttype ){
19221         infop = &fmtinfo[idx];
19222         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19223           xtype = infop->type;
19224         }else{
19225           return;
19226         }
19227         break;
19228       }
19229     }
19230     zExtra = 0;
19231 
19232 
19233     /* Limit the precision to prevent overflowing buf[] during conversion */
19234     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
19235       precision = etBUFSIZE-40;
19236     }
19237 
19238     /*
19239     ** At this point, variables are initialized as follows:
19240     **
19241     **   flag_alternateform          TRUE if a '#' is present.
19242     **   flag_altform2               TRUE if a '!' is present.
19243     **   flag_plussign               TRUE if a '+' is present.
19244     **   flag_leftjustify            TRUE if a '-' is present or if the
19245     **                               field width was negative.
19246     **   flag_zeropad                TRUE if the width began with 0.
19247     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19248     **                               the conversion character.
19249     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19250     **                               the conversion character.
19251     **   flag_blanksign              TRUE if a ' ' is present.
19252     **   width                       The specified field width.  This is
19253     **                               always non-negative.  Zero is the default.
19254     **   precision                   The specified precision.  The default
19255     **                               is -1.
19256     **   xtype                       The class of the conversion.
19257     **   infop                       Pointer to the appropriate info struct.
19258     */
19259     switch( xtype ){
19260       case etPOINTER:
19261         flag_longlong = sizeof(char*)==sizeof(i64);
19262         flag_long = sizeof(char*)==sizeof(long int);
19263         /* Fall through into the next case */
19264       case etORDINAL:
19265       case etRADIX:
19266         if( infop->flags & FLAG_SIGNED ){
19267           i64 v;
19268           if( flag_longlong ){
19269             v = va_arg(ap,i64);
19270           }else if( flag_long ){
19271             v = va_arg(ap,long int);
19272           }else{
19273             v = va_arg(ap,int);
19274           }
19275           if( v<0 ){
19276             if( v==SMALLEST_INT64 ){
19277               longvalue = ((u64)1)<<63;
19278             }else{
19279               longvalue = -v;
19280             }
19281             prefix = '-';
19282           }else{
19283             longvalue = v;
19284             if( flag_plussign )        prefix = '+';
19285             else if( flag_blanksign )  prefix = ' ';
19286             else                       prefix = 0;
19287           }
19288         }else{
19289           if( flag_longlong ){
19290             longvalue = va_arg(ap,u64);
19291           }else if( flag_long ){
19292             longvalue = va_arg(ap,unsigned long int);
19293           }else{
19294             longvalue = va_arg(ap,unsigned int);
19295           }
19296           prefix = 0;
19297         }
19298         if( longvalue==0 ) flag_alternateform = 0;
19299         if( flag_zeropad && precision<width-(prefix!=0) ){
19300           precision = width-(prefix!=0);
19301         }
19302         bufpt = &buf[etBUFSIZE-1];
19303         if( xtype==etORDINAL ){
19304           static const char zOrd[] = "thstndrd";
19305           int x = (int)(longvalue % 10);
19306           if( x>=4 || (longvalue/10)%10==1 ){
19307             x = 0;
19308           }
19309           buf[etBUFSIZE-3] = zOrd[x*2];
19310           buf[etBUFSIZE-2] = zOrd[x*2+1];
19311           bufpt -= 2;
19312         }
19313         {
19314           register const char *cset;      /* Use registers for speed */
19315           register int base;
19316           cset = &aDigits[infop->charset];
19317           base = infop->base;
19318           do{                                           /* Convert to ascii */
19319             *(--bufpt) = cset[longvalue%base];
19320             longvalue = longvalue/base;
19321           }while( longvalue>0 );
19322         }
19323         length = (int)(&buf[etBUFSIZE-1]-bufpt);
19324         for(idx=precision-length; idx>0; idx--){
19325           *(--bufpt) = '0';                             /* Zero pad */
19326         }
19327         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19328         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19329           const char *pre;
19330           char x;
19331           pre = &aPrefix[infop->prefix];
19332           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19333         }
19334         length = (int)(&buf[etBUFSIZE-1]-bufpt);
19335         break;
19336       case etFLOAT:
19337       case etEXP:
19338       case etGENERIC:
19339         realvalue = va_arg(ap,double);
19340 #ifdef SQLITE_OMIT_FLOATING_POINT
19341         length = 0;
19342 #else
19343         if( precision<0 ) precision = 6;         /* Set default precision */
19344         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
19345         if( realvalue<0.0 ){
19346           realvalue = -realvalue;
19347           prefix = '-';
19348         }else{
19349           if( flag_plussign )          prefix = '+';
19350           else if( flag_blanksign )    prefix = ' ';
19351           else                         prefix = 0;
19352         }
19353         if( xtype==etGENERIC && precision>0 ) precision--;
19354 #if 0
19355         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19356         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19357 #else
19358         /* It makes more sense to use 0.5 */
19359         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19360 #endif
19361         if( xtype==etFLOAT ) realvalue += rounder;
19362         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19363         exp = 0;
19364         if( sqlite3IsNaN((double)realvalue) ){
19365           bufpt = "NaN";
19366           length = 3;
19367           break;
19368         }
19369         if( realvalue>0.0 ){
19370           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19371           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19372           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19373           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19374           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19375           if( exp>350 ){
19376             if( prefix=='-' ){
19377               bufpt = "-Inf";
19378             }else if( prefix=='+' ){
19379               bufpt = "+Inf";
19380             }else{
19381               bufpt = "Inf";
19382             }
19383             length = sqlite3Strlen30(bufpt);
19384             break;
19385           }
19386         }
19387         bufpt = buf;
19388         /*
19389         ** If the field type is etGENERIC, then convert to either etEXP
19390         ** or etFLOAT, as appropriate.
19391         */
19392         flag_exp = xtype==etEXP;
19393         if( xtype!=etFLOAT ){
19394           realvalue += rounder;
19395           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19396         }
19397         if( xtype==etGENERIC ){
19398           flag_rtz = !flag_alternateform;
19399           if( exp<-4 || exp>precision ){
19400             xtype = etEXP;
19401           }else{
19402             precision = precision - exp;
19403             xtype = etFLOAT;
19404           }
19405         }else{
19406           flag_rtz = 0;
19407         }
19408         if( xtype==etEXP ){
19409           e2 = 0;
19410         }else{
19411           e2 = exp;
19412         }
19413         nsd = 0;
19414         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19415         /* The sign in front of the number */
19416         if( prefix ){
19417           *(bufpt++) = prefix;
19418         }
19419         /* Digits prior to the decimal point */
19420         if( e2<0 ){
19421           *(bufpt++) = '0';
19422         }else{
19423           for(; e2>=0; e2--){
19424             *(bufpt++) = et_getdigit(&realvalue,&nsd);
19425           }
19426         }
19427         /* The decimal point */
19428         if( flag_dp ){
19429           *(bufpt++) = '.';
19430         }
19431         /* "0" digits after the decimal point but before the first
19432         ** significant digit of the number */
19433         for(e2++; e2<0; precision--, e2++){
19434           assert( precision>0 );
19435           *(bufpt++) = '0';
19436         }
19437         /* Significant digits after the decimal point */
19438         while( (precision--)>0 ){
19439           *(bufpt++) = et_getdigit(&realvalue,&nsd);
19440         }
19441         /* Remove trailing zeros and the "." if no digits follow the "." */
19442         if( flag_rtz && flag_dp ){
19443           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19444           assert( bufpt>buf );
19445           if( bufpt[-1]=='.' ){
19446             if( flag_altform2 ){
19447               *(bufpt++) = '0';
19448             }else{
19449               *(--bufpt) = 0;
19450             }
19451           }
19452         }
19453         /* Add the "eNNN" suffix */
19454         if( flag_exp || xtype==etEXP ){
19455           *(bufpt++) = aDigits[infop->charset];
19456           if( exp<0 ){
19457             *(bufpt++) = '-'; exp = -exp;
19458           }else{
19459             *(bufpt++) = '+';
19460           }
19461           if( exp>=100 ){
19462             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19463             exp %= 100;
19464           }
19465           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19466           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19467         }
19468         *bufpt = 0;
19469 
19470         /* The converted number is in buf[] and zero terminated. Output it.
19471         ** Note that the number is in the usual order, not reversed as with
19472         ** integer conversions. */
19473         length = (int)(bufpt-buf);
19474         bufpt = buf;
19475 
19476         /* Special case:  Add leading zeros if the flag_zeropad flag is
19477         ** set and we are not left justified */
19478         if( flag_zeropad && !flag_leftjustify && length < width){
19479           int i;
19480           int nPad = width - length;
19481           for(i=width; i>=nPad; i--){
19482             bufpt[i] = bufpt[i-nPad];
19483           }
19484           i = prefix!=0;
19485           while( nPad-- ) bufpt[i++] = '0';
19486           length = width;
19487         }
19488 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19489         break;
19490       case etSIZE:
19491         *(va_arg(ap,int*)) = pAccum->nChar;
19492         length = width = 0;
19493         break;
19494       case etPERCENT:
19495         buf[0] = '%';
19496         bufpt = buf;
19497         length = 1;
19498         break;
19499       case etCHARX:
19500         c = va_arg(ap,int);
19501         buf[0] = (char)c;
19502         if( precision>=0 ){
19503           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19504           length = precision;
19505         }else{
19506           length =1;
19507         }
19508         bufpt = buf;
19509         break;
19510       case etSTRING:
19511       case etDYNSTRING:
19512         bufpt = va_arg(ap,char*);
19513         if( bufpt==0 ){
19514           bufpt = "";
19515         }else if( xtype==etDYNSTRING ){
19516           zExtra = bufpt;
19517         }
19518         if( precision>=0 ){
19519           for(length=0; length<precision && bufpt[length]; length++){}
19520         }else{
19521           length = sqlite3Strlen30(bufpt);
19522         }
19523         break;
19524       case etSQLESCAPE:
19525       case etSQLESCAPE2:
19526       case etSQLESCAPE3: {
19527         int i, j, k, n, isnull;
19528         int needQuote;
19529         char ch;
19530         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19531         char *escarg = va_arg(ap,char*);
19532         isnull = escarg==0;
19533         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19534         k = precision;
19535         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19536           if( ch==q )  n++;
19537         }
19538         needQuote = !isnull && xtype==etSQLESCAPE2;
19539         n += i + 1 + needQuote*2;
19540         if( n>etBUFSIZE ){
19541           bufpt = zExtra = sqlite3Malloc( n );
19542           if( bufpt==0 ){
19543             pAccum->mallocFailed = 1;
19544             return;
19545           }
19546         }else{
19547           bufpt = buf;
19548         }
19549         j = 0;
19550         if( needQuote ) bufpt[j++] = q;
19551         k = i;
19552         for(i=0; i<k; i++){
19553           bufpt[j++] = ch = escarg[i];
19554           if( ch==q ) bufpt[j++] = ch;
19555         }
19556         if( needQuote ) bufpt[j++] = q;
19557         bufpt[j] = 0;
19558         length = j;
19559         /* The precision in %q and %Q means how many input characters to
19560         ** consume, not the length of the output...
19561         ** if( precision>=0 && precision<length ) length = precision; */
19562         break;
19563       }
19564       case etTOKEN: {
19565         Token *pToken = va_arg(ap, Token*);
19566         if( pToken ){
19567           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
19568         }
19569         length = width = 0;
19570         break;
19571       }
19572       case etSRCLIST: {
19573         SrcList *pSrc = va_arg(ap, SrcList*);
19574         int k = va_arg(ap, int);
19575         struct SrcList_item *pItem = &pSrc->a[k];
19576         assert( k>=0 && k<pSrc->nSrc );
19577         if( pItem->zDatabase ){
19578           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
19579           sqlite3StrAccumAppend(pAccum, ".", 1);
19580         }
19581         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
19582         length = width = 0;
19583         break;
19584       }
19585       default: {
19586         assert( xtype==etINVALID );
19587         return;
19588       }
19589     }/* End switch over the format type */
19590     /*
19591     ** The text of the conversion is pointed to by "bufpt" and is
19592     ** "length" characters long.  The field width is "width".  Do
19593     ** the output.
19594     */
19595     if( !flag_leftjustify ){
19596       register int nspace;
19597       nspace = width-length;
19598       if( nspace>0 ){
19599         appendSpace(pAccum, nspace);
19600       }
19601     }
19602     if( length>0 ){
19603       sqlite3StrAccumAppend(pAccum, bufpt, length);
19604     }
19605     if( flag_leftjustify ){
19606       register int nspace;
19607       nspace = width-length;
19608       if( nspace>0 ){
19609         appendSpace(pAccum, nspace);
19610       }
19611     }
19612     if( zExtra ){
19613       sqlite3_free(zExtra);
19614     }
19615   }/* End for loop over the format string */
19616 } /* End of function */
19617 
19618 /*
19619 ** Append N bytes of text from z to the StrAccum object.
19620 */
sqlite3StrAccumAppend(StrAccum * p,const char * z,int N)19621 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
19622   assert( z!=0 || N==0 );
19623   if( p->tooBig | p->mallocFailed ){
19624     testcase(p->tooBig);
19625     testcase(p->mallocFailed);
19626     return;
19627   }
19628   if( N<0 ){
19629     N = sqlite3Strlen30(z);
19630   }
19631   if( N==0 || NEVER(z==0) ){
19632     return;
19633   }
19634   if( p->nChar+N >= p->nAlloc ){
19635     char *zNew;
19636     if( !p->useMalloc ){
19637       p->tooBig = 1;
19638       N = p->nAlloc - p->nChar - 1;
19639       if( N<=0 ){
19640         return;
19641       }
19642     }else{
19643       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
19644       i64 szNew = p->nChar;
19645       szNew += N + 1;
19646       if( szNew > p->mxAlloc ){
19647         sqlite3StrAccumReset(p);
19648         p->tooBig = 1;
19649         return;
19650       }else{
19651         p->nAlloc = (int)szNew;
19652       }
19653       if( p->useMalloc==1 ){
19654         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
19655       }else{
19656         zNew = sqlite3_realloc(zOld, p->nAlloc);
19657       }
19658       if( zNew ){
19659         if( zOld==0 ) memcpy(zNew, p->zText, p->nChar);
19660         p->zText = zNew;
19661       }else{
19662         p->mallocFailed = 1;
19663         sqlite3StrAccumReset(p);
19664         return;
19665       }
19666     }
19667   }
19668   memcpy(&p->zText[p->nChar], z, N);
19669   p->nChar += N;
19670 }
19671 
19672 /*
19673 ** Finish off a string by making sure it is zero-terminated.
19674 ** Return a pointer to the resulting string.  Return a NULL
19675 ** pointer if any kind of error was encountered.
19676 */
sqlite3StrAccumFinish(StrAccum * p)19677 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
19678   if( p->zText ){
19679     p->zText[p->nChar] = 0;
19680     if( p->useMalloc && p->zText==p->zBase ){
19681       if( p->useMalloc==1 ){
19682         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
19683       }else{
19684         p->zText = sqlite3_malloc(p->nChar+1);
19685       }
19686       if( p->zText ){
19687         memcpy(p->zText, p->zBase, p->nChar+1);
19688       }else{
19689         p->mallocFailed = 1;
19690       }
19691     }
19692   }
19693   return p->zText;
19694 }
19695 
19696 /*
19697 ** Reset an StrAccum string.  Reclaim all malloced memory.
19698 */
sqlite3StrAccumReset(StrAccum * p)19699 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
19700   if( p->zText!=p->zBase ){
19701     if( p->useMalloc==1 ){
19702       sqlite3DbFree(p->db, p->zText);
19703     }else{
19704       sqlite3_free(p->zText);
19705     }
19706   }
19707   p->zText = 0;
19708 }
19709 
19710 /*
19711 ** Initialize a string accumulator
19712 */
sqlite3StrAccumInit(StrAccum * p,char * zBase,int n,int mx)19713 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
19714   p->zText = p->zBase = zBase;
19715   p->db = 0;
19716   p->nChar = 0;
19717   p->nAlloc = n;
19718   p->mxAlloc = mx;
19719   p->useMalloc = 1;
19720   p->tooBig = 0;
19721   p->mallocFailed = 0;
19722 }
19723 
19724 /*
19725 ** Print into memory obtained from sqliteMalloc().  Use the internal
19726 ** %-conversion extensions.
19727 */
sqlite3VMPrintf(sqlite3 * db,const char * zFormat,va_list ap)19728 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
19729   char *z;
19730   char zBase[SQLITE_PRINT_BUF_SIZE];
19731   StrAccum acc;
19732   assert( db!=0 );
19733   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
19734                       db->aLimit[SQLITE_LIMIT_LENGTH]);
19735   acc.db = db;
19736   sqlite3VXPrintf(&acc, 1, zFormat, ap);
19737   z = sqlite3StrAccumFinish(&acc);
19738   if( acc.mallocFailed ){
19739     db->mallocFailed = 1;
19740   }
19741   return z;
19742 }
19743 
19744 /*
19745 ** Print into memory obtained from sqliteMalloc().  Use the internal
19746 ** %-conversion extensions.
19747 */
sqlite3MPrintf(sqlite3 * db,const char * zFormat,...)19748 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
19749   va_list ap;
19750   char *z;
19751   va_start(ap, zFormat);
19752   z = sqlite3VMPrintf(db, zFormat, ap);
19753   va_end(ap);
19754   return z;
19755 }
19756 
19757 /*
19758 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
19759 ** the string and before returnning.  This routine is intended to be used
19760 ** to modify an existing string.  For example:
19761 **
19762 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
19763 **
19764 */
sqlite3MAppendf(sqlite3 * db,char * zStr,const char * zFormat,...)19765 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
19766   va_list ap;
19767   char *z;
19768   va_start(ap, zFormat);
19769   z = sqlite3VMPrintf(db, zFormat, ap);
19770   va_end(ap);
19771   sqlite3DbFree(db, zStr);
19772   return z;
19773 }
19774 
19775 /*
19776 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
19777 ** %-conversion extensions.
19778 */
sqlite3_vmprintf(const char * zFormat,va_list ap)19779 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
19780   char *z;
19781   char zBase[SQLITE_PRINT_BUF_SIZE];
19782   StrAccum acc;
19783 #ifndef SQLITE_OMIT_AUTOINIT
19784   if( sqlite3_initialize() ) return 0;
19785 #endif
19786   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
19787   acc.useMalloc = 2;
19788   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19789   z = sqlite3StrAccumFinish(&acc);
19790   return z;
19791 }
19792 
19793 /*
19794 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
19795 ** %-conversion extensions.
19796 */
sqlite3_mprintf(const char * zFormat,...)19797 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
19798   va_list ap;
19799   char *z;
19800 #ifndef SQLITE_OMIT_AUTOINIT
19801   if( sqlite3_initialize() ) return 0;
19802 #endif
19803   va_start(ap, zFormat);
19804   z = sqlite3_vmprintf(zFormat, ap);
19805   va_end(ap);
19806   return z;
19807 }
19808 
19809 /*
19810 ** sqlite3_snprintf() works like snprintf() except that it ignores the
19811 ** current locale settings.  This is important for SQLite because we
19812 ** are not able to use a "," as the decimal point in place of "." as
19813 ** specified by some locales.
19814 **
19815 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
19816 ** from the snprintf() standard.  Unfortunately, it is too late to change
19817 ** this without breaking compatibility, so we just have to live with the
19818 ** mistake.
19819 **
19820 ** sqlite3_vsnprintf() is the varargs version.
19821 */
sqlite3_vsnprintf(int n,char * zBuf,const char * zFormat,va_list ap)19822 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
19823   StrAccum acc;
19824   if( n<=0 ) return zBuf;
19825   sqlite3StrAccumInit(&acc, zBuf, n, 0);
19826   acc.useMalloc = 0;
19827   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19828   return sqlite3StrAccumFinish(&acc);
19829 }
sqlite3_snprintf(int n,char * zBuf,const char * zFormat,...)19830 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
19831   char *z;
19832   va_list ap;
19833   va_start(ap,zFormat);
19834   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
19835   va_end(ap);
19836   return z;
19837 }
19838 
19839 /*
19840 ** This is the routine that actually formats the sqlite3_log() message.
19841 ** We house it in a separate routine from sqlite3_log() to avoid using
19842 ** stack space on small-stack systems when logging is disabled.
19843 **
19844 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
19845 ** allocate memory because it might be called while the memory allocator
19846 ** mutex is held.
19847 */
renderLogMsg(int iErrCode,const char * zFormat,va_list ap)19848 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
19849   StrAccum acc;                          /* String accumulator */
19850   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
19851 
19852   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
19853   acc.useMalloc = 0;
19854   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19855   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
19856                            sqlite3StrAccumFinish(&acc));
19857 }
19858 
19859 /*
19860 ** Format and write a message to the log if logging is enabled.
19861 */
sqlite3_log(int iErrCode,const char * zFormat,...)19862 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
19863   va_list ap;                             /* Vararg list */
19864   if( sqlite3GlobalConfig.xLog ){
19865     va_start(ap, zFormat);
19866     renderLogMsg(iErrCode, zFormat, ap);
19867     va_end(ap);
19868   }
19869 }
19870 
19871 #if defined(SQLITE_DEBUG)
19872 /*
19873 ** A version of printf() that understands %lld.  Used for debugging.
19874 ** The printf() built into some versions of windows does not understand %lld
19875 ** and segfaults if you give it a long long int.
19876 */
sqlite3DebugPrintf(const char * zFormat,...)19877 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
19878   va_list ap;
19879   StrAccum acc;
19880   char zBuf[500];
19881   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
19882   acc.useMalloc = 0;
19883   va_start(ap,zFormat);
19884   sqlite3VXPrintf(&acc, 0, zFormat, ap);
19885   va_end(ap);
19886   sqlite3StrAccumFinish(&acc);
19887   fprintf(stdout,"%s", zBuf);
19888   fflush(stdout);
19889 }
19890 #endif
19891 
19892 #ifndef SQLITE_OMIT_TRACE
19893 /*
19894 ** variable-argument wrapper around sqlite3VXPrintf().
19895 */
sqlite3XPrintf(StrAccum * p,const char * zFormat,...)19896 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
19897   va_list ap;
19898   va_start(ap,zFormat);
19899   sqlite3VXPrintf(p, 1, zFormat, ap);
19900   va_end(ap);
19901 }
19902 #endif
19903 
19904 /************** End of printf.c **********************************************/
19905 /************** Begin file random.c ******************************************/
19906 /*
19907 ** 2001 September 15
19908 **
19909 ** The author disclaims copyright to this source code.  In place of
19910 ** a legal notice, here is a blessing:
19911 **
19912 **    May you do good and not evil.
19913 **    May you find forgiveness for yourself and forgive others.
19914 **    May you share freely, never taking more than you give.
19915 **
19916 *************************************************************************
19917 ** This file contains code to implement a pseudo-random number
19918 ** generator (PRNG) for SQLite.
19919 **
19920 ** Random numbers are used by some of the database backends in order
19921 ** to generate random integer keys for tables or random filenames.
19922 */
19923 
19924 
19925 /* All threads share a single random number generator.
19926 ** This structure is the current state of the generator.
19927 */
19928 static SQLITE_WSD struct sqlite3PrngType {
19929   unsigned char isInit;          /* True if initialized */
19930   unsigned char i, j;            /* State variables */
19931   unsigned char s[256];          /* State variables */
19932 } sqlite3Prng;
19933 
19934 /*
19935 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
19936 ** must be held while executing this routine.
19937 **
19938 ** Why not just use a library random generator like lrand48() for this?
19939 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
19940 ** good source of random numbers.  The lrand48() library function may
19941 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
19942 ** subtle problems on some systems that could cause problems.  It is hard
19943 ** to know.  To minimize the risk of problems due to bad lrand48()
19944 ** implementations, SQLite uses this random number generator based
19945 ** on RC4, which we know works very well.
19946 **
19947 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
19948 ** randomness any more.  But we will leave this code in all the same.
19949 */
randomByte(void)19950 static u8 randomByte(void){
19951   unsigned char t;
19952 
19953 
19954   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
19955   ** state vector.  If writable static data is unsupported on the target,
19956   ** we have to locate the state vector at run-time.  In the more common
19957   ** case where writable static data is supported, wsdPrng can refer directly
19958   ** to the "sqlite3Prng" state vector declared above.
19959   */
19960 #ifdef SQLITE_OMIT_WSD
19961   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
19962 # define wsdPrng p[0]
19963 #else
19964 # define wsdPrng sqlite3Prng
19965 #endif
19966 
19967 
19968   /* Initialize the state of the random number generator once,
19969   ** the first time this routine is called.  The seed value does
19970   ** not need to contain a lot of randomness since we are not
19971   ** trying to do secure encryption or anything like that...
19972   **
19973   ** Nothing in this file or anywhere else in SQLite does any kind of
19974   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
19975   ** number generator) not as an encryption device.
19976   */
19977   if( !wsdPrng.isInit ){
19978     int i;
19979     char k[256];
19980     wsdPrng.j = 0;
19981     wsdPrng.i = 0;
19982     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
19983     for(i=0; i<256; i++){
19984       wsdPrng.s[i] = (u8)i;
19985     }
19986     for(i=0; i<256; i++){
19987       wsdPrng.j += wsdPrng.s[i] + k[i];
19988       t = wsdPrng.s[wsdPrng.j];
19989       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
19990       wsdPrng.s[i] = t;
19991     }
19992     wsdPrng.isInit = 1;
19993   }
19994 
19995   /* Generate and return single random byte
19996   */
19997   wsdPrng.i++;
19998   t = wsdPrng.s[wsdPrng.i];
19999   wsdPrng.j += t;
20000   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20001   wsdPrng.s[wsdPrng.j] = t;
20002   t += wsdPrng.s[wsdPrng.i];
20003   return wsdPrng.s[t];
20004 }
20005 
20006 /*
20007 ** Return N random bytes.
20008 */
sqlite3_randomness(int N,void * pBuf)20009 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20010   unsigned char *zBuf = pBuf;
20011 #if SQLITE_THREADSAFE
20012   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20013 #endif
20014   sqlite3_mutex_enter(mutex);
20015   while( N-- ){
20016     *(zBuf++) = randomByte();
20017   }
20018   sqlite3_mutex_leave(mutex);
20019 }
20020 
20021 #ifndef SQLITE_OMIT_BUILTIN_TEST
20022 /*
20023 ** For testing purposes, we sometimes want to preserve the state of
20024 ** PRNG and restore the PRNG to its saved state at a later time, or
20025 ** to reset the PRNG to its initial state.  These routines accomplish
20026 ** those tasks.
20027 **
20028 ** The sqlite3_test_control() interface calls these routines to
20029 ** control the PRNG.
20030 */
20031 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
sqlite3PrngSaveState(void)20032 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20033   memcpy(
20034     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20035     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20036     sizeof(sqlite3Prng)
20037   );
20038 }
sqlite3PrngRestoreState(void)20039 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20040   memcpy(
20041     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20042     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20043     sizeof(sqlite3Prng)
20044   );
20045 }
sqlite3PrngResetState(void)20046 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20047   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20048 }
20049 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20050 
20051 /************** End of random.c **********************************************/
20052 /************** Begin file utf.c *********************************************/
20053 /*
20054 ** 2004 April 13
20055 **
20056 ** The author disclaims copyright to this source code.  In place of
20057 ** a legal notice, here is a blessing:
20058 **
20059 **    May you do good and not evil.
20060 **    May you find forgiveness for yourself and forgive others.
20061 **    May you share freely, never taking more than you give.
20062 **
20063 *************************************************************************
20064 ** This file contains routines used to translate between UTF-8,
20065 ** UTF-16, UTF-16BE, and UTF-16LE.
20066 **
20067 ** Notes on UTF-8:
20068 **
20069 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20070 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20071 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20072 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20073 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20074 **
20075 **
20076 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20077 **
20078 **      Word-0               Word-1          Value
20079 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20080 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20081 **
20082 **
20083 ** BOM or Byte Order Mark:
20084 **     0xff 0xfe   little-endian utf-16 follows
20085 **     0xfe 0xff   big-endian utf-16 follows
20086 **
20087 */
20088 /* #include <assert.h> */
20089 
20090 #ifndef SQLITE_AMALGAMATION
20091 /*
20092 ** The following constant value is used by the SQLITE_BIGENDIAN and
20093 ** SQLITE_LITTLEENDIAN macros.
20094 */
20095 SQLITE_PRIVATE const int sqlite3one = 1;
20096 #endif /* SQLITE_AMALGAMATION */
20097 
20098 /*
20099 ** This lookup table is used to help decode the first byte of
20100 ** a multi-byte UTF8 character.
20101 */
20102 static const unsigned char sqlite3Utf8Trans1[] = {
20103   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20104   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20105   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20106   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20107   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20108   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20109   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20110   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20111 };
20112 
20113 
20114 #define WRITE_UTF8(zOut, c) {                          \
20115   if( c<0x00080 ){                                     \
20116     *zOut++ = (u8)(c&0xFF);                            \
20117   }                                                    \
20118   else if( c<0x00800 ){                                \
20119     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20120     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20121   }                                                    \
20122   else if( c<0x10000 ){                                \
20123     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20124     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20125     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20126   }else{                                               \
20127     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20128     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20129     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20130     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20131   }                                                    \
20132 }
20133 
20134 #define WRITE_UTF16LE(zOut, c) {                                    \
20135   if( c<=0xFFFF ){                                                  \
20136     *zOut++ = (u8)(c&0x00FF);                                       \
20137     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20138   }else{                                                            \
20139     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20140     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20141     *zOut++ = (u8)(c&0x00FF);                                       \
20142     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20143   }                                                                 \
20144 }
20145 
20146 #define WRITE_UTF16BE(zOut, c) {                                    \
20147   if( c<=0xFFFF ){                                                  \
20148     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20149     *zOut++ = (u8)(c&0x00FF);                                       \
20150   }else{                                                            \
20151     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20152     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20153     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20154     *zOut++ = (u8)(c&0x00FF);                                       \
20155   }                                                                 \
20156 }
20157 
20158 #define READ_UTF16LE(zIn, TERM, c){                                   \
20159   c = (*zIn++);                                                       \
20160   c += ((*zIn++)<<8);                                                 \
20161   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20162     int c2 = (*zIn++);                                                \
20163     c2 += ((*zIn++)<<8);                                              \
20164     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20165   }                                                                   \
20166 }
20167 
20168 #define READ_UTF16BE(zIn, TERM, c){                                   \
20169   c = ((*zIn++)<<8);                                                  \
20170   c += (*zIn++);                                                      \
20171   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20172     int c2 = ((*zIn++)<<8);                                           \
20173     c2 += (*zIn++);                                                   \
20174     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20175   }                                                                   \
20176 }
20177 
20178 /*
20179 ** Translate a single UTF-8 character.  Return the unicode value.
20180 **
20181 ** During translation, assume that the byte that zTerm points
20182 ** is a 0x00.
20183 **
20184 ** Write a pointer to the next unread byte back into *pzNext.
20185 **
20186 ** Notes On Invalid UTF-8:
20187 **
20188 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20189 **     be encoded as a multi-byte character.  Any multi-byte character that
20190 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20191 **
20192 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20193 **     If a multi-byte character attempts to encode a value between
20194 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20195 **
20196 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20197 **     byte of a character are interpreted as single-byte characters
20198 **     and rendered as themselves even though they are technically
20199 **     invalid characters.
20200 **
20201 **  *  This routine accepts an infinite number of different UTF8 encodings
20202 **     for unicode values 0x80 and greater.  It do not change over-length
20203 **     encodings to 0xfffd as some systems recommend.
20204 */
20205 #define READ_UTF8(zIn, zTerm, c)                           \
20206   c = *(zIn++);                                            \
20207   if( c>=0xc0 ){                                           \
20208     c = sqlite3Utf8Trans1[c-0xc0];                         \
20209     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20210       c = (c<<6) + (0x3f & *(zIn++));                      \
20211     }                                                      \
20212     if( c<0x80                                             \
20213         || (c&0xFFFFF800)==0xD800                          \
20214         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20215   }
sqlite3Utf8Read(const unsigned char * zIn,const unsigned char ** pzNext)20216 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20217   const unsigned char *zIn,       /* First byte of UTF-8 character */
20218   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20219 ){
20220   unsigned int c;
20221 
20222   /* Same as READ_UTF8() above but without the zTerm parameter.
20223   ** For this routine, we assume the UTF8 string is always zero-terminated.
20224   */
20225   c = *(zIn++);
20226   if( c>=0xc0 ){
20227     c = sqlite3Utf8Trans1[c-0xc0];
20228     while( (*zIn & 0xc0)==0x80 ){
20229       c = (c<<6) + (0x3f & *(zIn++));
20230     }
20231     if( c<0x80
20232         || (c&0xFFFFF800)==0xD800
20233         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20234   }
20235   *pzNext = zIn;
20236   return c;
20237 }
20238 
20239 
20240 
20241 
20242 /*
20243 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20244 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20245 */
20246 /* #define TRANSLATE_TRACE 1 */
20247 
20248 #ifndef SQLITE_OMIT_UTF16
20249 /*
20250 ** This routine transforms the internal text encoding used by pMem to
20251 ** desiredEnc. It is an error if the string is already of the desired
20252 ** encoding, or if *pMem does not contain a string value.
20253 */
sqlite3VdbeMemTranslate(Mem * pMem,u8 desiredEnc)20254 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20255   int len;                    /* Maximum length of output string in bytes */
20256   unsigned char *zOut;                  /* Output buffer */
20257   unsigned char *zIn;                   /* Input iterator */
20258   unsigned char *zTerm;                 /* End of input */
20259   unsigned char *z;                     /* Output iterator */
20260   unsigned int c;
20261 
20262   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20263   assert( pMem->flags&MEM_Str );
20264   assert( pMem->enc!=desiredEnc );
20265   assert( pMem->enc!=0 );
20266   assert( pMem->n>=0 );
20267 
20268 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20269   {
20270     char zBuf[100];
20271     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20272     fprintf(stderr, "INPUT:  %s\n", zBuf);
20273   }
20274 #endif
20275 
20276   /* If the translation is between UTF-16 little and big endian, then
20277   ** all that is required is to swap the byte order. This case is handled
20278   ** differently from the others.
20279   */
20280   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20281     u8 temp;
20282     int rc;
20283     rc = sqlite3VdbeMemMakeWriteable(pMem);
20284     if( rc!=SQLITE_OK ){
20285       assert( rc==SQLITE_NOMEM );
20286       return SQLITE_NOMEM;
20287     }
20288     zIn = (u8*)pMem->z;
20289     zTerm = &zIn[pMem->n&~1];
20290     while( zIn<zTerm ){
20291       temp = *zIn;
20292       *zIn = *(zIn+1);
20293       zIn++;
20294       *zIn++ = temp;
20295     }
20296     pMem->enc = desiredEnc;
20297     goto translate_out;
20298   }
20299 
20300   /* Set len to the maximum number of bytes required in the output buffer. */
20301   if( desiredEnc==SQLITE_UTF8 ){
20302     /* When converting from UTF-16, the maximum growth results from
20303     ** translating a 2-byte character to a 4-byte UTF-8 character.
20304     ** A single byte is required for the output string
20305     ** nul-terminator.
20306     */
20307     pMem->n &= ~1;
20308     len = pMem->n * 2 + 1;
20309   }else{
20310     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20311     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20312     ** character. Two bytes are required in the output buffer for the
20313     ** nul-terminator.
20314     */
20315     len = pMem->n * 2 + 2;
20316   }
20317 
20318   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20319   ** byte past the end.
20320   **
20321   ** Variable zOut is set to point at the output buffer, space obtained
20322   ** from sqlite3_malloc().
20323   */
20324   zIn = (u8*)pMem->z;
20325   zTerm = &zIn[pMem->n];
20326   zOut = sqlite3DbMallocRaw(pMem->db, len);
20327   if( !zOut ){
20328     return SQLITE_NOMEM;
20329   }
20330   z = zOut;
20331 
20332   if( pMem->enc==SQLITE_UTF8 ){
20333     if( desiredEnc==SQLITE_UTF16LE ){
20334       /* UTF-8 -> UTF-16 Little-endian */
20335       while( zIn<zTerm ){
20336         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20337         READ_UTF8(zIn, zTerm, c);
20338         WRITE_UTF16LE(z, c);
20339       }
20340     }else{
20341       assert( desiredEnc==SQLITE_UTF16BE );
20342       /* UTF-8 -> UTF-16 Big-endian */
20343       while( zIn<zTerm ){
20344         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20345         READ_UTF8(zIn, zTerm, c);
20346         WRITE_UTF16BE(z, c);
20347       }
20348     }
20349     pMem->n = (int)(z - zOut);
20350     *z++ = 0;
20351   }else{
20352     assert( desiredEnc==SQLITE_UTF8 );
20353     if( pMem->enc==SQLITE_UTF16LE ){
20354       /* UTF-16 Little-endian -> UTF-8 */
20355       while( zIn<zTerm ){
20356         READ_UTF16LE(zIn, zIn<zTerm, c);
20357         WRITE_UTF8(z, c);
20358       }
20359     }else{
20360       /* UTF-16 Big-endian -> UTF-8 */
20361       while( zIn<zTerm ){
20362         READ_UTF16BE(zIn, zIn<zTerm, c);
20363         WRITE_UTF8(z, c);
20364       }
20365     }
20366     pMem->n = (int)(z - zOut);
20367   }
20368   *z = 0;
20369   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20370 
20371   sqlite3VdbeMemRelease(pMem);
20372   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20373   pMem->enc = desiredEnc;
20374   pMem->flags |= (MEM_Term|MEM_Dyn);
20375   pMem->z = (char*)zOut;
20376   pMem->zMalloc = pMem->z;
20377 
20378 translate_out:
20379 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20380   {
20381     char zBuf[100];
20382     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20383     fprintf(stderr, "OUTPUT: %s\n", zBuf);
20384   }
20385 #endif
20386   return SQLITE_OK;
20387 }
20388 
20389 /*
20390 ** This routine checks for a byte-order mark at the beginning of the
20391 ** UTF-16 string stored in *pMem. If one is present, it is removed and
20392 ** the encoding of the Mem adjusted. This routine does not do any
20393 ** byte-swapping, it just sets Mem.enc appropriately.
20394 **
20395 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
20396 ** changed by this function.
20397 */
sqlite3VdbeMemHandleBom(Mem * pMem)20398 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20399   int rc = SQLITE_OK;
20400   u8 bom = 0;
20401 
20402   assert( pMem->n>=0 );
20403   if( pMem->n>1 ){
20404     u8 b1 = *(u8 *)pMem->z;
20405     u8 b2 = *(((u8 *)pMem->z) + 1);
20406     if( b1==0xFE && b2==0xFF ){
20407       bom = SQLITE_UTF16BE;
20408     }
20409     if( b1==0xFF && b2==0xFE ){
20410       bom = SQLITE_UTF16LE;
20411     }
20412   }
20413 
20414   if( bom ){
20415     rc = sqlite3VdbeMemMakeWriteable(pMem);
20416     if( rc==SQLITE_OK ){
20417       pMem->n -= 2;
20418       memmove(pMem->z, &pMem->z[2], pMem->n);
20419       pMem->z[pMem->n] = '\0';
20420       pMem->z[pMem->n+1] = '\0';
20421       pMem->flags |= MEM_Term;
20422       pMem->enc = bom;
20423     }
20424   }
20425   return rc;
20426 }
20427 #endif /* SQLITE_OMIT_UTF16 */
20428 
20429 /*
20430 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20431 ** return the number of unicode characters in pZ up to (but not including)
20432 ** the first 0x00 byte. If nByte is not less than zero, return the
20433 ** number of unicode characters in the first nByte of pZ (or up to
20434 ** the first 0x00, whichever comes first).
20435 */
sqlite3Utf8CharLen(const char * zIn,int nByte)20436 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20437   int r = 0;
20438   const u8 *z = (const u8*)zIn;
20439   const u8 *zTerm;
20440   if( nByte>=0 ){
20441     zTerm = &z[nByte];
20442   }else{
20443     zTerm = (const u8*)(-1);
20444   }
20445   assert( z<=zTerm );
20446   while( *z!=0 && z<zTerm ){
20447     SQLITE_SKIP_UTF8(z);
20448     r++;
20449   }
20450   return r;
20451 }
20452 
20453 /* This test function is not currently used by the automated test-suite.
20454 ** Hence it is only available in debug builds.
20455 */
20456 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20457 /*
20458 ** Translate UTF-8 to UTF-8.
20459 **
20460 ** This has the effect of making sure that the string is well-formed
20461 ** UTF-8.  Miscoded characters are removed.
20462 **
20463 ** The translation is done in-place and aborted if the output
20464 ** overruns the input.
20465 */
sqlite3Utf8To8(unsigned char * zIn)20466 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20467   unsigned char *zOut = zIn;
20468   unsigned char *zStart = zIn;
20469   u32 c;
20470 
20471   while( zIn[0] && zOut<=zIn ){
20472     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20473     if( c!=0xfffd ){
20474       WRITE_UTF8(zOut, c);
20475     }
20476   }
20477   *zOut = 0;
20478   return (int)(zOut - zStart);
20479 }
20480 #endif
20481 
20482 #ifndef SQLITE_OMIT_UTF16
20483 /*
20484 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20485 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20486 ** be freed by the calling function.
20487 **
20488 ** NULL is returned if there is an allocation error.
20489 */
sqlite3Utf16to8(sqlite3 * db,const void * z,int nByte,u8 enc)20490 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20491   Mem m;
20492   memset(&m, 0, sizeof(m));
20493   m.db = db;
20494   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20495   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20496   if( db->mallocFailed ){
20497     sqlite3VdbeMemRelease(&m);
20498     m.z = 0;
20499   }
20500   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20501   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20502   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20503   assert( m.z || db->mallocFailed );
20504   return m.z;
20505 }
20506 
20507 /*
20508 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20509 ** enc. A pointer to the new string is returned, and the value of *pnOut
20510 ** is set to the length of the returned string in bytes. The call should
20511 ** arrange to call sqlite3DbFree() on the returned pointer when it is
20512 ** no longer required.
20513 **
20514 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20515 ** flag set.
20516 */
20517 #ifdef SQLITE_ENABLE_STAT2
sqlite3Utf8to16(sqlite3 * db,u8 enc,char * z,int n,int * pnOut)20518 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20519   Mem m;
20520   memset(&m, 0, sizeof(m));
20521   m.db = db;
20522   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20523   if( sqlite3VdbeMemTranslate(&m, enc) ){
20524     assert( db->mallocFailed );
20525     return 0;
20526   }
20527   assert( m.z==m.zMalloc );
20528   *pnOut = m.n;
20529   return m.z;
20530 }
20531 #endif
20532 
20533 /*
20534 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20535 ** Return the number of bytes in the first nChar unicode characters
20536 ** in pZ.  nChar must be non-negative.
20537 */
sqlite3Utf16ByteLen(const void * zIn,int nChar)20538 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20539   int c;
20540   unsigned char const *z = zIn;
20541   int n = 0;
20542 
20543   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20544     while( n<nChar ){
20545       READ_UTF16BE(z, 1, c);
20546       n++;
20547     }
20548   }else{
20549     while( n<nChar ){
20550       READ_UTF16LE(z, 1, c);
20551       n++;
20552     }
20553   }
20554   return (int)(z-(unsigned char const *)zIn);
20555 }
20556 
20557 #if defined(SQLITE_TEST)
20558 /*
20559 ** This routine is called from the TCL test function "translate_selftest".
20560 ** It checks that the primitives for serializing and deserializing
20561 ** characters in each encoding are inverses of each other.
20562 */
sqlite3UtfSelfTest(void)20563 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20564   unsigned int i, t;
20565   unsigned char zBuf[20];
20566   unsigned char *z;
20567   int n;
20568   unsigned int c;
20569 
20570   for(i=0; i<0x00110000; i++){
20571     z = zBuf;
20572     WRITE_UTF8(z, i);
20573     n = (int)(z-zBuf);
20574     assert( n>0 && n<=4 );
20575     z[0] = 0;
20576     z = zBuf;
20577     c = sqlite3Utf8Read(z, (const u8**)&z);
20578     t = i;
20579     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
20580     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
20581     assert( c==t );
20582     assert( (z-zBuf)==n );
20583   }
20584   for(i=0; i<0x00110000; i++){
20585     if( i>=0xD800 && i<0xE000 ) continue;
20586     z = zBuf;
20587     WRITE_UTF16LE(z, i);
20588     n = (int)(z-zBuf);
20589     assert( n>0 && n<=4 );
20590     z[0] = 0;
20591     z = zBuf;
20592     READ_UTF16LE(z, 1, c);
20593     assert( c==i );
20594     assert( (z-zBuf)==n );
20595   }
20596   for(i=0; i<0x00110000; i++){
20597     if( i>=0xD800 && i<0xE000 ) continue;
20598     z = zBuf;
20599     WRITE_UTF16BE(z, i);
20600     n = (int)(z-zBuf);
20601     assert( n>0 && n<=4 );
20602     z[0] = 0;
20603     z = zBuf;
20604     READ_UTF16BE(z, 1, c);
20605     assert( c==i );
20606     assert( (z-zBuf)==n );
20607   }
20608 }
20609 #endif /* SQLITE_TEST */
20610 #endif /* SQLITE_OMIT_UTF16 */
20611 
20612 /************** End of utf.c *************************************************/
20613 /************** Begin file util.c ********************************************/
20614 /*
20615 ** 2001 September 15
20616 **
20617 ** The author disclaims copyright to this source code.  In place of
20618 ** a legal notice, here is a blessing:
20619 **
20620 **    May you do good and not evil.
20621 **    May you find forgiveness for yourself and forgive others.
20622 **    May you share freely, never taking more than you give.
20623 **
20624 *************************************************************************
20625 ** Utility functions used throughout sqlite.
20626 **
20627 ** This file contains functions for allocating memory, comparing
20628 ** strings, and stuff like that.
20629 **
20630 */
20631 /* #include <stdarg.h> */
20632 #ifdef SQLITE_HAVE_ISNAN
20633 # include <math.h>
20634 #endif
20635 
20636 /*
20637 ** Routine needed to support the testcase() macro.
20638 */
20639 #ifdef SQLITE_COVERAGE_TEST
sqlite3Coverage(int x)20640 SQLITE_PRIVATE void sqlite3Coverage(int x){
20641   static unsigned dummy = 0;
20642   dummy += (unsigned)x;
20643 }
20644 #endif
20645 
20646 #ifndef SQLITE_OMIT_FLOATING_POINT
20647 /*
20648 ** Return true if the floating point value is Not a Number (NaN).
20649 **
20650 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
20651 ** Otherwise, we have our own implementation that works on most systems.
20652 */
sqlite3IsNaN(double x)20653 SQLITE_PRIVATE int sqlite3IsNaN(double x){
20654   int rc;   /* The value return */
20655 #if !defined(SQLITE_HAVE_ISNAN)
20656   /*
20657   ** Systems that support the isnan() library function should probably
20658   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
20659   ** found that many systems do not have a working isnan() function so
20660   ** this implementation is provided as an alternative.
20661   **
20662   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
20663   ** On the other hand, the use of -ffast-math comes with the following
20664   ** warning:
20665   **
20666   **      This option [-ffast-math] should never be turned on by any
20667   **      -O option since it can result in incorrect output for programs
20668   **      which depend on an exact implementation of IEEE or ISO
20669   **      rules/specifications for math functions.
20670   **
20671   ** Under MSVC, this NaN test may fail if compiled with a floating-
20672   ** point precision mode other than /fp:precise.  From the MSDN
20673   ** documentation:
20674   **
20675   **      The compiler [with /fp:precise] will properly handle comparisons
20676   **      involving NaN. For example, x != x evaluates to true if x is NaN
20677   **      ...
20678   */
20679 #ifdef __FAST_MATH__
20680 # error SQLite will not work correctly with the -ffast-math option of GCC.
20681 #endif
20682   volatile double y = x;
20683   volatile double z = y;
20684   rc = (y!=z);
20685 #else  /* if defined(SQLITE_HAVE_ISNAN) */
20686   rc = isnan(x);
20687 #endif /* SQLITE_HAVE_ISNAN */
20688   testcase( rc );
20689   return rc;
20690 }
20691 #endif /* SQLITE_OMIT_FLOATING_POINT */
20692 
20693 /*
20694 ** Compute a string length that is limited to what can be stored in
20695 ** lower 30 bits of a 32-bit signed integer.
20696 **
20697 ** The value returned will never be negative.  Nor will it ever be greater
20698 ** than the actual length of the string.  For very long strings (greater
20699 ** than 1GiB) the value returned might be less than the true string length.
20700 */
sqlite3Strlen30(const char * z)20701 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
20702   const char *z2 = z;
20703   if( z==0 ) return 0;
20704   while( *z2 ){ z2++; }
20705   return 0x3fffffff & (int)(z2 - z);
20706 }
20707 
20708 /*
20709 ** Set the most recent error code and error string for the sqlite
20710 ** handle "db". The error code is set to "err_code".
20711 **
20712 ** If it is not NULL, string zFormat specifies the format of the
20713 ** error string in the style of the printf functions: The following
20714 ** format characters are allowed:
20715 **
20716 **      %s      Insert a string
20717 **      %z      A string that should be freed after use
20718 **      %d      Insert an integer
20719 **      %T      Insert a token
20720 **      %S      Insert the first element of a SrcList
20721 **
20722 ** zFormat and any string tokens that follow it are assumed to be
20723 ** encoded in UTF-8.
20724 **
20725 ** To clear the most recent error for sqlite handle "db", sqlite3Error
20726 ** should be called with err_code set to SQLITE_OK and zFormat set
20727 ** to NULL.
20728 */
sqlite3Error(sqlite3 * db,int err_code,const char * zFormat,...)20729 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
20730   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
20731     db->errCode = err_code;
20732     if( zFormat ){
20733       char *z;
20734       va_list ap;
20735       va_start(ap, zFormat);
20736       z = sqlite3VMPrintf(db, zFormat, ap);
20737       va_end(ap);
20738       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
20739     }else{
20740       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
20741     }
20742   }
20743 }
20744 
20745 /*
20746 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
20747 ** The following formatting characters are allowed:
20748 **
20749 **      %s      Insert a string
20750 **      %z      A string that should be freed after use
20751 **      %d      Insert an integer
20752 **      %T      Insert a token
20753 **      %S      Insert the first element of a SrcList
20754 **
20755 ** This function should be used to report any error that occurs whilst
20756 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
20757 ** last thing the sqlite3_prepare() function does is copy the error
20758 ** stored by this function into the database handle using sqlite3Error().
20759 ** Function sqlite3Error() should be used during statement execution
20760 ** (sqlite3_step() etc.).
20761 */
sqlite3ErrorMsg(Parse * pParse,const char * zFormat,...)20762 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
20763   char *zMsg;
20764   va_list ap;
20765   sqlite3 *db = pParse->db;
20766   va_start(ap, zFormat);
20767   zMsg = sqlite3VMPrintf(db, zFormat, ap);
20768   va_end(ap);
20769   if( db->suppressErr ){
20770     sqlite3DbFree(db, zMsg);
20771   }else{
20772     pParse->nErr++;
20773     sqlite3DbFree(db, pParse->zErrMsg);
20774     pParse->zErrMsg = zMsg;
20775     pParse->rc = SQLITE_ERROR;
20776   }
20777 }
20778 
20779 /*
20780 ** Convert an SQL-style quoted string into a normal string by removing
20781 ** the quote characters.  The conversion is done in-place.  If the
20782 ** input does not begin with a quote character, then this routine
20783 ** is a no-op.
20784 **
20785 ** The input string must be zero-terminated.  A new zero-terminator
20786 ** is added to the dequoted string.
20787 **
20788 ** The return value is -1 if no dequoting occurs or the length of the
20789 ** dequoted string, exclusive of the zero terminator, if dequoting does
20790 ** occur.
20791 **
20792 ** 2002-Feb-14: This routine is extended to remove MS-Access style
20793 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
20794 ** "a-b-c".
20795 */
sqlite3Dequote(char * z)20796 SQLITE_PRIVATE int sqlite3Dequote(char *z){
20797   char quote;
20798   int i, j;
20799   if( z==0 ) return -1;
20800   quote = z[0];
20801   switch( quote ){
20802     case '\'':  break;
20803     case '"':   break;
20804     case '`':   break;                /* For MySQL compatibility */
20805     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
20806     default:    return -1;
20807   }
20808   for(i=1, j=0; ALWAYS(z[i]); i++){
20809     if( z[i]==quote ){
20810       if( z[i+1]==quote ){
20811         z[j++] = quote;
20812         i++;
20813       }else{
20814         break;
20815       }
20816     }else{
20817       z[j++] = z[i];
20818     }
20819   }
20820   z[j] = 0;
20821   return j;
20822 }
20823 
20824 /* Convenient short-hand */
20825 #define UpperToLower sqlite3UpperToLower
20826 
20827 /*
20828 ** Some systems have stricmp().  Others have strcasecmp().  Because
20829 ** there is no consistency, we will define our own.
20830 **
20831 ** IMPLEMENTATION-OF: R-20522-24639 The sqlite3_strnicmp() API allows
20832 ** applications and extensions to compare the contents of two buffers
20833 ** containing UTF-8 strings in a case-independent fashion, using the same
20834 ** definition of case independence that SQLite uses internally when
20835 ** comparing identifiers.
20836 */
sqlite3StrICmp(const char * zLeft,const char * zRight)20837 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
20838   register unsigned char *a, *b;
20839   a = (unsigned char *)zLeft;
20840   b = (unsigned char *)zRight;
20841   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20842   return UpperToLower[*a] - UpperToLower[*b];
20843 }
sqlite3_strnicmp(const char * zLeft,const char * zRight,int N)20844 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
20845   register unsigned char *a, *b;
20846   a = (unsigned char *)zLeft;
20847   b = (unsigned char *)zRight;
20848   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
20849   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
20850 }
20851 
20852 /*
20853 ** The string z[] is an text representation of a real number.
20854 ** Convert this string to a double and write it into *pResult.
20855 **
20856 ** The string z[] is length bytes in length (bytes, not characters) and
20857 ** uses the encoding enc.  The string is not necessarily zero-terminated.
20858 **
20859 ** Return TRUE if the result is a valid real number (or integer) and FALSE
20860 ** if the string is empty or contains extraneous text.  Valid numbers
20861 ** are in one of these formats:
20862 **
20863 **    [+-]digits[E[+-]digits]
20864 **    [+-]digits.[digits][E[+-]digits]
20865 **    [+-].digits[E[+-]digits]
20866 **
20867 ** Leading and trailing whitespace is ignored for the purpose of determining
20868 ** validity.
20869 **
20870 ** If some prefix of the input string is a valid number, this routine
20871 ** returns FALSE but it still converts the prefix and writes the result
20872 ** into *pResult.
20873 */
sqlite3AtoF(const char * z,double * pResult,int length,u8 enc)20874 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
20875 #ifndef SQLITE_OMIT_FLOATING_POINT
20876   int incr = (enc==SQLITE_UTF8?1:2);
20877   const char *zEnd = z + length;
20878   /* sign * significand * (10 ^ (esign * exponent)) */
20879   int sign = 1;    /* sign of significand */
20880   i64 s = 0;       /* significand */
20881   int d = 0;       /* adjust exponent for shifting decimal point */
20882   int esign = 1;   /* sign of exponent */
20883   int e = 0;       /* exponent */
20884   int eValid = 1;  /* True exponent is either not used or is well-formed */
20885   double result;
20886   int nDigits = 0;
20887 
20888   *pResult = 0.0;   /* Default return value, in case of an error */
20889 
20890   if( enc==SQLITE_UTF16BE ) z++;
20891 
20892   /* skip leading spaces */
20893   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20894   if( z>=zEnd ) return 0;
20895 
20896   /* get sign of significand */
20897   if( *z=='-' ){
20898     sign = -1;
20899     z+=incr;
20900   }else if( *z=='+' ){
20901     z+=incr;
20902   }
20903 
20904   /* skip leading zeroes */
20905   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
20906 
20907   /* copy max significant digits to significand */
20908   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20909     s = s*10 + (*z - '0');
20910     z+=incr, nDigits++;
20911   }
20912 
20913   /* skip non-significant significand digits
20914   ** (increase exponent by d to shift decimal left) */
20915   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
20916   if( z>=zEnd ) goto do_atof_calc;
20917 
20918   /* if decimal point is present */
20919   if( *z=='.' ){
20920     z+=incr;
20921     /* copy digits from after decimal to significand
20922     ** (decrease exponent by d to shift decimal right) */
20923     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
20924       s = s*10 + (*z - '0');
20925       z+=incr, nDigits++, d--;
20926     }
20927     /* skip non-significant digits */
20928     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
20929   }
20930   if( z>=zEnd ) goto do_atof_calc;
20931 
20932   /* if exponent is present */
20933   if( *z=='e' || *z=='E' ){
20934     z+=incr;
20935     eValid = 0;
20936     if( z>=zEnd ) goto do_atof_calc;
20937     /* get sign of exponent */
20938     if( *z=='-' ){
20939       esign = -1;
20940       z+=incr;
20941     }else if( *z=='+' ){
20942       z+=incr;
20943     }
20944     /* copy digits to exponent */
20945     while( z<zEnd && sqlite3Isdigit(*z) ){
20946       e = e*10 + (*z - '0');
20947       z+=incr;
20948       eValid = 1;
20949     }
20950   }
20951 
20952   /* skip trailing spaces */
20953   if( nDigits && eValid ){
20954     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
20955   }
20956 
20957 do_atof_calc:
20958   /* adjust exponent by d, and update sign */
20959   e = (e*esign) + d;
20960   if( e<0 ) {
20961     esign = -1;
20962     e *= -1;
20963   } else {
20964     esign = 1;
20965   }
20966 
20967   /* if 0 significand */
20968   if( !s ) {
20969     /* In the IEEE 754 standard, zero is signed.
20970     ** Add the sign if we've seen at least one digit */
20971     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
20972   } else {
20973     /* attempt to reduce exponent */
20974     if( esign>0 ){
20975       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
20976     }else{
20977       while( !(s%10) && e>0 ) e--,s/=10;
20978     }
20979 
20980     /* adjust the sign of significand */
20981     s = sign<0 ? -s : s;
20982 
20983     /* if exponent, scale significand as appropriate
20984     ** and store in result. */
20985     if( e ){
20986       double scale = 1.0;
20987       /* attempt to handle extremely small/large numbers better */
20988       if( e>307 && e<342 ){
20989         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
20990         if( esign<0 ){
20991           result = s / scale;
20992           result /= 1.0e+308;
20993         }else{
20994           result = s * scale;
20995           result *= 1.0e+308;
20996         }
20997       }else{
20998         /* 1.0e+22 is the largest power of 10 than can be
20999         ** represented exactly. */
21000         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21001         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21002         if( esign<0 ){
21003           result = s / scale;
21004         }else{
21005           result = s * scale;
21006         }
21007       }
21008     } else {
21009       result = (double)s;
21010     }
21011   }
21012 
21013   /* store the result */
21014   *pResult = result;
21015 
21016   /* return true if number and no extra non-whitespace chracters after */
21017   return z>=zEnd && nDigits>0 && eValid;
21018 #else
21019   return !sqlite3Atoi64(z, pResult, length, enc);
21020 #endif /* SQLITE_OMIT_FLOATING_POINT */
21021 }
21022 
21023 /*
21024 ** Compare the 19-character string zNum against the text representation
21025 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21026 ** if zNum is less than, equal to, or greater than the string.
21027 ** Note that zNum must contain exactly 19 characters.
21028 **
21029 ** Unlike memcmp() this routine is guaranteed to return the difference
21030 ** in the values of the last digit if the only difference is in the
21031 ** last digit.  So, for example,
21032 **
21033 **      compare2pow63("9223372036854775800", 1)
21034 **
21035 ** will return -8.
21036 */
compare2pow63(const char * zNum,int incr)21037 static int compare2pow63(const char *zNum, int incr){
21038   int c = 0;
21039   int i;
21040                     /* 012345678901234567 */
21041   const char *pow63 = "922337203685477580";
21042   for(i=0; c==0 && i<18; i++){
21043     c = (zNum[i*incr]-pow63[i])*10;
21044   }
21045   if( c==0 ){
21046     c = zNum[18*incr] - '8';
21047     testcase( c==(-1) );
21048     testcase( c==0 );
21049     testcase( c==(+1) );
21050   }
21051   return c;
21052 }
21053 
21054 
21055 /*
21056 ** Convert zNum to a 64-bit signed integer.
21057 **
21058 ** If the zNum value is representable as a 64-bit twos-complement
21059 ** integer, then write that value into *pNum and return 0.
21060 **
21061 ** If zNum is exactly 9223372036854665808, return 2.  This special
21062 ** case is broken out because while 9223372036854665808 cannot be a
21063 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21064 **
21065 ** If zNum is too big for a 64-bit integer and is not
21066 ** 9223372036854665808 then return 1.
21067 **
21068 ** length is the number of bytes in the string (bytes, not characters).
21069 ** The string is not necessarily zero-terminated.  The encoding is
21070 ** given by enc.
21071 */
sqlite3Atoi64(const char * zNum,i64 * pNum,int length,u8 enc)21072 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21073   int incr = (enc==SQLITE_UTF8?1:2);
21074   u64 u = 0;
21075   int neg = 0; /* assume positive */
21076   int i;
21077   int c = 0;
21078   const char *zStart;
21079   const char *zEnd = zNum + length;
21080   if( enc==SQLITE_UTF16BE ) zNum++;
21081   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21082   if( zNum<zEnd ){
21083     if( *zNum=='-' ){
21084       neg = 1;
21085       zNum+=incr;
21086     }else if( *zNum=='+' ){
21087       zNum+=incr;
21088     }
21089   }
21090   zStart = zNum;
21091   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21092   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21093     u = u*10 + c - '0';
21094   }
21095   if( u>LARGEST_INT64 ){
21096     *pNum = SMALLEST_INT64;
21097   }else if( neg ){
21098     *pNum = -(i64)u;
21099   }else{
21100     *pNum = (i64)u;
21101   }
21102   testcase( i==18 );
21103   testcase( i==19 );
21104   testcase( i==20 );
21105   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21106     /* zNum is empty or contains non-numeric text or is longer
21107     ** than 19 digits (thus guaranteeing that it is too large) */
21108     return 1;
21109   }else if( i<19*incr ){
21110     /* Less than 19 digits, so we know that it fits in 64 bits */
21111     assert( u<=LARGEST_INT64 );
21112     return 0;
21113   }else{
21114     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21115     c = compare2pow63(zNum, incr);
21116     if( c<0 ){
21117       /* zNum is less than 9223372036854775808 so it fits */
21118       assert( u<=LARGEST_INT64 );
21119       return 0;
21120     }else if( c>0 ){
21121       /* zNum is greater than 9223372036854775808 so it overflows */
21122       return 1;
21123     }else{
21124       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21125       ** special case 2 overflow if positive */
21126       assert( u-1==LARGEST_INT64 );
21127       assert( (*pNum)==SMALLEST_INT64 );
21128       return neg ? 0 : 2;
21129     }
21130   }
21131 }
21132 
21133 /*
21134 ** If zNum represents an integer that will fit in 32-bits, then set
21135 ** *pValue to that integer and return true.  Otherwise return false.
21136 **
21137 ** Any non-numeric characters that following zNum are ignored.
21138 ** This is different from sqlite3Atoi64() which requires the
21139 ** input number to be zero-terminated.
21140 */
sqlite3GetInt32(const char * zNum,int * pValue)21141 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21142   sqlite_int64 v = 0;
21143   int i, c;
21144   int neg = 0;
21145   if( zNum[0]=='-' ){
21146     neg = 1;
21147     zNum++;
21148   }else if( zNum[0]=='+' ){
21149     zNum++;
21150   }
21151   while( zNum[0]=='0' ) zNum++;
21152   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21153     v = v*10 + c;
21154   }
21155 
21156   /* The longest decimal representation of a 32 bit integer is 10 digits:
21157   **
21158   **             1234567890
21159   **     2^31 -> 2147483648
21160   */
21161   testcase( i==10 );
21162   if( i>10 ){
21163     return 0;
21164   }
21165   testcase( v-neg==2147483647 );
21166   if( v-neg>2147483647 ){
21167     return 0;
21168   }
21169   if( neg ){
21170     v = -v;
21171   }
21172   *pValue = (int)v;
21173   return 1;
21174 }
21175 
21176 /*
21177 ** Return a 32-bit integer value extracted from a string.  If the
21178 ** string is not an integer, just return 0.
21179 */
sqlite3Atoi(const char * z)21180 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21181   int x = 0;
21182   if( z ) sqlite3GetInt32(z, &x);
21183   return x;
21184 }
21185 
21186 /*
21187 ** The variable-length integer encoding is as follows:
21188 **
21189 ** KEY:
21190 **         A = 0xxxxxxx    7 bits of data and one flag bit
21191 **         B = 1xxxxxxx    7 bits of data and one flag bit
21192 **         C = xxxxxxxx    8 bits of data
21193 **
21194 **  7 bits - A
21195 ** 14 bits - BA
21196 ** 21 bits - BBA
21197 ** 28 bits - BBBA
21198 ** 35 bits - BBBBA
21199 ** 42 bits - BBBBBA
21200 ** 49 bits - BBBBBBA
21201 ** 56 bits - BBBBBBBA
21202 ** 64 bits - BBBBBBBBC
21203 */
21204 
21205 /*
21206 ** Write a 64-bit variable-length integer to memory starting at p[0].
21207 ** The length of data write will be between 1 and 9 bytes.  The number
21208 ** of bytes written is returned.
21209 **
21210 ** A variable-length integer consists of the lower 7 bits of each byte
21211 ** for all bytes that have the 8th bit set and one byte with the 8th
21212 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21213 ** 8 bits and is the last byte.
21214 */
sqlite3PutVarint(unsigned char * p,u64 v)21215 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21216   int i, j, n;
21217   u8 buf[10];
21218   if( v & (((u64)0xff000000)<<32) ){
21219     p[8] = (u8)v;
21220     v >>= 8;
21221     for(i=7; i>=0; i--){
21222       p[i] = (u8)((v & 0x7f) | 0x80);
21223       v >>= 7;
21224     }
21225     return 9;
21226   }
21227   n = 0;
21228   do{
21229     buf[n++] = (u8)((v & 0x7f) | 0x80);
21230     v >>= 7;
21231   }while( v!=0 );
21232   buf[0] &= 0x7f;
21233   assert( n<=9 );
21234   for(i=0, j=n-1; j>=0; j--, i++){
21235     p[i] = buf[j];
21236   }
21237   return n;
21238 }
21239 
21240 /*
21241 ** This routine is a faster version of sqlite3PutVarint() that only
21242 ** works for 32-bit positive integers and which is optimized for
21243 ** the common case of small integers.  A MACRO version, putVarint32,
21244 ** is provided which inlines the single-byte case.  All code should use
21245 ** the MACRO version as this function assumes the single-byte case has
21246 ** already been handled.
21247 */
sqlite3PutVarint32(unsigned char * p,u32 v)21248 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21249 #ifndef putVarint32
21250   if( (v & ~0x7f)==0 ){
21251     p[0] = v;
21252     return 1;
21253   }
21254 #endif
21255   if( (v & ~0x3fff)==0 ){
21256     p[0] = (u8)((v>>7) | 0x80);
21257     p[1] = (u8)(v & 0x7f);
21258     return 2;
21259   }
21260   return sqlite3PutVarint(p, v);
21261 }
21262 
21263 /*
21264 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21265 ** are defined here rather than simply putting the constant expressions
21266 ** inline in order to work around bugs in the RVT compiler.
21267 **
21268 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21269 **
21270 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21271 */
21272 #define SLOT_2_0     0x001fc07f
21273 #define SLOT_4_2_0   0xf01fc07f
21274 
21275 
21276 /*
21277 ** Read a 64-bit variable-length integer from memory starting at p[0].
21278 ** Return the number of bytes read.  The value is stored in *v.
21279 */
sqlite3GetVarint(const unsigned char * p,u64 * v)21280 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21281   u32 a,b,s;
21282 
21283   a = *p;
21284   /* a: p0 (unmasked) */
21285   if (!(a&0x80))
21286   {
21287     *v = a;
21288     return 1;
21289   }
21290 
21291   p++;
21292   b = *p;
21293   /* b: p1 (unmasked) */
21294   if (!(b&0x80))
21295   {
21296     a &= 0x7f;
21297     a = a<<7;
21298     a |= b;
21299     *v = a;
21300     return 2;
21301   }
21302 
21303   /* Verify that constants are precomputed correctly */
21304   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21305   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21306 
21307   p++;
21308   a = a<<14;
21309   a |= *p;
21310   /* a: p0<<14 | p2 (unmasked) */
21311   if (!(a&0x80))
21312   {
21313     a &= SLOT_2_0;
21314     b &= 0x7f;
21315     b = b<<7;
21316     a |= b;
21317     *v = a;
21318     return 3;
21319   }
21320 
21321   /* CSE1 from below */
21322   a &= SLOT_2_0;
21323   p++;
21324   b = b<<14;
21325   b |= *p;
21326   /* b: p1<<14 | p3 (unmasked) */
21327   if (!(b&0x80))
21328   {
21329     b &= SLOT_2_0;
21330     /* moved CSE1 up */
21331     /* a &= (0x7f<<14)|(0x7f); */
21332     a = a<<7;
21333     a |= b;
21334     *v = a;
21335     return 4;
21336   }
21337 
21338   /* a: p0<<14 | p2 (masked) */
21339   /* b: p1<<14 | p3 (unmasked) */
21340   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21341   /* moved CSE1 up */
21342   /* a &= (0x7f<<14)|(0x7f); */
21343   b &= SLOT_2_0;
21344   s = a;
21345   /* s: p0<<14 | p2 (masked) */
21346 
21347   p++;
21348   a = a<<14;
21349   a |= *p;
21350   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21351   if (!(a&0x80))
21352   {
21353     /* we can skip these cause they were (effectively) done above in calc'ing s */
21354     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21355     /* b &= (0x7f<<14)|(0x7f); */
21356     b = b<<7;
21357     a |= b;
21358     s = s>>18;
21359     *v = ((u64)s)<<32 | a;
21360     return 5;
21361   }
21362 
21363   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21364   s = s<<7;
21365   s |= b;
21366   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21367 
21368   p++;
21369   b = b<<14;
21370   b |= *p;
21371   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21372   if (!(b&0x80))
21373   {
21374     /* we can skip this cause it was (effectively) done above in calc'ing s */
21375     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21376     a &= SLOT_2_0;
21377     a = a<<7;
21378     a |= b;
21379     s = s>>18;
21380     *v = ((u64)s)<<32 | a;
21381     return 6;
21382   }
21383 
21384   p++;
21385   a = a<<14;
21386   a |= *p;
21387   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21388   if (!(a&0x80))
21389   {
21390     a &= SLOT_4_2_0;
21391     b &= SLOT_2_0;
21392     b = b<<7;
21393     a |= b;
21394     s = s>>11;
21395     *v = ((u64)s)<<32 | a;
21396     return 7;
21397   }
21398 
21399   /* CSE2 from below */
21400   a &= SLOT_2_0;
21401   p++;
21402   b = b<<14;
21403   b |= *p;
21404   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21405   if (!(b&0x80))
21406   {
21407     b &= SLOT_4_2_0;
21408     /* moved CSE2 up */
21409     /* a &= (0x7f<<14)|(0x7f); */
21410     a = a<<7;
21411     a |= b;
21412     s = s>>4;
21413     *v = ((u64)s)<<32 | a;
21414     return 8;
21415   }
21416 
21417   p++;
21418   a = a<<15;
21419   a |= *p;
21420   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21421 
21422   /* moved CSE2 up */
21423   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21424   b &= SLOT_2_0;
21425   b = b<<8;
21426   a |= b;
21427 
21428   s = s<<4;
21429   b = p[-4];
21430   b &= 0x7f;
21431   b = b>>3;
21432   s |= b;
21433 
21434   *v = ((u64)s)<<32 | a;
21435 
21436   return 9;
21437 }
21438 
21439 /*
21440 ** Read a 32-bit variable-length integer from memory starting at p[0].
21441 ** Return the number of bytes read.  The value is stored in *v.
21442 **
21443 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21444 ** integer, then set *v to 0xffffffff.
21445 **
21446 ** A MACRO version, getVarint32, is provided which inlines the
21447 ** single-byte case.  All code should use the MACRO version as
21448 ** this function assumes the single-byte case has already been handled.
21449 */
sqlite3GetVarint32(const unsigned char * p,u32 * v)21450 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21451   u32 a,b;
21452 
21453   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21454   ** by the getVarin32() macro */
21455   a = *p;
21456   /* a: p0 (unmasked) */
21457 #ifndef getVarint32
21458   if (!(a&0x80))
21459   {
21460     /* Values between 0 and 127 */
21461     *v = a;
21462     return 1;
21463   }
21464 #endif
21465 
21466   /* The 2-byte case */
21467   p++;
21468   b = *p;
21469   /* b: p1 (unmasked) */
21470   if (!(b&0x80))
21471   {
21472     /* Values between 128 and 16383 */
21473     a &= 0x7f;
21474     a = a<<7;
21475     *v = a | b;
21476     return 2;
21477   }
21478 
21479   /* The 3-byte case */
21480   p++;
21481   a = a<<14;
21482   a |= *p;
21483   /* a: p0<<14 | p2 (unmasked) */
21484   if (!(a&0x80))
21485   {
21486     /* Values between 16384 and 2097151 */
21487     a &= (0x7f<<14)|(0x7f);
21488     b &= 0x7f;
21489     b = b<<7;
21490     *v = a | b;
21491     return 3;
21492   }
21493 
21494   /* A 32-bit varint is used to store size information in btrees.
21495   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21496   ** A 3-byte varint is sufficient, for example, to record the size
21497   ** of a 1048569-byte BLOB or string.
21498   **
21499   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21500   ** rare larger cases can be handled by the slower 64-bit varint
21501   ** routine.
21502   */
21503 #if 1
21504   {
21505     u64 v64;
21506     u8 n;
21507 
21508     p -= 2;
21509     n = sqlite3GetVarint(p, &v64);
21510     assert( n>3 && n<=9 );
21511     if( (v64 & SQLITE_MAX_U32)!=v64 ){
21512       *v = 0xffffffff;
21513     }else{
21514       *v = (u32)v64;
21515     }
21516     return n;
21517   }
21518 
21519 #else
21520   /* For following code (kept for historical record only) shows an
21521   ** unrolling for the 3- and 4-byte varint cases.  This code is
21522   ** slightly faster, but it is also larger and much harder to test.
21523   */
21524   p++;
21525   b = b<<14;
21526   b |= *p;
21527   /* b: p1<<14 | p3 (unmasked) */
21528   if (!(b&0x80))
21529   {
21530     /* Values between 2097152 and 268435455 */
21531     b &= (0x7f<<14)|(0x7f);
21532     a &= (0x7f<<14)|(0x7f);
21533     a = a<<7;
21534     *v = a | b;
21535     return 4;
21536   }
21537 
21538   p++;
21539   a = a<<14;
21540   a |= *p;
21541   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21542   if (!(a&0x80))
21543   {
21544     /* Values  between 268435456 and 34359738367 */
21545     a &= SLOT_4_2_0;
21546     b &= SLOT_4_2_0;
21547     b = b<<7;
21548     *v = a | b;
21549     return 5;
21550   }
21551 
21552   /* We can only reach this point when reading a corrupt database
21553   ** file.  In that case we are not in any hurry.  Use the (relatively
21554   ** slow) general-purpose sqlite3GetVarint() routine to extract the
21555   ** value. */
21556   {
21557     u64 v64;
21558     u8 n;
21559 
21560     p -= 4;
21561     n = sqlite3GetVarint(p, &v64);
21562     assert( n>5 && n<=9 );
21563     *v = (u32)v64;
21564     return n;
21565   }
21566 #endif
21567 }
21568 
21569 /*
21570 ** Return the number of bytes that will be needed to store the given
21571 ** 64-bit integer.
21572 */
sqlite3VarintLen(u64 v)21573 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
21574   int i = 0;
21575   do{
21576     i++;
21577     v >>= 7;
21578   }while( v!=0 && ALWAYS(i<9) );
21579   return i;
21580 }
21581 
21582 
21583 /*
21584 ** Read or write a four-byte big-endian integer value.
21585 */
sqlite3Get4byte(const u8 * p)21586 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
21587   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
21588 }
sqlite3Put4byte(unsigned char * p,u32 v)21589 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
21590   p[0] = (u8)(v>>24);
21591   p[1] = (u8)(v>>16);
21592   p[2] = (u8)(v>>8);
21593   p[3] = (u8)v;
21594 }
21595 
21596 
21597 
21598 /*
21599 ** Translate a single byte of Hex into an integer.
21600 ** This routine only works if h really is a valid hexadecimal
21601 ** character:  0..9a..fA..F
21602 */
sqlite3HexToInt(int h)21603 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
21604   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
21605 #ifdef SQLITE_ASCII
21606   h += 9*(1&(h>>6));
21607 #endif
21608 #ifdef SQLITE_EBCDIC
21609   h += 9*(1&~(h>>4));
21610 #endif
21611   return (u8)(h & 0xf);
21612 }
21613 
21614 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
21615 /*
21616 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
21617 ** value.  Return a pointer to its binary value.  Space to hold the
21618 ** binary value has been obtained from malloc and must be freed by
21619 ** the calling routine.
21620 */
sqlite3HexToBlob(sqlite3 * db,const char * z,int n)21621 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
21622   char *zBlob;
21623   int i;
21624 
21625   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
21626   n--;
21627   if( zBlob ){
21628     for(i=0; i<n; i+=2){
21629       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
21630     }
21631     zBlob[i/2] = 0;
21632   }
21633   return zBlob;
21634 }
21635 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
21636 
21637 /*
21638 ** Log an error that is an API call on a connection pointer that should
21639 ** not have been used.  The "type" of connection pointer is given as the
21640 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
21641 */
logBadConnection(const char * zType)21642 static void logBadConnection(const char *zType){
21643   sqlite3_log(SQLITE_MISUSE,
21644      "API call with %s database connection pointer",
21645      zType
21646   );
21647 }
21648 
21649 /*
21650 ** Check to make sure we have a valid db pointer.  This test is not
21651 ** foolproof but it does provide some measure of protection against
21652 ** misuse of the interface such as passing in db pointers that are
21653 ** NULL or which have been previously closed.  If this routine returns
21654 ** 1 it means that the db pointer is valid and 0 if it should not be
21655 ** dereferenced for any reason.  The calling function should invoke
21656 ** SQLITE_MISUSE immediately.
21657 **
21658 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
21659 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
21660 ** open properly and is not fit for general use but which can be
21661 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
21662 */
sqlite3SafetyCheckOk(sqlite3 * db)21663 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
21664   u32 magic;
21665   if( db==0 ){
21666     logBadConnection("NULL");
21667     return 0;
21668   }
21669   magic = db->magic;
21670   if( magic!=SQLITE_MAGIC_OPEN ){
21671     if( sqlite3SafetyCheckSickOrOk(db) ){
21672       testcase( sqlite3GlobalConfig.xLog!=0 );
21673       logBadConnection("unopened");
21674     }
21675     return 0;
21676   }else{
21677     return 1;
21678   }
21679 }
sqlite3SafetyCheckSickOrOk(sqlite3 * db)21680 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
21681   u32 magic;
21682   magic = db->magic;
21683   if( magic!=SQLITE_MAGIC_SICK &&
21684       magic!=SQLITE_MAGIC_OPEN &&
21685       magic!=SQLITE_MAGIC_BUSY ){
21686     testcase( sqlite3GlobalConfig.xLog!=0 );
21687     logBadConnection("invalid");
21688     return 0;
21689   }else{
21690     return 1;
21691   }
21692 }
21693 
21694 /*
21695 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
21696 ** the other 64-bit signed integer at *pA and store the result in *pA.
21697 ** Return 0 on success.  Or if the operation would have resulted in an
21698 ** overflow, leave *pA unchanged and return 1.
21699 */
sqlite3AddInt64(i64 * pA,i64 iB)21700 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
21701   i64 iA = *pA;
21702   testcase( iA==0 ); testcase( iA==1 );
21703   testcase( iB==-1 ); testcase( iB==0 );
21704   if( iB>=0 ){
21705     testcase( iA>0 && LARGEST_INT64 - iA == iB );
21706     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
21707     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
21708     *pA += iB;
21709   }else{
21710     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
21711     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
21712     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
21713     *pA += iB;
21714   }
21715   return 0;
21716 }
sqlite3SubInt64(i64 * pA,i64 iB)21717 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
21718   testcase( iB==SMALLEST_INT64+1 );
21719   if( iB==SMALLEST_INT64 ){
21720     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
21721     if( (*pA)>=0 ) return 1;
21722     *pA -= iB;
21723     return 0;
21724   }else{
21725     return sqlite3AddInt64(pA, -iB);
21726   }
21727 }
21728 #define TWOPOWER32 (((i64)1)<<32)
21729 #define TWOPOWER31 (((i64)1)<<31)
sqlite3MulInt64(i64 * pA,i64 iB)21730 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
21731   i64 iA = *pA;
21732   i64 iA1, iA0, iB1, iB0, r;
21733 
21734   iA1 = iA/TWOPOWER32;
21735   iA0 = iA % TWOPOWER32;
21736   iB1 = iB/TWOPOWER32;
21737   iB0 = iB % TWOPOWER32;
21738   if( iA1*iB1 != 0 ) return 1;
21739   assert( iA1*iB0==0 || iA0*iB1==0 );
21740   r = iA1*iB0 + iA0*iB1;
21741   testcase( r==(-TWOPOWER31)-1 );
21742   testcase( r==(-TWOPOWER31) );
21743   testcase( r==TWOPOWER31 );
21744   testcase( r==TWOPOWER31-1 );
21745   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
21746   r *= TWOPOWER32;
21747   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
21748   *pA = r;
21749   return 0;
21750 }
21751 
21752 /*
21753 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or
21754 ** if the integer has a value of -2147483648, return +2147483647
21755 */
sqlite3AbsInt32(int x)21756 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
21757   if( x>=0 ) return x;
21758   if( x==(int)0x80000000 ) return 0x7fffffff;
21759   return -x;
21760 }
21761 
21762 #ifdef SQLITE_ENABLE_8_3_NAMES
21763 /*
21764 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
21765 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
21766 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
21767 ** three characters, then shorten the suffix on z[] to be the last three
21768 ** characters of the original suffix.
21769 **
21770 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
21771 ** do the suffix shortening regardless of URI parameter.
21772 **
21773 ** Examples:
21774 **
21775 **     test.db-journal    =>   test.nal
21776 **     test.db-wal        =>   test.wal
21777 **     test.db-shm        =>   test.shm
21778 */
sqlite3FileSuffix3(const char * zBaseFilename,char * z)21779 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
21780 #if SQLITE_ENABLE_8_3_NAMES<2
21781   const char *zOk;
21782   zOk = sqlite3_uri_parameter(zBaseFilename, "8_3_names");
21783   if( zOk && sqlite3GetBoolean(zOk) )
21784 #endif
21785   {
21786     int i, sz;
21787     sz = sqlite3Strlen30(z);
21788     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
21789     if( z[i]=='.' && ALWAYS(sz>i+4) ) memcpy(&z[i+1], &z[sz-3], 4);
21790   }
21791 }
21792 #endif
21793 
21794 /************** End of util.c ************************************************/
21795 /************** Begin file hash.c ********************************************/
21796 /*
21797 ** 2001 September 22
21798 **
21799 ** The author disclaims copyright to this source code.  In place of
21800 ** a legal notice, here is a blessing:
21801 **
21802 **    May you do good and not evil.
21803 **    May you find forgiveness for yourself and forgive others.
21804 **    May you share freely, never taking more than you give.
21805 **
21806 *************************************************************************
21807 ** This is the implementation of generic hash-tables
21808 ** used in SQLite.
21809 */
21810 /* #include <assert.h> */
21811 
21812 /* Turn bulk memory into a hash table object by initializing the
21813 ** fields of the Hash structure.
21814 **
21815 ** "pNew" is a pointer to the hash table that is to be initialized.
21816 */
sqlite3HashInit(Hash * pNew)21817 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
21818   assert( pNew!=0 );
21819   pNew->first = 0;
21820   pNew->count = 0;
21821   pNew->htsize = 0;
21822   pNew->ht = 0;
21823 }
21824 
21825 /* Remove all entries from a hash table.  Reclaim all memory.
21826 ** Call this routine to delete a hash table or to reset a hash table
21827 ** to the empty state.
21828 */
sqlite3HashClear(Hash * pH)21829 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
21830   HashElem *elem;         /* For looping over all elements of the table */
21831 
21832   assert( pH!=0 );
21833   elem = pH->first;
21834   pH->first = 0;
21835   sqlite3_free(pH->ht);
21836   pH->ht = 0;
21837   pH->htsize = 0;
21838   while( elem ){
21839     HashElem *next_elem = elem->next;
21840     sqlite3_free(elem);
21841     elem = next_elem;
21842   }
21843   pH->count = 0;
21844 }
21845 
21846 /*
21847 ** The hashing function.
21848 */
strHash(const char * z,int nKey)21849 static unsigned int strHash(const char *z, int nKey){
21850   int h = 0;
21851   assert( nKey>=0 );
21852   while( nKey > 0  ){
21853     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
21854     nKey--;
21855   }
21856   return h;
21857 }
21858 
21859 
21860 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
21861 ** insert pNew into the pEntry hash bucket.
21862 */
insertElement(Hash * pH,struct _ht * pEntry,HashElem * pNew)21863 static void insertElement(
21864   Hash *pH,              /* The complete hash table */
21865   struct _ht *pEntry,    /* The entry into which pNew is inserted */
21866   HashElem *pNew         /* The element to be inserted */
21867 ){
21868   HashElem *pHead;       /* First element already in pEntry */
21869   if( pEntry ){
21870     pHead = pEntry->count ? pEntry->chain : 0;
21871     pEntry->count++;
21872     pEntry->chain = pNew;
21873   }else{
21874     pHead = 0;
21875   }
21876   if( pHead ){
21877     pNew->next = pHead;
21878     pNew->prev = pHead->prev;
21879     if( pHead->prev ){ pHead->prev->next = pNew; }
21880     else             { pH->first = pNew; }
21881     pHead->prev = pNew;
21882   }else{
21883     pNew->next = pH->first;
21884     if( pH->first ){ pH->first->prev = pNew; }
21885     pNew->prev = 0;
21886     pH->first = pNew;
21887   }
21888 }
21889 
21890 
21891 /* Resize the hash table so that it cantains "new_size" buckets.
21892 **
21893 ** The hash table might fail to resize if sqlite3_malloc() fails or
21894 ** if the new size is the same as the prior size.
21895 ** Return TRUE if the resize occurs and false if not.
21896 */
rehash(Hash * pH,unsigned int new_size)21897 static int rehash(Hash *pH, unsigned int new_size){
21898   struct _ht *new_ht;            /* The new hash table */
21899   HashElem *elem, *next_elem;    /* For looping over existing elements */
21900 
21901 #if SQLITE_MALLOC_SOFT_LIMIT>0
21902   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
21903     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
21904   }
21905   if( new_size==pH->htsize ) return 0;
21906 #endif
21907 
21908   /* The inability to allocates space for a larger hash table is
21909   ** a performance hit but it is not a fatal error.  So mark the
21910   ** allocation as a benign.
21911   */
21912   sqlite3BeginBenignMalloc();
21913   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
21914   sqlite3EndBenignMalloc();
21915 
21916   if( new_ht==0 ) return 0;
21917   sqlite3_free(pH->ht);
21918   pH->ht = new_ht;
21919   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
21920   memset(new_ht, 0, new_size*sizeof(struct _ht));
21921   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
21922     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
21923     next_elem = elem->next;
21924     insertElement(pH, &new_ht[h], elem);
21925   }
21926   return 1;
21927 }
21928 
21929 /* This function (for internal use only) locates an element in an
21930 ** hash table that matches the given key.  The hash for this key has
21931 ** already been computed and is passed as the 4th parameter.
21932 */
findElementGivenHash(const Hash * pH,const char * pKey,int nKey,unsigned int h)21933 static HashElem *findElementGivenHash(
21934   const Hash *pH,     /* The pH to be searched */
21935   const char *pKey,   /* The key we are searching for */
21936   int nKey,           /* Bytes in key (not counting zero terminator) */
21937   unsigned int h      /* The hash for this key. */
21938 ){
21939   HashElem *elem;                /* Used to loop thru the element list */
21940   int count;                     /* Number of elements left to test */
21941 
21942   if( pH->ht ){
21943     struct _ht *pEntry = &pH->ht[h];
21944     elem = pEntry->chain;
21945     count = pEntry->count;
21946   }else{
21947     elem = pH->first;
21948     count = pH->count;
21949   }
21950   while( count-- && ALWAYS(elem) ){
21951     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
21952       return elem;
21953     }
21954     elem = elem->next;
21955   }
21956   return 0;
21957 }
21958 
21959 /* Remove a single entry from the hash table given a pointer to that
21960 ** element and a hash on the element's key.
21961 */
removeElementGivenHash(Hash * pH,HashElem * elem,unsigned int h)21962 static void removeElementGivenHash(
21963   Hash *pH,         /* The pH containing "elem" */
21964   HashElem* elem,   /* The element to be removed from the pH */
21965   unsigned int h    /* Hash value for the element */
21966 ){
21967   struct _ht *pEntry;
21968   if( elem->prev ){
21969     elem->prev->next = elem->next;
21970   }else{
21971     pH->first = elem->next;
21972   }
21973   if( elem->next ){
21974     elem->next->prev = elem->prev;
21975   }
21976   if( pH->ht ){
21977     pEntry = &pH->ht[h];
21978     if( pEntry->chain==elem ){
21979       pEntry->chain = elem->next;
21980     }
21981     pEntry->count--;
21982     assert( pEntry->count>=0 );
21983   }
21984   sqlite3_free( elem );
21985   pH->count--;
21986   if( pH->count<=0 ){
21987     assert( pH->first==0 );
21988     assert( pH->count==0 );
21989     sqlite3HashClear(pH);
21990   }
21991 }
21992 
21993 /* Attempt to locate an element of the hash table pH with a key
21994 ** that matches pKey,nKey.  Return the data for this element if it is
21995 ** found, or NULL if there is no match.
21996 */
sqlite3HashFind(const Hash * pH,const char * pKey,int nKey)21997 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
21998   HashElem *elem;    /* The element that matches key */
21999   unsigned int h;    /* A hash on key */
22000 
22001   assert( pH!=0 );
22002   assert( pKey!=0 );
22003   assert( nKey>=0 );
22004   if( pH->ht ){
22005     h = strHash(pKey, nKey) % pH->htsize;
22006   }else{
22007     h = 0;
22008   }
22009   elem = findElementGivenHash(pH, pKey, nKey, h);
22010   return elem ? elem->data : 0;
22011 }
22012 
22013 /* Insert an element into the hash table pH.  The key is pKey,nKey
22014 ** and the data is "data".
22015 **
22016 ** If no element exists with a matching key, then a new
22017 ** element is created and NULL is returned.
22018 **
22019 ** If another element already exists with the same key, then the
22020 ** new data replaces the old data and the old data is returned.
22021 ** The key is not copied in this instance.  If a malloc fails, then
22022 ** the new data is returned and the hash table is unchanged.
22023 **
22024 ** If the "data" parameter to this function is NULL, then the
22025 ** element corresponding to "key" is removed from the hash table.
22026 */
sqlite3HashInsert(Hash * pH,const char * pKey,int nKey,void * data)22027 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22028   unsigned int h;       /* the hash of the key modulo hash table size */
22029   HashElem *elem;       /* Used to loop thru the element list */
22030   HashElem *new_elem;   /* New element added to the pH */
22031 
22032   assert( pH!=0 );
22033   assert( pKey!=0 );
22034   assert( nKey>=0 );
22035   if( pH->htsize ){
22036     h = strHash(pKey, nKey) % pH->htsize;
22037   }else{
22038     h = 0;
22039   }
22040   elem = findElementGivenHash(pH,pKey,nKey,h);
22041   if( elem ){
22042     void *old_data = elem->data;
22043     if( data==0 ){
22044       removeElementGivenHash(pH,elem,h);
22045     }else{
22046       elem->data = data;
22047       elem->pKey = pKey;
22048       assert(nKey==elem->nKey);
22049     }
22050     return old_data;
22051   }
22052   if( data==0 ) return 0;
22053   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22054   if( new_elem==0 ) return data;
22055   new_elem->pKey = pKey;
22056   new_elem->nKey = nKey;
22057   new_elem->data = data;
22058   pH->count++;
22059   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22060     if( rehash(pH, pH->count*2) ){
22061       assert( pH->htsize>0 );
22062       h = strHash(pKey, nKey) % pH->htsize;
22063     }
22064   }
22065   if( pH->ht ){
22066     insertElement(pH, &pH->ht[h], new_elem);
22067   }else{
22068     insertElement(pH, 0, new_elem);
22069   }
22070   return 0;
22071 }
22072 
22073 /************** End of hash.c ************************************************/
22074 /************** Begin file opcodes.c *****************************************/
22075 /* Automatically generated.  Do not edit */
22076 /* See the mkopcodec.awk script for details. */
22077 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
sqlite3OpcodeName(int i)22078 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22079  static const char *const azName[] = { "?",
22080      /*   1 */ "Goto",
22081      /*   2 */ "Gosub",
22082      /*   3 */ "Return",
22083      /*   4 */ "Yield",
22084      /*   5 */ "HaltIfNull",
22085      /*   6 */ "Halt",
22086      /*   7 */ "Integer",
22087      /*   8 */ "Int64",
22088      /*   9 */ "String",
22089      /*  10 */ "Null",
22090      /*  11 */ "Blob",
22091      /*  12 */ "Variable",
22092      /*  13 */ "Move",
22093      /*  14 */ "Copy",
22094      /*  15 */ "SCopy",
22095      /*  16 */ "ResultRow",
22096      /*  17 */ "CollSeq",
22097      /*  18 */ "Function",
22098      /*  19 */ "Not",
22099      /*  20 */ "AddImm",
22100      /*  21 */ "MustBeInt",
22101      /*  22 */ "RealAffinity",
22102      /*  23 */ "Permutation",
22103      /*  24 */ "Compare",
22104      /*  25 */ "Jump",
22105      /*  26 */ "Once",
22106      /*  27 */ "If",
22107      /*  28 */ "IfNot",
22108      /*  29 */ "Column",
22109      /*  30 */ "Affinity",
22110      /*  31 */ "MakeRecord",
22111      /*  32 */ "Count",
22112      /*  33 */ "Savepoint",
22113      /*  34 */ "AutoCommit",
22114      /*  35 */ "Transaction",
22115      /*  36 */ "ReadCookie",
22116      /*  37 */ "SetCookie",
22117      /*  38 */ "VerifyCookie",
22118      /*  39 */ "OpenRead",
22119      /*  40 */ "OpenWrite",
22120      /*  41 */ "OpenAutoindex",
22121      /*  42 */ "OpenEphemeral",
22122      /*  43 */ "SorterOpen",
22123      /*  44 */ "OpenPseudo",
22124      /*  45 */ "Close",
22125      /*  46 */ "SeekLt",
22126      /*  47 */ "SeekLe",
22127      /*  48 */ "SeekGe",
22128      /*  49 */ "SeekGt",
22129      /*  50 */ "Seek",
22130      /*  51 */ "NotFound",
22131      /*  52 */ "Found",
22132      /*  53 */ "IsUnique",
22133      /*  54 */ "NotExists",
22134      /*  55 */ "Sequence",
22135      /*  56 */ "NewRowid",
22136      /*  57 */ "Insert",
22137      /*  58 */ "InsertInt",
22138      /*  59 */ "Delete",
22139      /*  60 */ "ResetCount",
22140      /*  61 */ "SorterCompare",
22141      /*  62 */ "SorterData",
22142      /*  63 */ "RowKey",
22143      /*  64 */ "RowData",
22144      /*  65 */ "Rowid",
22145      /*  66 */ "NullRow",
22146      /*  67 */ "Last",
22147      /*  68 */ "Or",
22148      /*  69 */ "And",
22149      /*  70 */ "SorterSort",
22150      /*  71 */ "Sort",
22151      /*  72 */ "Rewind",
22152      /*  73 */ "IsNull",
22153      /*  74 */ "NotNull",
22154      /*  75 */ "Ne",
22155      /*  76 */ "Eq",
22156      /*  77 */ "Gt",
22157      /*  78 */ "Le",
22158      /*  79 */ "Lt",
22159      /*  80 */ "Ge",
22160      /*  81 */ "SorterNext",
22161      /*  82 */ "BitAnd",
22162      /*  83 */ "BitOr",
22163      /*  84 */ "ShiftLeft",
22164      /*  85 */ "ShiftRight",
22165      /*  86 */ "Add",
22166      /*  87 */ "Subtract",
22167      /*  88 */ "Multiply",
22168      /*  89 */ "Divide",
22169      /*  90 */ "Remainder",
22170      /*  91 */ "Concat",
22171      /*  92 */ "Prev",
22172      /*  93 */ "BitNot",
22173      /*  94 */ "String8",
22174      /*  95 */ "Next",
22175      /*  96 */ "SorterInsert",
22176      /*  97 */ "IdxInsert",
22177      /*  98 */ "IdxDelete",
22178      /*  99 */ "IdxRowid",
22179      /* 100 */ "IdxLT",
22180      /* 101 */ "IdxGE",
22181      /* 102 */ "Destroy",
22182      /* 103 */ "Clear",
22183      /* 104 */ "CreateIndex",
22184      /* 105 */ "CreateTable",
22185      /* 106 */ "ParseSchema",
22186      /* 107 */ "LoadAnalysis",
22187      /* 108 */ "DropTable",
22188      /* 109 */ "DropIndex",
22189      /* 110 */ "DropTrigger",
22190      /* 111 */ "IntegrityCk",
22191      /* 112 */ "RowSetAdd",
22192      /* 113 */ "RowSetRead",
22193      /* 114 */ "RowSetTest",
22194      /* 115 */ "Program",
22195      /* 116 */ "Param",
22196      /* 117 */ "FkCounter",
22197      /* 118 */ "FkIfZero",
22198      /* 119 */ "MemMax",
22199      /* 120 */ "IfPos",
22200      /* 121 */ "IfNeg",
22201      /* 122 */ "IfZero",
22202      /* 123 */ "AggStep",
22203      /* 124 */ "AggFinal",
22204      /* 125 */ "Checkpoint",
22205      /* 126 */ "JournalMode",
22206      /* 127 */ "Vacuum",
22207      /* 128 */ "IncrVacuum",
22208      /* 129 */ "Expire",
22209      /* 130 */ "Real",
22210      /* 131 */ "TableLock",
22211      /* 132 */ "VBegin",
22212      /* 133 */ "VCreate",
22213      /* 134 */ "VDestroy",
22214      /* 135 */ "VOpen",
22215      /* 136 */ "VFilter",
22216      /* 137 */ "VColumn",
22217      /* 138 */ "VNext",
22218      /* 139 */ "VRename",
22219      /* 140 */ "VUpdate",
22220      /* 141 */ "ToText",
22221      /* 142 */ "ToBlob",
22222      /* 143 */ "ToNumeric",
22223      /* 144 */ "ToInt",
22224      /* 145 */ "ToReal",
22225      /* 146 */ "Pagecount",
22226      /* 147 */ "MaxPgcnt",
22227      /* 148 */ "Trace",
22228      /* 149 */ "Noop",
22229      /* 150 */ "Explain",
22230   };
22231   return azName[i];
22232 }
22233 #endif
22234 
22235 /************** End of opcodes.c *********************************************/
22236 /************** Begin file os_os2.c ******************************************/
22237 /*
22238 ** 2006 Feb 14
22239 **
22240 ** The author disclaims copyright to this source code.  In place of
22241 ** a legal notice, here is a blessing:
22242 **
22243 **    May you do good and not evil.
22244 **    May you find forgiveness for yourself and forgive others.
22245 **    May you share freely, never taking more than you give.
22246 **
22247 ******************************************************************************
22248 **
22249 ** This file contains code that is specific to OS/2.
22250 */
22251 
22252 
22253 #if SQLITE_OS_OS2
22254 
22255 /*
22256 ** A Note About Memory Allocation:
22257 **
22258 ** This driver uses malloc()/free() directly rather than going through
22259 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
22260 ** are designed for use on embedded systems where memory is scarce and
22261 ** malloc failures happen frequently.  OS/2 does not typically run on
22262 ** embedded systems, and when it does the developers normally have bigger
22263 ** problems to worry about than running out of memory.  So there is not
22264 ** a compelling need to use the wrappers.
22265 **
22266 ** But there is a good reason to not use the wrappers.  If we use the
22267 ** wrappers then we will get simulated malloc() failures within this
22268 ** driver.  And that causes all kinds of problems for our tests.  We
22269 ** could enhance SQLite to deal with simulated malloc failures within
22270 ** the OS driver, but the code to deal with those failure would not
22271 ** be exercised on Linux (which does not need to malloc() in the driver)
22272 ** and so we would have difficulty writing coverage tests for that
22273 ** code.  Better to leave the code out, we think.
22274 **
22275 ** The point of this discussion is as follows:  When creating a new
22276 ** OS layer for an embedded system, if you use this file as an example,
22277 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
22278 ** desktops but not so well in embedded systems.
22279 */
22280 
22281 /*
22282 ** Macros used to determine whether or not to use threads.
22283 */
22284 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22285 # define SQLITE_OS2_THREADS 1
22286 #endif
22287 
22288 /*
22289 ** Include code that is common to all os_*.c files
22290 */
22291 /************** Include os_common.h in the middle of os_os2.c ****************/
22292 /************** Begin file os_common.h ***************************************/
22293 /*
22294 ** 2004 May 22
22295 **
22296 ** The author disclaims copyright to this source code.  In place of
22297 ** a legal notice, here is a blessing:
22298 **
22299 **    May you do good and not evil.
22300 **    May you find forgiveness for yourself and forgive others.
22301 **    May you share freely, never taking more than you give.
22302 **
22303 ******************************************************************************
22304 **
22305 ** This file contains macros and a little bit of code that is common to
22306 ** all of the platform-specific files (os_*.c) and is #included into those
22307 ** files.
22308 **
22309 ** This file should be #included by the os_*.c files only.  It is not a
22310 ** general purpose header file.
22311 */
22312 #ifndef _OS_COMMON_H_
22313 #define _OS_COMMON_H_
22314 
22315 /*
22316 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22317 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22318 ** switch.  The following code should catch this problem at compile-time.
22319 */
22320 #ifdef MEMORY_DEBUG
22321 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22322 #endif
22323 
22324 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22325 # ifndef SQLITE_DEBUG_OS_TRACE
22326 #   define SQLITE_DEBUG_OS_TRACE 0
22327 # endif
22328   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22329 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22330 #else
22331 # define OSTRACE(X)
22332 #endif
22333 
22334 /*
22335 ** Macros for performance tracing.  Normally turned off.  Only works
22336 ** on i486 hardware.
22337 */
22338 #ifdef SQLITE_PERFORMANCE_TRACE
22339 
22340 /*
22341 ** hwtime.h contains inline assembler code for implementing
22342 ** high-performance timing routines.
22343 */
22344 /************** Include hwtime.h in the middle of os_common.h ****************/
22345 /************** Begin file hwtime.h ******************************************/
22346 /*
22347 ** 2008 May 27
22348 **
22349 ** The author disclaims copyright to this source code.  In place of
22350 ** a legal notice, here is a blessing:
22351 **
22352 **    May you do good and not evil.
22353 **    May you find forgiveness for yourself and forgive others.
22354 **    May you share freely, never taking more than you give.
22355 **
22356 ******************************************************************************
22357 **
22358 ** This file contains inline asm code for retrieving "high-performance"
22359 ** counters for x86 class CPUs.
22360 */
22361 #ifndef _HWTIME_H_
22362 #define _HWTIME_H_
22363 
22364 /*
22365 ** The following routine only works on pentium-class (or newer) processors.
22366 ** It uses the RDTSC opcode to read the cycle count value out of the
22367 ** processor and returns that value.  This can be used for high-res
22368 ** profiling.
22369 */
22370 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22371       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22372 
22373   #if defined(__GNUC__)
22374 
sqlite3Hwtime(void)22375   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22376      unsigned int lo, hi;
22377      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22378      return (sqlite_uint64)hi << 32 | lo;
22379   }
22380 
22381   #elif defined(_MSC_VER)
22382 
sqlite3Hwtime(void)22383   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22384      __asm {
22385         rdtsc
22386         ret       ; return value at EDX:EAX
22387      }
22388   }
22389 
22390   #endif
22391 
22392 #elif (defined(__GNUC__) && defined(__x86_64__))
22393 
22394   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22395       unsigned long val;
22396       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22397       return val;
22398   }
22399 
22400 #elif (defined(__GNUC__) && defined(__ppc__))
22401 
22402   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22403       unsigned long long retval;
22404       unsigned long junk;
22405       __asm__ __volatile__ ("\n\
22406           1:      mftbu   %1\n\
22407                   mftb    %L0\n\
22408                   mftbu   %0\n\
22409                   cmpw    %0,%1\n\
22410                   bne     1b"
22411                   : "=r" (retval), "=r" (junk));
22412       return retval;
22413   }
22414 
22415 #else
22416 
22417   #error Need implementation of sqlite3Hwtime() for your platform.
22418 
22419   /*
22420   ** To compile without implementing sqlite3Hwtime() for your platform,
22421   ** you can remove the above #error and use the following
22422   ** stub function.  You will lose timing support for many
22423   ** of the debugging and testing utilities, but it should at
22424   ** least compile and run.
22425   */
22426 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22427 
22428 #endif
22429 
22430 #endif /* !defined(_HWTIME_H_) */
22431 
22432 /************** End of hwtime.h **********************************************/
22433 /************** Continuing where we left off in os_common.h ******************/
22434 
22435 static sqlite_uint64 g_start;
22436 static sqlite_uint64 g_elapsed;
22437 #define TIMER_START       g_start=sqlite3Hwtime()
22438 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22439 #define TIMER_ELAPSED     g_elapsed
22440 #else
22441 #define TIMER_START
22442 #define TIMER_END
22443 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22444 #endif
22445 
22446 /*
22447 ** If we compile with the SQLITE_TEST macro set, then the following block
22448 ** of code will give us the ability to simulate a disk I/O error.  This
22449 ** is used for testing the I/O recovery logic.
22450 */
22451 #ifdef SQLITE_TEST
22452 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22453 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22454 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22455 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22456 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22457 SQLITE_API int sqlite3_diskfull_pending = 0;
22458 SQLITE_API int sqlite3_diskfull = 0;
22459 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22460 #define SimulateIOError(CODE)  \
22461   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22462        || sqlite3_io_error_pending-- == 1 )  \
22463               { local_ioerr(); CODE; }
22464 static void local_ioerr(){
22465   IOTRACE(("IOERR\n"));
22466   sqlite3_io_error_hit++;
22467   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22468 }
22469 #define SimulateDiskfullError(CODE) \
22470    if( sqlite3_diskfull_pending ){ \
22471      if( sqlite3_diskfull_pending == 1 ){ \
22472        local_ioerr(); \
22473        sqlite3_diskfull = 1; \
22474        sqlite3_io_error_hit = 1; \
22475        CODE; \
22476      }else{ \
22477        sqlite3_diskfull_pending--; \
22478      } \
22479    }
22480 #else
22481 #define SimulateIOErrorBenign(X)
22482 #define SimulateIOError(A)
22483 #define SimulateDiskfullError(A)
22484 #endif
22485 
22486 /*
22487 ** When testing, keep a count of the number of open files.
22488 */
22489 #ifdef SQLITE_TEST
22490 SQLITE_API int sqlite3_open_file_count = 0;
22491 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22492 #else
22493 #define OpenCounter(X)
22494 #endif
22495 
22496 #endif /* !defined(_OS_COMMON_H_) */
22497 
22498 /************** End of os_common.h *******************************************/
22499 /************** Continuing where we left off in os_os2.c *********************/
22500 
22501 /* Forward references */
22502 typedef struct os2File os2File;         /* The file structure */
22503 typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22504 typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22505 
22506 /*
22507 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
22508 ** protability layer.
22509 */
22510 struct os2File {
22511   const sqlite3_io_methods *pMethod;  /* Always the first entry */
22512   HFILE h;                  /* Handle for accessing the file */
22513   int flags;                /* Flags provided to os2Open() */
22514   int locktype;             /* Type of lock currently held on this file */
22515   int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22516   char *zFullPathCp;        /* Full path name of this file */
22517   os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22518 };
22519 
22520 #define LOCK_TIMEOUT 10L /* the default locking timeout */
22521 
22522 /*
22523 ** Missing from some versions of the OS/2 toolkit -
22524 ** used to allocate from high memory if possible
22525 */
22526 #ifndef OBJ_ANY
22527 # define OBJ_ANY 0x00000400
22528 #endif
22529 
22530 /*****************************************************************************
22531 ** The next group of routines implement the I/O methods specified
22532 ** by the sqlite3_io_methods object.
22533 ******************************************************************************/
22534 
22535 /*
22536 ** Close a file.
22537 */
22538 static int os2Close( sqlite3_file *id ){
22539   APIRET rc;
22540   os2File *pFile = (os2File*)id;
22541 
22542   assert( id!=0 );
22543   OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22544 
22545   rc = DosClose( pFile->h );
22546 
22547   if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22548     DosForceDelete( (PSZ)pFile->zFullPathCp );
22549 
22550   free( pFile->zFullPathCp );
22551   pFile->zFullPathCp = NULL;
22552   pFile->locktype = NO_LOCK;
22553   pFile->h = (HFILE)-1;
22554   pFile->flags = 0;
22555 
22556   OpenCounter( -1 );
22557   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22558 }
22559 
22560 /*
22561 ** Read data from a file into a buffer.  Return SQLITE_OK if all
22562 ** bytes were read successfully and SQLITE_IOERR if anything goes
22563 ** wrong.
22564 */
22565 static int os2Read(
22566   sqlite3_file *id,               /* File to read from */
22567   void *pBuf,                     /* Write content into this buffer */
22568   int amt,                        /* Number of bytes to read */
22569   sqlite3_int64 offset            /* Begin reading at this offset */
22570 ){
22571   ULONG fileLocation = 0L;
22572   ULONG got;
22573   os2File *pFile = (os2File*)id;
22574   assert( id!=0 );
22575   SimulateIOError( return SQLITE_IOERR_READ );
22576   OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
22577   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22578     return SQLITE_IOERR;
22579   }
22580   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
22581     return SQLITE_IOERR_READ;
22582   }
22583   if( got == (ULONG)amt )
22584     return SQLITE_OK;
22585   else {
22586     /* Unread portions of the input buffer must be zero-filled */
22587     memset(&((char*)pBuf)[got], 0, amt-got);
22588     return SQLITE_IOERR_SHORT_READ;
22589   }
22590 }
22591 
22592 /*
22593 ** Write data from a buffer into a file.  Return SQLITE_OK on success
22594 ** or some other error code on failure.
22595 */
22596 static int os2Write(
22597   sqlite3_file *id,               /* File to write into */
22598   const void *pBuf,               /* The bytes to be written */
22599   int amt,                        /* Number of bytes to write */
22600   sqlite3_int64 offset            /* Offset into the file to begin writing at */
22601 ){
22602   ULONG fileLocation = 0L;
22603   APIRET rc = NO_ERROR;
22604   ULONG wrote;
22605   os2File *pFile = (os2File*)id;
22606   assert( id!=0 );
22607   SimulateIOError( return SQLITE_IOERR_WRITE );
22608   SimulateDiskfullError( return SQLITE_FULL );
22609   OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
22610   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
22611     return SQLITE_IOERR;
22612   }
22613   assert( amt>0 );
22614   while( amt > 0 &&
22615          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
22616          wrote > 0
22617   ){
22618     amt -= wrote;
22619     pBuf = &((char*)pBuf)[wrote];
22620   }
22621 
22622   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
22623 }
22624 
22625 /*
22626 ** Truncate an open file to a specified size
22627 */
22628 static int os2Truncate( sqlite3_file *id, i64 nByte ){
22629   APIRET rc;
22630   os2File *pFile = (os2File*)id;
22631   assert( id!=0 );
22632   OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
22633   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
22634 
22635   /* If the user has configured a chunk-size for this file, truncate the
22636   ** file so that it consists of an integer number of chunks (i.e. the
22637   ** actual file size after the operation may be larger than the requested
22638   ** size).
22639   */
22640   if( pFile->szChunk ){
22641     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
22642   }
22643 
22644   rc = DosSetFileSize( pFile->h, nByte );
22645   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
22646 }
22647 
22648 #ifdef SQLITE_TEST
22649 /*
22650 ** Count the number of fullsyncs and normal syncs.  This is used to test
22651 ** that syncs and fullsyncs are occuring at the right times.
22652 */
22653 SQLITE_API int sqlite3_sync_count = 0;
22654 SQLITE_API int sqlite3_fullsync_count = 0;
22655 #endif
22656 
22657 /*
22658 ** Make sure all writes to a particular file are committed to disk.
22659 */
22660 static int os2Sync( sqlite3_file *id, int flags ){
22661   os2File *pFile = (os2File*)id;
22662   OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
22663 #ifdef SQLITE_TEST
22664   if( flags & SQLITE_SYNC_FULL){
22665     sqlite3_fullsync_count++;
22666   }
22667   sqlite3_sync_count++;
22668 #endif
22669   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
22670   ** no-op
22671   */
22672 #ifdef SQLITE_NO_SYNC
22673   UNUSED_PARAMETER(pFile);
22674   return SQLITE_OK;
22675 #else
22676   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22677 #endif
22678 }
22679 
22680 /*
22681 ** Determine the current size of a file in bytes
22682 */
22683 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
22684   APIRET rc = NO_ERROR;
22685   FILESTATUS3 fsts3FileInfo;
22686   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
22687   assert( id!=0 );
22688   SimulateIOError( return SQLITE_IOERR_FSTAT );
22689   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
22690   if( rc == NO_ERROR ){
22691     *pSize = fsts3FileInfo.cbFile;
22692     return SQLITE_OK;
22693   }else{
22694     return SQLITE_IOERR_FSTAT;
22695   }
22696 }
22697 
22698 /*
22699 ** Acquire a reader lock.
22700 */
22701 static int getReadLock( os2File *pFile ){
22702   FILELOCK  LockArea,
22703             UnlockArea;
22704   APIRET res;
22705   memset(&LockArea, 0, sizeof(LockArea));
22706   memset(&UnlockArea, 0, sizeof(UnlockArea));
22707   LockArea.lOffset = SHARED_FIRST;
22708   LockArea.lRange = SHARED_SIZE;
22709   UnlockArea.lOffset = 0L;
22710   UnlockArea.lRange = 0L;
22711   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22712   OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
22713   return res;
22714 }
22715 
22716 /*
22717 ** Undo a readlock
22718 */
22719 static int unlockReadLock( os2File *id ){
22720   FILELOCK  LockArea,
22721             UnlockArea;
22722   APIRET res;
22723   memset(&LockArea, 0, sizeof(LockArea));
22724   memset(&UnlockArea, 0, sizeof(UnlockArea));
22725   LockArea.lOffset = 0L;
22726   LockArea.lRange = 0L;
22727   UnlockArea.lOffset = SHARED_FIRST;
22728   UnlockArea.lRange = SHARED_SIZE;
22729   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
22730   OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
22731   return res;
22732 }
22733 
22734 /*
22735 ** Lock the file with the lock specified by parameter locktype - one
22736 ** of the following:
22737 **
22738 **     (1) SHARED_LOCK
22739 **     (2) RESERVED_LOCK
22740 **     (3) PENDING_LOCK
22741 **     (4) EXCLUSIVE_LOCK
22742 **
22743 ** Sometimes when requesting one lock state, additional lock states
22744 ** are inserted in between.  The locking might fail on one of the later
22745 ** transitions leaving the lock state different from what it started but
22746 ** still short of its goal.  The following chart shows the allowed
22747 ** transitions and the inserted intermediate states:
22748 **
22749 **    UNLOCKED -> SHARED
22750 **    SHARED -> RESERVED
22751 **    SHARED -> (PENDING) -> EXCLUSIVE
22752 **    RESERVED -> (PENDING) -> EXCLUSIVE
22753 **    PENDING -> EXCLUSIVE
22754 **
22755 ** This routine will only increase a lock.  The os2Unlock() routine
22756 ** erases all locks at once and returns us immediately to locking level 0.
22757 ** It is not possible to lower the locking level one step at a time.  You
22758 ** must go straight to locking level 0.
22759 */
22760 static int os2Lock( sqlite3_file *id, int locktype ){
22761   int rc = SQLITE_OK;       /* Return code from subroutines */
22762   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
22763   int newLocktype;       /* Set pFile->locktype to this value before exiting */
22764   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
22765   FILELOCK  LockArea,
22766             UnlockArea;
22767   os2File *pFile = (os2File*)id;
22768   memset(&LockArea, 0, sizeof(LockArea));
22769   memset(&UnlockArea, 0, sizeof(UnlockArea));
22770   assert( pFile!=0 );
22771   OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
22772 
22773   /* If there is already a lock of this type or more restrictive on the
22774   ** os2File, do nothing. Don't use the end_lock: exit path, as
22775   ** sqlite3_mutex_enter() hasn't been called yet.
22776   */
22777   if( pFile->locktype>=locktype ){
22778     OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
22779     return SQLITE_OK;
22780   }
22781 
22782   /* Make sure the locking sequence is correct
22783   */
22784   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22785   assert( locktype!=PENDING_LOCK );
22786   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22787 
22788   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
22789   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
22790   ** the PENDING_LOCK byte is temporary.
22791   */
22792   newLocktype = pFile->locktype;
22793   if( pFile->locktype==NO_LOCK
22794       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
22795   ){
22796     LockArea.lOffset = PENDING_BYTE;
22797     LockArea.lRange = 1L;
22798     UnlockArea.lOffset = 0L;
22799     UnlockArea.lRange = 0L;
22800 
22801     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
22802     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
22803     if( res == NO_ERROR ){
22804       gotPendingLock = 1;
22805       OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
22806     }
22807   }
22808 
22809   /* Acquire a shared lock
22810   */
22811   if( locktype==SHARED_LOCK && res == NO_ERROR ){
22812     assert( pFile->locktype==NO_LOCK );
22813     res = getReadLock(pFile);
22814     if( res == NO_ERROR ){
22815       newLocktype = SHARED_LOCK;
22816     }
22817     OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
22818   }
22819 
22820   /* Acquire a RESERVED lock
22821   */
22822   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
22823     assert( pFile->locktype==SHARED_LOCK );
22824     LockArea.lOffset = RESERVED_BYTE;
22825     LockArea.lRange = 1L;
22826     UnlockArea.lOffset = 0L;
22827     UnlockArea.lRange = 0L;
22828     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22829     if( res == NO_ERROR ){
22830       newLocktype = RESERVED_LOCK;
22831     }
22832     OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
22833   }
22834 
22835   /* Acquire a PENDING lock
22836   */
22837   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22838     newLocktype = PENDING_LOCK;
22839     gotPendingLock = 0;
22840     OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
22841                pFile->h ));
22842   }
22843 
22844   /* Acquire an EXCLUSIVE lock
22845   */
22846   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
22847     assert( pFile->locktype>=SHARED_LOCK );
22848     res = unlockReadLock(pFile);
22849     OSTRACE(( "unreadlock = %d\n", res ));
22850     LockArea.lOffset = SHARED_FIRST;
22851     LockArea.lRange = SHARED_SIZE;
22852     UnlockArea.lOffset = 0L;
22853     UnlockArea.lRange = 0L;
22854     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22855     if( res == NO_ERROR ){
22856       newLocktype = EXCLUSIVE_LOCK;
22857     }else{
22858       OSTRACE(( "OS/2 error-code = %d\n", res ));
22859       getReadLock(pFile);
22860     }
22861     OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
22862   }
22863 
22864   /* If we are holding a PENDING lock that ought to be released, then
22865   ** release it now.
22866   */
22867   if( gotPendingLock && locktype==SHARED_LOCK ){
22868     int r;
22869     LockArea.lOffset = 0L;
22870     LockArea.lRange = 0L;
22871     UnlockArea.lOffset = PENDING_BYTE;
22872     UnlockArea.lRange = 1L;
22873     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22874     OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
22875   }
22876 
22877   /* Update the state of the lock has held in the file descriptor then
22878   ** return the appropriate result code.
22879   */
22880   if( res == NO_ERROR ){
22881     rc = SQLITE_OK;
22882   }else{
22883     OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
22884               locktype, newLocktype ));
22885     rc = SQLITE_BUSY;
22886   }
22887   pFile->locktype = newLocktype;
22888   OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
22889   return rc;
22890 }
22891 
22892 /*
22893 ** This routine checks if there is a RESERVED lock held on the specified
22894 ** file by this or any other process. If such a lock is held, return
22895 ** non-zero, otherwise zero.
22896 */
22897 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
22898   int r = 0;
22899   os2File *pFile = (os2File*)id;
22900   assert( pFile!=0 );
22901   if( pFile->locktype>=RESERVED_LOCK ){
22902     r = 1;
22903     OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
22904   }else{
22905     FILELOCK  LockArea,
22906               UnlockArea;
22907     APIRET rc = NO_ERROR;
22908     memset(&LockArea, 0, sizeof(LockArea));
22909     memset(&UnlockArea, 0, sizeof(UnlockArea));
22910     LockArea.lOffset = RESERVED_BYTE;
22911     LockArea.lRange = 1L;
22912     UnlockArea.lOffset = 0L;
22913     UnlockArea.lRange = 0L;
22914     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22915     OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
22916     if( rc == NO_ERROR ){
22917       APIRET rcu = NO_ERROR; /* return code for unlocking */
22918       LockArea.lOffset = 0L;
22919       LockArea.lRange = 0L;
22920       UnlockArea.lOffset = RESERVED_BYTE;
22921       UnlockArea.lRange = 1L;
22922       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22923       OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
22924     }
22925     r = !(rc == NO_ERROR);
22926     OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
22927   }
22928   *pOut = r;
22929   return SQLITE_OK;
22930 }
22931 
22932 /*
22933 ** Lower the locking level on file descriptor id to locktype.  locktype
22934 ** must be either NO_LOCK or SHARED_LOCK.
22935 **
22936 ** If the locking level of the file descriptor is already at or below
22937 ** the requested locking level, this routine is a no-op.
22938 **
22939 ** It is not possible for this routine to fail if the second argument
22940 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
22941 ** might return SQLITE_IOERR;
22942 */
22943 static int os2Unlock( sqlite3_file *id, int locktype ){
22944   int type;
22945   os2File *pFile = (os2File*)id;
22946   APIRET rc = SQLITE_OK;
22947   APIRET res = NO_ERROR;
22948   FILELOCK  LockArea,
22949             UnlockArea;
22950   memset(&LockArea, 0, sizeof(LockArea));
22951   memset(&UnlockArea, 0, sizeof(UnlockArea));
22952   assert( pFile!=0 );
22953   assert( locktype<=SHARED_LOCK );
22954   OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
22955   type = pFile->locktype;
22956   if( type>=EXCLUSIVE_LOCK ){
22957     LockArea.lOffset = 0L;
22958     LockArea.lRange = 0L;
22959     UnlockArea.lOffset = SHARED_FIRST;
22960     UnlockArea.lRange = SHARED_SIZE;
22961     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22962     OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
22963     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
22964       /* This should never happen.  We should always be able to
22965       ** reacquire the read lock */
22966       OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
22967       rc = SQLITE_IOERR_UNLOCK;
22968     }
22969   }
22970   if( type>=RESERVED_LOCK ){
22971     LockArea.lOffset = 0L;
22972     LockArea.lRange = 0L;
22973     UnlockArea.lOffset = RESERVED_BYTE;
22974     UnlockArea.lRange = 1L;
22975     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22976     OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
22977   }
22978   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
22979     res = unlockReadLock(pFile);
22980     OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
22981               pFile->h, type, locktype, res ));
22982   }
22983   if( type>=PENDING_LOCK ){
22984     LockArea.lOffset = 0L;
22985     LockArea.lRange = 0L;
22986     UnlockArea.lOffset = PENDING_BYTE;
22987     UnlockArea.lRange = 1L;
22988     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
22989     OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
22990   }
22991   pFile->locktype = locktype;
22992   OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
22993   return rc;
22994 }
22995 
22996 /*
22997 ** Control and query of the open file handle.
22998 */
22999 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
23000   switch( op ){
23001     case SQLITE_FCNTL_LOCKSTATE: {
23002       *(int*)pArg = ((os2File*)id)->locktype;
23003       OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
23004                 ((os2File*)id)->h, ((os2File*)id)->locktype ));
23005       return SQLITE_OK;
23006     }
23007     case SQLITE_FCNTL_CHUNK_SIZE: {
23008       ((os2File*)id)->szChunk = *(int*)pArg;
23009       return SQLITE_OK;
23010     }
23011     case SQLITE_FCNTL_SIZE_HINT: {
23012       sqlite3_int64 sz = *(sqlite3_int64*)pArg;
23013       SimulateIOErrorBenign(1);
23014       os2Truncate(id, sz);
23015       SimulateIOErrorBenign(0);
23016       return SQLITE_OK;
23017     }
23018     case SQLITE_FCNTL_SYNC_OMITTED: {
23019       return SQLITE_OK;
23020     }
23021   }
23022   return SQLITE_NOTFOUND;
23023 }
23024 
23025 /*
23026 ** Return the sector size in bytes of the underlying block device for
23027 ** the specified file. This is almost always 512 bytes, but may be
23028 ** larger for some devices.
23029 **
23030 ** SQLite code assumes this function cannot fail. It also assumes that
23031 ** if two files are created in the same file-system directory (i.e.
23032 ** a database and its journal file) that the sector size will be the
23033 ** same for both.
23034 */
23035 static int os2SectorSize(sqlite3_file *id){
23036   UNUSED_PARAMETER(id);
23037   return SQLITE_DEFAULT_SECTOR_SIZE;
23038 }
23039 
23040 /*
23041 ** Return a vector of device characteristics.
23042 */
23043 static int os2DeviceCharacteristics(sqlite3_file *id){
23044   UNUSED_PARAMETER(id);
23045   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
23046 }
23047 
23048 
23049 /*
23050 ** Character set conversion objects used by conversion routines.
23051 */
23052 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
23053 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
23054 
23055 /*
23056 ** Helper function to initialize the conversion objects from and to UTF-8.
23057 */
23058 static void initUconvObjects( void ){
23059   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
23060     ucUtf8 = NULL;
23061   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
23062     uclCp = NULL;
23063 }
23064 
23065 /*
23066 ** Helper function to free the conversion objects from and to UTF-8.
23067 */
23068 static void freeUconvObjects( void ){
23069   if ( ucUtf8 )
23070     UniFreeUconvObject( ucUtf8 );
23071   if ( uclCp )
23072     UniFreeUconvObject( uclCp );
23073   ucUtf8 = NULL;
23074   uclCp = NULL;
23075 }
23076 
23077 /*
23078 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
23079 ** The two-step process: first convert the incoming UTF-8 string
23080 ** into UCS-2 and then from UCS-2 to the current codepage.
23081 ** The returned char pointer has to be freed.
23082 */
23083 static char *convertUtf8PathToCp( const char *in ){
23084   UniChar tempPath[CCHMAXPATH];
23085   char *out = (char *)calloc( CCHMAXPATH, 1 );
23086 
23087   if( !out )
23088     return NULL;
23089 
23090   if( !ucUtf8 || !uclCp )
23091     initUconvObjects();
23092 
23093   /* determine string for the conversion of UTF-8 which is CP1208 */
23094   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23095     return out; /* if conversion fails, return the empty string */
23096 
23097   /* conversion for current codepage which can be used for paths */
23098   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
23099 
23100   return out;
23101 }
23102 
23103 /*
23104 ** Helper function to convert filenames from local codepage to UTF-8.
23105 ** The two-step process: first convert the incoming codepage-specific
23106 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23107 ** The returned char pointer has to be freed.
23108 **
23109 ** This function is non-static to be able to use this in shell.c and
23110 ** similar applications that take command line arguments.
23111 */
23112 char *convertCpPathToUtf8( const char *in ){
23113   UniChar tempPath[CCHMAXPATH];
23114   char *out = (char *)calloc( CCHMAXPATH, 1 );
23115 
23116   if( !out )
23117     return NULL;
23118 
23119   if( !ucUtf8 || !uclCp )
23120     initUconvObjects();
23121 
23122   /* conversion for current codepage which can be used for paths */
23123   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23124     return out; /* if conversion fails, return the empty string */
23125 
23126   /* determine string for the conversion of UTF-8 which is CP1208 */
23127   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23128 
23129   return out;
23130 }
23131 
23132 
23133 #ifndef SQLITE_OMIT_WAL
23134 
23135 /*
23136 ** Use main database file for interprocess locking. If un-defined
23137 ** a separate file is created for this purpose. The file will be
23138 ** used only to set file locks. There will be no data written to it.
23139 */
23140 #define SQLITE_OS2_NO_WAL_LOCK_FILE
23141 
23142 #if 0
23143 static void _ERR_TRACE( const char *fmt, ... ) {
23144   va_list  ap;
23145   va_start(ap, fmt);
23146   vfprintf(stderr, fmt, ap);
23147   fflush(stderr);
23148 }
23149 #define ERR_TRACE(rc, msg)        \
23150         if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23151 #else
23152 #define ERR_TRACE(rc, msg)
23153 #endif
23154 
23155 /*
23156 ** Helper functions to obtain and relinquish the global mutex. The
23157 ** global mutex is used to protect os2ShmNodeList.
23158 **
23159 ** Function os2ShmMutexHeld() is used to assert() that the global mutex
23160 ** is held when required. This function is only used as part of assert()
23161 ** statements. e.g.
23162 **
23163 **   os2ShmEnterMutex()
23164 **     assert( os2ShmMutexHeld() );
23165 **   os2ShmLeaveMutex()
23166 */
23167 static void os2ShmEnterMutex(void){
23168   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23169 }
23170 static void os2ShmLeaveMutex(void){
23171   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23172 }
23173 #ifdef SQLITE_DEBUG
23174 static int os2ShmMutexHeld(void) {
23175   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23176 }
23177 int GetCurrentProcessId(void) {
23178   PPIB pib;
23179   DosGetInfoBlocks(NULL, &pib);
23180   return (int)pib->pib_ulpid;
23181 }
23182 #endif
23183 
23184 /*
23185 ** Object used to represent a the shared memory area for a single log file.
23186 ** When multiple threads all reference the same log-summary, each thread has
23187 ** its own os2File object, but they all point to a single instance of this
23188 ** object.  In other words, each log-summary is opened only once per process.
23189 **
23190 ** os2ShmMutexHeld() must be true when creating or destroying
23191 ** this object or while reading or writing the following fields:
23192 **
23193 **      nRef
23194 **      pNext
23195 **
23196 ** The following fields are read-only after the object is created:
23197 **
23198 **      szRegion
23199 **      hLockFile
23200 **      shmBaseName
23201 **
23202 ** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23203 ** os2ShmMutexHeld() is true when reading or writing any other field
23204 ** in this structure.
23205 **
23206 */
23207 struct os2ShmNode {
23208   sqlite3_mutex *mutex;      /* Mutex to access this object */
23209   os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
23210 
23211   int szRegion;              /* Size of shared-memory regions */
23212 
23213   int nRegion;               /* Size of array apRegion */
23214   void **apRegion;           /* Array of pointers to shared-memory regions */
23215 
23216   int nRef;                  /* Number of os2ShmLink objects pointing to this */
23217   os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
23218 
23219   HFILE hLockFile;           /* File used for inter-process memory locking */
23220   char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
23221 };
23222 
23223 
23224 /*
23225 ** Structure used internally by this VFS to record the state of an
23226 ** open shared memory connection.
23227 **
23228 ** The following fields are initialized when this object is created and
23229 ** are read-only thereafter:
23230 **
23231 **    os2Shm.pShmNode
23232 **    os2Shm.id
23233 **
23234 ** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
23235 ** while accessing any read/write fields.
23236 */
23237 struct os2ShmLink {
23238   os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
23239   os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
23240   u32 sharedMask;            /* Mask of shared locks held */
23241   u32 exclMask;              /* Mask of exclusive locks held */
23242 #ifdef SQLITE_DEBUG
23243   u8 id;                     /* Id of this connection with its os2ShmNode */
23244 #endif
23245 };
23246 
23247 
23248 /*
23249 ** A global list of all os2ShmNode objects.
23250 **
23251 ** The os2ShmMutexHeld() must be true while reading or writing this list.
23252 */
23253 static os2ShmNode *os2ShmNodeList = NULL;
23254 
23255 /*
23256 ** Constants used for locking
23257 */
23258 #ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
23259 #define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
23260 #else
23261 #define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
23262 #endif
23263 
23264 #define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
23265 
23266 /*
23267 ** Apply advisory locks for all n bytes beginning at ofst.
23268 */
23269 #define _SHM_UNLCK  1   /* no lock */
23270 #define _SHM_RDLCK  2   /* shared lock, no wait */
23271 #define _SHM_WRLCK  3   /* exlusive lock, no wait */
23272 #define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23273 static int os2ShmSystemLock(
23274   os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
23275   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23276   int ofst,             /* Offset to first byte to be locked/unlocked */
23277   int nByte             /* Number of bytes to lock or unlock */
23278 ){
23279   APIRET rc;
23280   FILELOCK area;
23281   ULONG mode, timeout;
23282 
23283   /* Access to the os2ShmNode object is serialized by the caller */
23284   assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23285 
23286   mode = 1;     /* shared lock */
23287   timeout = 0;  /* no wait */
23288   area.lOffset = ofst;
23289   area.lRange = nByte;
23290 
23291   switch( lockType ) {
23292     case _SHM_WRLCK_WAIT:
23293       timeout = (ULONG)-1;      /* wait forever */
23294     case _SHM_WRLCK:
23295       mode = 0;                 /* exclusive lock */
23296     case _SHM_RDLCK:
23297       rc = DosSetFileLocks(pNode->hLockFile,
23298                            NULL, &area, timeout, mode);
23299       break;
23300     /* case _SHM_UNLCK: */
23301     default:
23302       rc = DosSetFileLocks(pNode->hLockFile,
23303                            &area, NULL, 0, 0);
23304       break;
23305   }
23306 
23307   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
23308            pNode->hLockFile,
23309            rc==SQLITE_OK ? "ok" : "failed",
23310            lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23311            rc));
23312 
23313   ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23314 
23315   return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
23316 }
23317 
23318 /*
23319 ** Find an os2ShmNode in global list or allocate a new one, if not found.
23320 **
23321 ** This is not a VFS shared-memory method; it is a utility function called
23322 ** by VFS shared-memory methods.
23323 */
23324 static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23325   os2ShmLink *pLink;
23326   os2ShmNode *pNode;
23327   int cbShmName, rc = SQLITE_OK;
23328   char shmName[CCHMAXPATH + 30];
23329 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23330   ULONG action;
23331 #endif
23332 
23333   /* We need some additional space at the end to append the region number */
23334   cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23335   if( cbShmName >= CCHMAXPATH-8 )
23336     return SQLITE_IOERR_SHMOPEN;
23337 
23338   /* Replace colon in file name to form a valid shared memory name */
23339   shmName[10+1] = '!';
23340 
23341   /* Allocate link object (we free it later in case of failure) */
23342   pLink = sqlite3_malloc( sizeof(*pLink) );
23343   if( !pLink )
23344     return SQLITE_NOMEM;
23345 
23346   /* Access node list */
23347   os2ShmEnterMutex();
23348 
23349   /* Find node by it's shared memory base name */
23350   for( pNode = os2ShmNodeList;
23351        pNode && stricmp(shmName, pNode->shmBaseName) != 0;
23352        pNode = pNode->pNext )   ;
23353 
23354   /* Not found: allocate a new node */
23355   if( !pNode ) {
23356     pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23357     if( pNode ) {
23358       memset(pNode, 0, sizeof(*pNode) );
23359       pNode->szRegion = szRegion;
23360       pNode->hLockFile = (HFILE)-1;
23361       strcpy(pNode->shmBaseName, shmName);
23362 
23363 #ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23364       if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23365 #else
23366       sprintf(shmName, "%s-lck", fd->zFullPathCp);
23367       if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
23368                   OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23369                   OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
23370                   OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23371                   NULL) != 0 ) {
23372 #endif
23373         sqlite3_free(pNode);
23374         rc = SQLITE_IOERR;
23375       } else {
23376         pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23377         if( !pNode->mutex ) {
23378           sqlite3_free(pNode);
23379           rc = SQLITE_NOMEM;
23380         }
23381       }
23382     } else {
23383       rc = SQLITE_NOMEM;
23384     }
23385 
23386     if( rc == SQLITE_OK ) {
23387       pNode->pNext = os2ShmNodeList;
23388       os2ShmNodeList = pNode;
23389     } else {
23390       pNode = NULL;
23391     }
23392   } else if( pNode->szRegion != szRegion ) {
23393     rc = SQLITE_IOERR_SHMSIZE;
23394     pNode = NULL;
23395   }
23396 
23397   if( pNode ) {
23398     sqlite3_mutex_enter(pNode->mutex);
23399 
23400     memset(pLink, 0, sizeof(*pLink));
23401 
23402     pLink->pShmNode = pNode;
23403     pLink->pNext = pNode->pFirst;
23404     pNode->pFirst = pLink;
23405     pNode->nRef++;
23406 
23407     fd->pShmLink = pLink;
23408 
23409     sqlite3_mutex_leave(pNode->mutex);
23410 
23411   } else {
23412     /* Error occured. Free our link object. */
23413     sqlite3_free(pLink);
23414   }
23415 
23416   os2ShmLeaveMutex();
23417 
23418   ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))
23419 
23420   return rc;
23421 }
23422 
23423 /*
23424 ** Purge the os2ShmNodeList list of all entries with nRef==0.
23425 **
23426 ** This is not a VFS shared-memory method; it is a utility function called
23427 ** by VFS shared-memory methods.
23428 */
23429 static void os2PurgeShmNodes( int deleteFlag ) {
23430   os2ShmNode *pNode;
23431   os2ShmNode **ppNode;
23432 
23433   os2ShmEnterMutex();
23434 
23435   ppNode = &os2ShmNodeList;
23436 
23437   while( *ppNode ) {
23438     pNode = *ppNode;
23439 
23440     if( pNode->nRef == 0 ) {
23441       *ppNode = pNode->pNext;
23442 
23443       if( pNode->apRegion ) {
23444         /* Prevent other processes from resizing the shared memory */
23445         os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23446 
23447         while( pNode->nRegion-- ) {
23448 #ifdef SQLITE_DEBUG
23449           int rc =
23450 #endif
23451           DosFreeMem(pNode->apRegion[pNode->nRegion]);
23452 
23453           OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23454                   (int)GetCurrentProcessId(), pNode->nRegion,
23455                   rc == 0 ? "ok" : "failed"));
23456         }
23457 
23458         /* Allow other processes to resize the shared memory */
23459         os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23460 
23461         sqlite3_free(pNode->apRegion);
23462       }
23463 
23464       DosClose(pNode->hLockFile);
23465 
23466 #ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23467       if( deleteFlag ) {
23468          char fileName[CCHMAXPATH];
23469          /* Skip "\\SHAREMEM\\" */
23470          sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23471          /* restore colon */
23472          fileName[1] = ':';
23473 
23474          DosForceDelete(fileName);
23475       }
23476 #endif
23477 
23478       sqlite3_mutex_free(pNode->mutex);
23479 
23480       sqlite3_free(pNode);
23481 
23482     } else {
23483       ppNode = &pNode->pNext;
23484     }
23485   }
23486 
23487   os2ShmLeaveMutex();
23488 }
23489 
23490 /*
23491 ** This function is called to obtain a pointer to region iRegion of the
23492 ** shared-memory associated with the database file id. Shared-memory regions
23493 ** are numbered starting from zero. Each shared-memory region is szRegion
23494 ** bytes in size.
23495 **
23496 ** If an error occurs, an error code is returned and *pp is set to NULL.
23497 **
23498 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23499 ** region has not been allocated (by any client, including one running in a
23500 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23501 ** bExtend is non-zero and the requested shared-memory region has not yet
23502 ** been allocated, it is allocated by this function.
23503 **
23504 ** If the shared-memory region has already been allocated or is allocated by
23505 ** this call as described above, then it is mapped into this processes
23506 ** address space (if it is not already), *pp is set to point to the mapped
23507 ** memory and SQLITE_OK returned.
23508 */
23509 static int os2ShmMap(
23510   sqlite3_file *id,               /* Handle open on database file */
23511   int iRegion,                    /* Region to retrieve */
23512   int szRegion,                   /* Size of regions */
23513   int bExtend,                    /* True to extend block if necessary */
23514   void volatile **pp              /* OUT: Mapped memory */
23515 ){
23516   PVOID pvTemp;
23517   void **apRegion;
23518   os2ShmNode *pNode;
23519   int n, rc = SQLITE_OK;
23520   char shmName[CCHMAXPATH];
23521   os2File *pFile = (os2File*)id;
23522 
23523   *pp = NULL;
23524 
23525   if( !pFile->pShmLink )
23526     rc = os2OpenSharedMemory( pFile, szRegion );
23527 
23528   if( rc == SQLITE_OK ) {
23529     pNode = pFile->pShmLink->pShmNode ;
23530 
23531     sqlite3_mutex_enter(pNode->mutex);
23532 
23533     assert( szRegion==pNode->szRegion );
23534 
23535     /* Unmapped region ? */
23536     if( iRegion >= pNode->nRegion ) {
23537       /* Prevent other processes from resizing the shared memory */
23538       os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23539 
23540       apRegion = sqlite3_realloc(
23541         pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23542 
23543       if( apRegion ) {
23544         pNode->apRegion = apRegion;
23545 
23546         while( pNode->nRegion <= iRegion ) {
23547           sprintf(shmName, "%s-%u",
23548                   pNode->shmBaseName, pNode->nRegion);
23549 
23550           if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23551                 PAG_READ | PAG_WRITE) != NO_ERROR ) {
23552             if( !bExtend )
23553               break;
23554 
23555             if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23556                   PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23557                 DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23558                   PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23559               rc = SQLITE_NOMEM;
23560               break;
23561             }
23562           }
23563 
23564           apRegion[pNode->nRegion++] = pvTemp;
23565         }
23566 
23567         /* zero out remaining entries */
23568         for( n = pNode->nRegion; n <= iRegion; n++ )
23569           pNode->apRegion[n] = NULL;
23570 
23571         /* Return this region (maybe zero) */
23572         *pp = pNode->apRegion[iRegion];
23573       } else {
23574         rc = SQLITE_NOMEM;
23575       }
23576 
23577       /* Allow other processes to resize the shared memory */
23578       os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23579 
23580     } else {
23581       /* Region has been mapped previously */
23582       *pp = pNode->apRegion[iRegion];
23583     }
23584 
23585     sqlite3_mutex_leave(pNode->mutex);
23586   }
23587 
23588   ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
23589                  pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
23590 
23591   return rc;
23592 }
23593 
23594 /*
23595 ** Close a connection to shared-memory.  Delete the underlying
23596 ** storage if deleteFlag is true.
23597 **
23598 ** If there is no shared memory associated with the connection then this
23599 ** routine is a harmless no-op.
23600 */
23601 static int os2ShmUnmap(
23602   sqlite3_file *id,               /* The underlying database file */
23603   int deleteFlag                  /* Delete shared-memory if true */
23604 ){
23605   os2File *pFile = (os2File*)id;
23606   os2ShmLink *pLink = pFile->pShmLink;
23607 
23608   if( pLink ) {
23609     int nRef = -1;
23610     os2ShmLink **ppLink;
23611     os2ShmNode *pNode = pLink->pShmNode;
23612 
23613     sqlite3_mutex_enter(pNode->mutex);
23614 
23615     for( ppLink = &pNode->pFirst;
23616          *ppLink && *ppLink != pLink;
23617          ppLink = &(*ppLink)->pNext )   ;
23618 
23619     assert(*ppLink);
23620 
23621     if( *ppLink ) {
23622       *ppLink = pLink->pNext;
23623       nRef = --pNode->nRef;
23624     } else {
23625       ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
23626                     pNode->shmBaseName))
23627     }
23628 
23629     pFile->pShmLink = NULL;
23630     sqlite3_free(pLink);
23631 
23632     sqlite3_mutex_leave(pNode->mutex);
23633 
23634     if( nRef == 0 )
23635       os2PurgeShmNodes( deleteFlag );
23636   }
23637 
23638   return SQLITE_OK;
23639 }
23640 
23641 /*
23642 ** Change the lock state for a shared-memory segment.
23643 **
23644 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
23645 ** different here than in posix.  In xShmLock(), one can go from unlocked
23646 ** to shared and back or from unlocked to exclusive and back.  But one may
23647 ** not go from shared to exclusive or from exclusive to shared.
23648 */
23649 static int os2ShmLock(
23650   sqlite3_file *id,          /* Database file holding the shared memory */
23651   int ofst,                  /* First lock to acquire or release */
23652   int n,                     /* Number of locks to acquire or release */
23653   int flags                  /* What to do with the lock */
23654 ){
23655   u32 mask;                             /* Mask of locks to take or release */
23656   int rc = SQLITE_OK;                   /* Result code */
23657   os2File *pFile = (os2File*)id;
23658   os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
23659   os2ShmLink *pX;                       /* For looping over all siblings */
23660   os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
23661 
23662   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
23663   assert( n>=1 );
23664   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
23665        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
23666        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
23667        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
23668   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
23669 
23670   mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
23671   assert( n>1 || mask==(1<<ofst) );
23672 
23673 
23674   sqlite3_mutex_enter(pShmNode->mutex);
23675 
23676   if( flags & SQLITE_SHM_UNLOCK ){
23677     u32 allMask = 0; /* Mask of locks held by siblings */
23678 
23679     /* See if any siblings hold this same lock */
23680     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23681       if( pX==p ) continue;
23682       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
23683       allMask |= pX->sharedMask;
23684     }
23685 
23686     /* Unlock the system-level locks */
23687     if( (mask & allMask)==0 ){
23688       rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
23689     }else{
23690       rc = SQLITE_OK;
23691     }
23692 
23693     /* Undo the local locks */
23694     if( rc==SQLITE_OK ){
23695       p->exclMask &= ~mask;
23696       p->sharedMask &= ~mask;
23697     }
23698   }else if( flags & SQLITE_SHM_SHARED ){
23699     u32 allShared = 0;  /* Union of locks held by connections other than "p" */
23700 
23701     /* Find out which shared locks are already held by sibling connections.
23702     ** If any sibling already holds an exclusive lock, go ahead and return
23703     ** SQLITE_BUSY.
23704     */
23705     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23706       if( (pX->exclMask & mask)!=0 ){
23707         rc = SQLITE_BUSY;
23708         break;
23709       }
23710       allShared |= pX->sharedMask;
23711     }
23712 
23713     /* Get shared locks at the system level, if necessary */
23714     if( rc==SQLITE_OK ){
23715       if( (allShared & mask)==0 ){
23716         rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
23717       }else{
23718         rc = SQLITE_OK;
23719       }
23720     }
23721 
23722     /* Get the local shared locks */
23723     if( rc==SQLITE_OK ){
23724       p->sharedMask |= mask;
23725     }
23726   }else{
23727     /* Make sure no sibling connections hold locks that will block this
23728     ** lock.  If any do, return SQLITE_BUSY right away.
23729     */
23730     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
23731       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
23732         rc = SQLITE_BUSY;
23733         break;
23734       }
23735     }
23736 
23737     /* Get the exclusive locks at the system level.  Then if successful
23738     ** also mark the local connection as being locked.
23739     */
23740     if( rc==SQLITE_OK ){
23741       rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
23742       if( rc==SQLITE_OK ){
23743         assert( (p->sharedMask & mask)==0 );
23744         p->exclMask |= mask;
23745       }
23746     }
23747   }
23748 
23749   sqlite3_mutex_leave(pShmNode->mutex);
23750 
23751   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
23752            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
23753            rc ? "failed" : "ok"));
23754 
23755   ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
23756                  ofst, n, flags, rc))
23757 
23758   return rc;
23759 }
23760 
23761 /*
23762 ** Implement a memory barrier or memory fence on shared memory.
23763 **
23764 ** All loads and stores begun before the barrier must complete before
23765 ** any load or store begun after the barrier.
23766 */
23767 static void os2ShmBarrier(
23768   sqlite3_file *id                /* Database file holding the shared memory */
23769 ){
23770   UNUSED_PARAMETER(id);
23771   os2ShmEnterMutex();
23772   os2ShmLeaveMutex();
23773 }
23774 
23775 #else
23776 # define os2ShmMap     0
23777 # define os2ShmLock    0
23778 # define os2ShmBarrier 0
23779 # define os2ShmUnmap   0
23780 #endif /* #ifndef SQLITE_OMIT_WAL */
23781 
23782 
23783 /*
23784 ** This vector defines all the methods that can operate on an
23785 ** sqlite3_file for os2.
23786 */
23787 static const sqlite3_io_methods os2IoMethod = {
23788   2,                              /* iVersion */
23789   os2Close,                       /* xClose */
23790   os2Read,                        /* xRead */
23791   os2Write,                       /* xWrite */
23792   os2Truncate,                    /* xTruncate */
23793   os2Sync,                        /* xSync */
23794   os2FileSize,                    /* xFileSize */
23795   os2Lock,                        /* xLock */
23796   os2Unlock,                      /* xUnlock */
23797   os2CheckReservedLock,           /* xCheckReservedLock */
23798   os2FileControl,                 /* xFileControl */
23799   os2SectorSize,                  /* xSectorSize */
23800   os2DeviceCharacteristics,       /* xDeviceCharacteristics */
23801   os2ShmMap,                      /* xShmMap */
23802   os2ShmLock,                     /* xShmLock */
23803   os2ShmBarrier,                  /* xShmBarrier */
23804   os2ShmUnmap                     /* xShmUnmap */
23805 };
23806 
23807 
23808 /***************************************************************************
23809 ** Here ends the I/O methods that form the sqlite3_io_methods object.
23810 **
23811 ** The next block of code implements the VFS methods.
23812 ****************************************************************************/
23813 
23814 /*
23815 ** Create a temporary file name in zBuf.  zBuf must be big enough to
23816 ** hold at pVfs->mxPathname characters.
23817 */
23818 static int getTempname(int nBuf, char *zBuf ){
23819   static const char zChars[] =
23820     "abcdefghijklmnopqrstuvwxyz"
23821     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
23822     "0123456789";
23823   int i, j;
23824   PSZ zTempPathCp;
23825   char zTempPath[CCHMAXPATH];
23826   ULONG ulDriveNum, ulDriveMap;
23827 
23828   /* It's odd to simulate an io-error here, but really this is just
23829   ** using the io-error infrastructure to test that SQLite handles this
23830   ** function failing.
23831   */
23832   SimulateIOError( return SQLITE_IOERR );
23833 
23834   if( sqlite3_temp_directory ) {
23835     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
23836   } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
23837              DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
23838              DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
23839     char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
23840     sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
23841     free( zTempPathUTF );
23842   } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
23843     zTempPath[0] = (char)('A' + ulDriveNum - 1);
23844     zTempPath[1] = ':';
23845     zTempPath[2] = '\0';
23846   } else {
23847     zTempPath[0] = '\0';
23848   }
23849 
23850   /* Strip off a trailing slashes or backslashes, otherwise we would get *
23851    * multiple (back)slashes which causes DosOpen() to fail.              *
23852    * Trailing spaces are not allowed, either.                            */
23853   j = sqlite3Strlen30(zTempPath);
23854   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
23855                     zTempPath[j-1] == ' ' ) ){
23856     j--;
23857   }
23858   zTempPath[j] = '\0';
23859 
23860   /* We use 20 bytes to randomize the name */
23861   sqlite3_snprintf(nBuf-22, zBuf,
23862                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
23863   j = sqlite3Strlen30(zBuf);
23864   sqlite3_randomness( 20, &zBuf[j] );
23865   for( i = 0; i < 20; i++, j++ ){
23866     zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
23867   }
23868   zBuf[j] = 0;
23869 
23870   OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
23871   return SQLITE_OK;
23872 }
23873 
23874 
23875 /*
23876 ** Turn a relative pathname into a full pathname.  Write the full
23877 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
23878 ** bytes in size.
23879 */
23880 static int os2FullPathname(
23881   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
23882   const char *zRelative,      /* Possibly relative input path */
23883   int nFull,                  /* Size of output buffer in bytes */
23884   char *zFull                 /* Output buffer */
23885 ){
23886   char *zRelativeCp = convertUtf8PathToCp( zRelative );
23887   char zFullCp[CCHMAXPATH] = "\0";
23888   char *zFullUTF;
23889   APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
23890                                 zFullCp, CCHMAXPATH );
23891   free( zRelativeCp );
23892   zFullUTF = convertCpPathToUtf8( zFullCp );
23893   sqlite3_snprintf( nFull, zFull, zFullUTF );
23894   free( zFullUTF );
23895   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23896 }
23897 
23898 
23899 /*
23900 ** Open a file.
23901 */
23902 static int os2Open(
23903   sqlite3_vfs *pVfs,            /* Not used */
23904   const char *zName,            /* Name of the file (UTF-8) */
23905   sqlite3_file *id,             /* Write the SQLite file handle here */
23906   int flags,                    /* Open mode flags */
23907   int *pOutFlags                /* Status return flags */
23908 ){
23909   HFILE h;
23910   ULONG ulOpenFlags = 0;
23911   ULONG ulOpenMode = 0;
23912   ULONG ulAction = 0;
23913   ULONG rc;
23914   os2File *pFile = (os2File*)id;
23915   const char *zUtf8Name = zName;
23916   char *zNameCp;
23917   char  zTmpname[CCHMAXPATH];
23918 
23919   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
23920   int isCreate     = (flags & SQLITE_OPEN_CREATE);
23921   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
23922 #ifndef NDEBUG
23923   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
23924   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
23925   int eType        = (flags & 0xFFFFFF00);
23926   int isOpenJournal = (isCreate && (
23927         eType==SQLITE_OPEN_MASTER_JOURNAL
23928      || eType==SQLITE_OPEN_MAIN_JOURNAL
23929      || eType==SQLITE_OPEN_WAL
23930   ));
23931 #endif
23932 
23933   UNUSED_PARAMETER(pVfs);
23934   assert( id!=0 );
23935 
23936   /* Check the following statements are true:
23937   **
23938   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
23939   **   (b) if CREATE is set, then READWRITE must also be set, and
23940   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
23941   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
23942   */
23943   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
23944   assert(isCreate==0 || isReadWrite);
23945   assert(isExclusive==0 || isCreate);
23946   assert(isDelete==0 || isCreate);
23947 
23948   /* The main DB, main journal, WAL file and master journal are never
23949   ** automatically deleted. Nor are they ever temporary files.  */
23950   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
23951   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
23952   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
23953   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
23954 
23955   /* Assert that the upper layer has set one of the "file-type" flags. */
23956   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
23957        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
23958        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
23959        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
23960   );
23961 
23962   memset( pFile, 0, sizeof(*pFile) );
23963   pFile->h = (HFILE)-1;
23964 
23965   /* If the second argument to this function is NULL, generate a
23966   ** temporary file name to use
23967   */
23968   if( !zUtf8Name ){
23969     assert(isDelete && !isOpenJournal);
23970     rc = getTempname(CCHMAXPATH, zTmpname);
23971     if( rc!=SQLITE_OK ){
23972       return rc;
23973     }
23974     zUtf8Name = zTmpname;
23975   }
23976 
23977   if( isReadWrite ){
23978     ulOpenMode |= OPEN_ACCESS_READWRITE;
23979   }else{
23980     ulOpenMode |= OPEN_ACCESS_READONLY;
23981   }
23982 
23983   /* Open in random access mode for possibly better speed.  Allow full
23984   ** sharing because file locks will provide exclusive access when needed.
23985   ** The handle should not be inherited by child processes and we don't
23986   ** want popups from the critical error handler.
23987   */
23988   ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
23989                 OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
23990 
23991   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
23992   ** created. SQLite doesn't use it to indicate "exclusive access"
23993   ** as it is usually understood.
23994   */
23995   if( isExclusive ){
23996     /* Creates a new file, only if it does not already exist. */
23997     /* If the file exists, it fails. */
23998     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
23999   }else if( isCreate ){
24000     /* Open existing file, or create if it doesn't exist */
24001     ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24002   }else{
24003     /* Opens a file, only if it exists. */
24004     ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24005   }
24006 
24007   zNameCp = convertUtf8PathToCp( zUtf8Name );
24008   rc = DosOpen( (PSZ)zNameCp,
24009                 &h,
24010                 &ulAction,
24011                 0L,
24012                 FILE_NORMAL,
24013                 ulOpenFlags,
24014                 ulOpenMode,
24015                 (PEAOP2)NULL );
24016   free( zNameCp );
24017 
24018   if( rc != NO_ERROR ){
24019     OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
24020               rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
24021 
24022     if( isReadWrite ){
24023       return os2Open( pVfs, zName, id,
24024                       ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
24025                       pOutFlags );
24026     }else{
24027       return SQLITE_CANTOPEN;
24028     }
24029   }
24030 
24031   if( pOutFlags ){
24032     *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
24033   }
24034 
24035   os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
24036   pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
24037   pFile->pMethod = &os2IoMethod;
24038   pFile->flags = flags;
24039   pFile->h = h;
24040 
24041   OpenCounter(+1);
24042   OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
24043   return SQLITE_OK;
24044 }
24045 
24046 /*
24047 ** Delete the named file.
24048 */
24049 static int os2Delete(
24050   sqlite3_vfs *pVfs,                     /* Not used on os2 */
24051   const char *zFilename,                 /* Name of file to delete */
24052   int syncDir                            /* Not used on os2 */
24053 ){
24054   APIRET rc;
24055   char *zFilenameCp;
24056   SimulateIOError( return SQLITE_IOERR_DELETE );
24057   zFilenameCp = convertUtf8PathToCp( zFilename );
24058   rc = DosDelete( (PSZ)zFilenameCp );
24059   free( zFilenameCp );
24060   OSTRACE(( "DELETE \"%s\"\n", zFilename ));
24061   return (rc == NO_ERROR ||
24062           rc == ERROR_FILE_NOT_FOUND ||
24063           rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
24064 }
24065 
24066 /*
24067 ** Check the existance and status of a file.
24068 */
24069 static int os2Access(
24070   sqlite3_vfs *pVfs,        /* Not used on os2 */
24071   const char *zFilename,    /* Name of file to check */
24072   int flags,                /* Type of test to make on this file */
24073   int *pOut                 /* Write results here */
24074 ){
24075   APIRET rc;
24076   FILESTATUS3 fsts3ConfigInfo;
24077   char *zFilenameCp;
24078 
24079   UNUSED_PARAMETER(pVfs);
24080   SimulateIOError( return SQLITE_IOERR_ACCESS; );
24081 
24082   zFilenameCp = convertUtf8PathToCp( zFilename );
24083   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
24084                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
24085   free( zFilenameCp );
24086   OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
24087             fsts3ConfigInfo.attrFile, flags, rc ));
24088 
24089   switch( flags ){
24090     case SQLITE_ACCESS_EXISTS:
24091       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
24092       ** as if it does not exist.
24093       */
24094       if( fsts3ConfigInfo.cbFile == 0 )
24095         rc = ERROR_FILE_NOT_FOUND;
24096       break;
24097     case SQLITE_ACCESS_READ:
24098       break;
24099     case SQLITE_ACCESS_READWRITE:
24100       if( fsts3ConfigInfo.attrFile & FILE_READONLY )
24101         rc = ERROR_ACCESS_DENIED;
24102       break;
24103     default:
24104       rc = ERROR_FILE_NOT_FOUND;
24105       assert( !"Invalid flags argument" );
24106   }
24107 
24108   *pOut = (rc == NO_ERROR);
24109   OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24110 
24111   return SQLITE_OK;
24112 }
24113 
24114 
24115 #ifndef SQLITE_OMIT_LOAD_EXTENSION
24116 /*
24117 ** Interfaces for opening a shared library, finding entry points
24118 ** within the shared library, and closing the shared library.
24119 */
24120 /*
24121 ** Interfaces for opening a shared library, finding entry points
24122 ** within the shared library, and closing the shared library.
24123 */
24124 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24125   HMODULE hmod;
24126   APIRET rc;
24127   char *zFilenameCp = convertUtf8PathToCp(zFilename);
24128   rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24129   free(zFilenameCp);
24130   return rc != NO_ERROR ? 0 : (void*)hmod;
24131 }
24132 /*
24133 ** A no-op since the error code is returned on the DosLoadModule call.
24134 ** os2Dlopen returns zero if DosLoadModule is not successful.
24135 */
24136 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24137 /* no-op */
24138 }
24139 static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24140   PFN pfn;
24141   APIRET rc;
24142   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24143   if( rc != NO_ERROR ){
24144     /* if the symbol itself was not found, search again for the same
24145      * symbol with an extra underscore, that might be needed depending
24146      * on the calling convention */
24147     char _zSymbol[256] = "_";
24148     strncat(_zSymbol, zSymbol, 254);
24149     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24150   }
24151   return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24152 }
24153 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24154   DosFreeModule((HMODULE)pHandle);
24155 }
24156 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24157   #define os2DlOpen 0
24158   #define os2DlError 0
24159   #define os2DlSym 0
24160   #define os2DlClose 0
24161 #endif
24162 
24163 
24164 /*
24165 ** Write up to nBuf bytes of randomness into zBuf.
24166 */
24167 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24168   int n = 0;
24169 #if defined(SQLITE_TEST)
24170   n = nBuf;
24171   memset(zBuf, 0, nBuf);
24172 #else
24173   int i;
24174   PPIB ppib;
24175   PTIB ptib;
24176   DATETIME dt;
24177   static unsigned c = 0;
24178   /* Ordered by variation probability */
24179   static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24180                             QSV_MAXPRMEM, QSV_MAXSHMEM,
24181                             QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24182 
24183   /* 8 bytes; timezone and weekday don't increase the randomness much */
24184   if( (int)sizeof(dt)-3 <= nBuf - n ){
24185     c += 0x0100;
24186     DosGetDateTime(&dt);
24187     dt.year = (USHORT)((dt.year - 1900) | c);
24188     memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24189     n += sizeof(dt)-3;
24190   }
24191 
24192   /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24193   if( (int)sizeof(ULONG) <= nBuf - n ){
24194     DosGetInfoBlocks(&ptib, &ppib);
24195     *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24196                                  ptib->tib_ptib2->tib2_ultid);
24197     n += sizeof(ULONG);
24198   }
24199 
24200   /* Up to 6 * 4 bytes; variables depend on the system state */
24201   for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24202     DosQuerySysInfo(svIdx[i], svIdx[i],
24203                     (PULONG)&zBuf[n], sizeof(ULONG));
24204     n += sizeof(ULONG);
24205   }
24206 #endif
24207 
24208   return n;
24209 }
24210 
24211 /*
24212 ** Sleep for a little while.  Return the amount of time slept.
24213 ** The argument is the number of microseconds we want to sleep.
24214 ** The return value is the number of microseconds of sleep actually
24215 ** requested from the underlying operating system, a number which
24216 ** might be greater than or equal to the argument, but not less
24217 ** than the argument.
24218 */
24219 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24220   DosSleep( (microsec/1000) );
24221   return microsec;
24222 }
24223 
24224 /*
24225 ** The following variable, if set to a non-zero value, becomes the result
24226 ** returned from sqlite3OsCurrentTime().  This is used for testing.
24227 */
24228 #ifdef SQLITE_TEST
24229 SQLITE_API int sqlite3_current_time = 0;
24230 #endif
24231 
24232 /*
24233 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
24234 ** the current time and date as a Julian Day number times 86_400_000.  In
24235 ** other words, write into *piNow the number of milliseconds since the Julian
24236 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24237 ** proleptic Gregorian calendar.
24238 **
24239 ** On success, return 0.  Return 1 if the time and date cannot be found.
24240 */
24241 static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24242 #ifdef SQLITE_TEST
24243   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24244 #endif
24245   int year, month, datepart, timepart;
24246 
24247   DATETIME dt;
24248   DosGetDateTime( &dt );
24249 
24250   year = dt.year;
24251   month = dt.month;
24252 
24253   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24254   ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24255   ** Calculate the Julian days
24256   */
24257   datepart = (int)dt.day - 32076 +
24258     1461*(year + 4800 + (month - 14)/12)/4 +
24259     367*(month - 2 - (month - 14)/12*12)/12 -
24260     3*((year + 4900 + (month - 14)/12)/100)/4;
24261 
24262   /* Time in milliseconds, hours to noon added */
24263   timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24264     ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24265 
24266   *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24267 
24268 #ifdef SQLITE_TEST
24269   if( sqlite3_current_time ){
24270     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24271   }
24272 #endif
24273 
24274   UNUSED_PARAMETER(pVfs);
24275   return 0;
24276 }
24277 
24278 /*
24279 ** Find the current time (in Universal Coordinated Time).  Write the
24280 ** current time and date as a Julian Day number into *prNow and
24281 ** return 0.  Return 1 if the time and date cannot be found.
24282 */
24283 static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24284   int rc;
24285   sqlite3_int64 i;
24286   rc = os2CurrentTimeInt64(pVfs, &i);
24287   if( !rc ){
24288     *prNow = i/86400000.0;
24289   }
24290   return rc;
24291 }
24292 
24293 /*
24294 ** The idea is that this function works like a combination of
24295 ** GetLastError() and FormatMessage() on windows (or errno and
24296 ** strerror_r() on unix). After an error is returned by an OS
24297 ** function, SQLite calls this function with zBuf pointing to
24298 ** a buffer of nBuf bytes. The OS layer should populate the
24299 ** buffer with a nul-terminated UTF-8 encoded error message
24300 ** describing the last IO error to have occurred within the calling
24301 ** thread.
24302 **
24303 ** If the error message is too large for the supplied buffer,
24304 ** it should be truncated. The return value of xGetLastError
24305 ** is zero if the error message fits in the buffer, or non-zero
24306 ** otherwise (if the message was truncated). If non-zero is returned,
24307 ** then it is not necessary to include the nul-terminator character
24308 ** in the output buffer.
24309 **
24310 ** Not supplying an error message will have no adverse effect
24311 ** on SQLite. It is fine to have an implementation that never
24312 ** returns an error message:
24313 **
24314 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24315 **     assert(zBuf[0]=='\0');
24316 **     return 0;
24317 **   }
24318 **
24319 ** However if an error message is supplied, it will be incorporated
24320 ** by sqlite into the error message available to the user using
24321 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
24322 */
24323 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24324   assert(zBuf[0]=='\0');
24325   return 0;
24326 }
24327 
24328 /*
24329 ** Initialize and deinitialize the operating system interface.
24330 */
24331 SQLITE_API int sqlite3_os_init(void){
24332   static sqlite3_vfs os2Vfs = {
24333     3,                 /* iVersion */
24334     sizeof(os2File),   /* szOsFile */
24335     CCHMAXPATH,        /* mxPathname */
24336     0,                 /* pNext */
24337     "os2",             /* zName */
24338     0,                 /* pAppData */
24339 
24340     os2Open,           /* xOpen */
24341     os2Delete,         /* xDelete */
24342     os2Access,         /* xAccess */
24343     os2FullPathname,   /* xFullPathname */
24344     os2DlOpen,         /* xDlOpen */
24345     os2DlError,        /* xDlError */
24346     os2DlSym,          /* xDlSym */
24347     os2DlClose,        /* xDlClose */
24348     os2Randomness,     /* xRandomness */
24349     os2Sleep,          /* xSleep */
24350     os2CurrentTime,    /* xCurrentTime */
24351     os2GetLastError,   /* xGetLastError */
24352     os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24353     0,                 /* xSetSystemCall */
24354     0,                 /* xGetSystemCall */
24355     0                  /* xNextSystemCall */
24356   };
24357   sqlite3_vfs_register(&os2Vfs, 1);
24358   initUconvObjects();
24359 /*  sqlite3OSTrace = 1; */
24360   return SQLITE_OK;
24361 }
24362 SQLITE_API int sqlite3_os_end(void){
24363   freeUconvObjects();
24364   return SQLITE_OK;
24365 }
24366 
24367 #endif /* SQLITE_OS_OS2 */
24368 
24369 /************** End of os_os2.c **********************************************/
24370 /************** Begin file os_unix.c *****************************************/
24371 /*
24372 ** 2004 May 22
24373 **
24374 ** The author disclaims copyright to this source code.  In place of
24375 ** a legal notice, here is a blessing:
24376 **
24377 **    May you do good and not evil.
24378 **    May you find forgiveness for yourself and forgive others.
24379 **    May you share freely, never taking more than you give.
24380 **
24381 ******************************************************************************
24382 **
24383 ** This file contains the VFS implementation for unix-like operating systems
24384 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24385 **
24386 ** There are actually several different VFS implementations in this file.
24387 ** The differences are in the way that file locking is done.  The default
24388 ** implementation uses Posix Advisory Locks.  Alternative implementations
24389 ** use flock(), dot-files, various proprietary locking schemas, or simply
24390 ** skip locking all together.
24391 **
24392 ** This source file is organized into divisions where the logic for various
24393 ** subfunctions is contained within the appropriate division.  PLEASE
24394 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24395 ** in the correct division and should be clearly labeled.
24396 **
24397 ** The layout of divisions is as follows:
24398 **
24399 **   *  General-purpose declarations and utility functions.
24400 **   *  Unique file ID logic used by VxWorks.
24401 **   *  Various locking primitive implementations (all except proxy locking):
24402 **      + for Posix Advisory Locks
24403 **      + for no-op locks
24404 **      + for dot-file locks
24405 **      + for flock() locking
24406 **      + for named semaphore locks (VxWorks only)
24407 **      + for AFP filesystem locks (MacOSX only)
24408 **   *  sqlite3_file methods not associated with locking.
24409 **   *  Definitions of sqlite3_io_methods objects for all locking
24410 **      methods plus "finder" functions for each locking method.
24411 **   *  sqlite3_vfs method implementations.
24412 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24413 **   *  Definitions of sqlite3_vfs objects for all locking methods
24414 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24415 */
24416 #if SQLITE_OS_UNIX              /* This file is used on unix only */
24417 
24418 /*
24419 ** There are various methods for file locking used for concurrency
24420 ** control:
24421 **
24422 **   1. POSIX locking (the default),
24423 **   2. No locking,
24424 **   3. Dot-file locking,
24425 **   4. flock() locking,
24426 **   5. AFP locking (OSX only),
24427 **   6. Named POSIX semaphores (VXWorks only),
24428 **   7. proxy locking. (OSX only)
24429 **
24430 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24431 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24432 ** selection of the appropriate locking style based on the filesystem
24433 ** where the database is located.
24434 */
24435 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24436 #  if defined(__APPLE__)
24437 #    define SQLITE_ENABLE_LOCKING_STYLE 1
24438 #  else
24439 #    define SQLITE_ENABLE_LOCKING_STYLE 0
24440 #  endif
24441 #endif
24442 
24443 /*
24444 ** Define the OS_VXWORKS pre-processor macro to 1 if building on
24445 ** vxworks, or 0 otherwise.
24446 */
24447 #ifndef OS_VXWORKS
24448 #  if defined(__RTP__) || defined(_WRS_KERNEL)
24449 #    define OS_VXWORKS 1
24450 #  else
24451 #    define OS_VXWORKS 0
24452 #  endif
24453 #endif
24454 
24455 /*
24456 ** These #defines should enable >2GB file support on Posix if the
24457 ** underlying operating system supports it.  If the OS lacks
24458 ** large file support, these should be no-ops.
24459 **
24460 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24461 ** on the compiler command line.  This is necessary if you are compiling
24462 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
24463 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24464 ** without this option, LFS is enable.  But LFS does not exist in the kernel
24465 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24466 ** portability you should omit LFS.
24467 **
24468 ** The previous paragraph was written in 2005.  (This paragraph is written
24469 ** on 2008-11-28.) These days, all Linux kernels support large files, so
24470 ** you should probably leave LFS enabled.  But some embedded platforms might
24471 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24472 */
24473 #ifndef SQLITE_DISABLE_LFS
24474 # define _LARGE_FILE       1
24475 # ifndef _FILE_OFFSET_BITS
24476 #   define _FILE_OFFSET_BITS 64
24477 # endif
24478 # define _LARGEFILE_SOURCE 1
24479 #endif
24480 
24481 /*
24482 ** standard include files.
24483 */
24484 #include <sys/types.h>
24485 #include <sys/stat.h>
24486 #include <fcntl.h>
24487 #include <unistd.h>
24488 /* #include <time.h> */
24489 #include <sys/time.h>
24490 #include <errno.h>
24491 #ifndef SQLITE_OMIT_WAL
24492 #include <sys/mman.h>
24493 #endif
24494 
24495 #if SQLITE_ENABLE_LOCKING_STYLE
24496 # include <sys/ioctl.h>
24497 # if OS_VXWORKS
24498 #  include <semaphore.h>
24499 #  include <limits.h>
24500 # else
24501 #  include <sys/file.h>
24502 #  include <sys/param.h>
24503 # endif
24504 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
24505 
24506 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24507 # include <sys/mount.h>
24508 #endif
24509 
24510 #ifdef HAVE_UTIME
24511 # include <utime.h>
24512 #endif
24513 
24514 /*
24515 ** Allowed values of unixFile.fsFlags
24516 */
24517 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
24518 
24519 /*
24520 ** If we are to be thread-safe, include the pthreads header and define
24521 ** the SQLITE_UNIX_THREADS macro.
24522 */
24523 #if SQLITE_THREADSAFE
24524 /* # include <pthread.h> */
24525 # define SQLITE_UNIX_THREADS 1
24526 #endif
24527 
24528 /*
24529 ** Default permissions when creating a new file
24530 */
24531 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24532 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24533 #endif
24534 
24535 /*
24536  ** Default permissions when creating auto proxy dir
24537  */
24538 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24539 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24540 #endif
24541 
24542 /*
24543 ** Maximum supported path-length.
24544 */
24545 #define MAX_PATHNAME 512
24546 
24547 /*
24548 ** Only set the lastErrno if the error code is a real error and not
24549 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24550 */
24551 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24552 
24553 /* Forward references */
24554 typedef struct unixShm unixShm;               /* Connection shared memory */
24555 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24556 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24557 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24558 
24559 /*
24560 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
24561 ** cannot be closed immediately. In these cases, instances of the following
24562 ** structure are used to store the file descriptor while waiting for an
24563 ** opportunity to either close or reuse it.
24564 */
24565 struct UnixUnusedFd {
24566   int fd;                   /* File descriptor to close */
24567   int flags;                /* Flags this file descriptor was opened with */
24568   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
24569 };
24570 
24571 /*
24572 ** The unixFile structure is subclass of sqlite3_file specific to the unix
24573 ** VFS implementations.
24574 */
24575 typedef struct unixFile unixFile;
24576 struct unixFile {
24577   sqlite3_io_methods const *pMethod;  /* Always the first entry */
24578   unixInodeInfo *pInode;              /* Info about locks on this inode */
24579   int h;                              /* The file descriptor */
24580   unsigned char eFileLock;            /* The type of lock held on this fd */
24581   unsigned char ctrlFlags;            /* Behavioral bits.  UNIXFILE_* flags */
24582   int lastErrno;                      /* The unix errno from last I/O error */
24583   void *lockingContext;               /* Locking style specific state */
24584   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
24585   const char *zPath;                  /* Name of the file */
24586   unixShm *pShm;                      /* Shared memory segment information */
24587   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
24588 #if SQLITE_ENABLE_LOCKING_STYLE
24589   int openFlags;                      /* The flags specified at open() */
24590 #endif
24591 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
24592   unsigned fsFlags;                   /* cached details from statfs() */
24593 #endif
24594 #if OS_VXWORKS
24595   int isDelete;                       /* Delete on close if true */
24596   struct vxworksFileId *pId;          /* Unique file ID */
24597 #endif
24598 #ifndef NDEBUG
24599   /* The next group of variables are used to track whether or not the
24600   ** transaction counter in bytes 24-27 of database files are updated
24601   ** whenever any part of the database changes.  An assertion fault will
24602   ** occur if a file is updated without also updating the transaction
24603   ** counter.  This test is made to avoid new problems similar to the
24604   ** one described by ticket #3584.
24605   */
24606   unsigned char transCntrChng;   /* True if the transaction counter changed */
24607   unsigned char dbUpdate;        /* True if any part of database file changed */
24608   unsigned char inNormalWrite;   /* True if in a normal write operation */
24609 #endif
24610 #ifdef SQLITE_TEST
24611   /* In test mode, increase the size of this structure a bit so that
24612   ** it is larger than the struct CrashFile defined in test6.c.
24613   */
24614   char aPadding[32];
24615 #endif
24616 };
24617 
24618 /*
24619 ** Allowed values for the unixFile.ctrlFlags bitmask:
24620 */
24621 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
24622 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
24623 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
24624 #ifndef SQLITE_DISABLE_DIRSYNC
24625 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
24626 #else
24627 # define UNIXFILE_DIRSYNC    0x00
24628 #endif
24629 
24630 /*
24631 ** Include code that is common to all os_*.c files
24632 */
24633 /************** Include os_common.h in the middle of os_unix.c ***************/
24634 /************** Begin file os_common.h ***************************************/
24635 /*
24636 ** 2004 May 22
24637 **
24638 ** The author disclaims copyright to this source code.  In place of
24639 ** a legal notice, here is a blessing:
24640 **
24641 **    May you do good and not evil.
24642 **    May you find forgiveness for yourself and forgive others.
24643 **    May you share freely, never taking more than you give.
24644 **
24645 ******************************************************************************
24646 **
24647 ** This file contains macros and a little bit of code that is common to
24648 ** all of the platform-specific files (os_*.c) and is #included into those
24649 ** files.
24650 **
24651 ** This file should be #included by the os_*.c files only.  It is not a
24652 ** general purpose header file.
24653 */
24654 #ifndef _OS_COMMON_H_
24655 #define _OS_COMMON_H_
24656 
24657 /*
24658 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
24659 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
24660 ** switch.  The following code should catch this problem at compile-time.
24661 */
24662 #ifdef MEMORY_DEBUG
24663 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
24664 #endif
24665 
24666 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
24667 # ifndef SQLITE_DEBUG_OS_TRACE
24668 #   define SQLITE_DEBUG_OS_TRACE 0
24669 # endif
24670   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
24671 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
24672 #else
24673 # define OSTRACE(X)
24674 #endif
24675 
24676 /*
24677 ** Macros for performance tracing.  Normally turned off.  Only works
24678 ** on i486 hardware.
24679 */
24680 #ifdef SQLITE_PERFORMANCE_TRACE
24681 
24682 /*
24683 ** hwtime.h contains inline assembler code for implementing
24684 ** high-performance timing routines.
24685 */
24686 /************** Include hwtime.h in the middle of os_common.h ****************/
24687 /************** Begin file hwtime.h ******************************************/
24688 /*
24689 ** 2008 May 27
24690 **
24691 ** The author disclaims copyright to this source code.  In place of
24692 ** a legal notice, here is a blessing:
24693 **
24694 **    May you do good and not evil.
24695 **    May you find forgiveness for yourself and forgive others.
24696 **    May you share freely, never taking more than you give.
24697 **
24698 ******************************************************************************
24699 **
24700 ** This file contains inline asm code for retrieving "high-performance"
24701 ** counters for x86 class CPUs.
24702 */
24703 #ifndef _HWTIME_H_
24704 #define _HWTIME_H_
24705 
24706 /*
24707 ** The following routine only works on pentium-class (or newer) processors.
24708 ** It uses the RDTSC opcode to read the cycle count value out of the
24709 ** processor and returns that value.  This can be used for high-res
24710 ** profiling.
24711 */
24712 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
24713       (defined(i386) || defined(__i386__) || defined(_M_IX86))
24714 
24715   #if defined(__GNUC__)
24716 
24717   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24718      unsigned int lo, hi;
24719      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
24720      return (sqlite_uint64)hi << 32 | lo;
24721   }
24722 
24723   #elif defined(_MSC_VER)
24724 
24725   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
24726      __asm {
24727         rdtsc
24728         ret       ; return value at EDX:EAX
24729      }
24730   }
24731 
24732   #endif
24733 
24734 #elif (defined(__GNUC__) && defined(__x86_64__))
24735 
24736   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24737       unsigned long val;
24738       __asm__ __volatile__ ("rdtsc" : "=A" (val));
24739       return val;
24740   }
24741 
24742 #elif (defined(__GNUC__) && defined(__ppc__))
24743 
24744   __inline__ sqlite_uint64 sqlite3Hwtime(void){
24745       unsigned long long retval;
24746       unsigned long junk;
24747       __asm__ __volatile__ ("\n\
24748           1:      mftbu   %1\n\
24749                   mftb    %L0\n\
24750                   mftbu   %0\n\
24751                   cmpw    %0,%1\n\
24752                   bne     1b"
24753                   : "=r" (retval), "=r" (junk));
24754       return retval;
24755   }
24756 
24757 #else
24758 
24759   #error Need implementation of sqlite3Hwtime() for your platform.
24760 
24761   /*
24762   ** To compile without implementing sqlite3Hwtime() for your platform,
24763   ** you can remove the above #error and use the following
24764   ** stub function.  You will lose timing support for many
24765   ** of the debugging and testing utilities, but it should at
24766   ** least compile and run.
24767   */
24768 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
24769 
24770 #endif
24771 
24772 #endif /* !defined(_HWTIME_H_) */
24773 
24774 /************** End of hwtime.h **********************************************/
24775 /************** Continuing where we left off in os_common.h ******************/
24776 
24777 static sqlite_uint64 g_start;
24778 static sqlite_uint64 g_elapsed;
24779 #define TIMER_START       g_start=sqlite3Hwtime()
24780 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
24781 #define TIMER_ELAPSED     g_elapsed
24782 #else
24783 #define TIMER_START
24784 #define TIMER_END
24785 #define TIMER_ELAPSED     ((sqlite_uint64)0)
24786 #endif
24787 
24788 /*
24789 ** If we compile with the SQLITE_TEST macro set, then the following block
24790 ** of code will give us the ability to simulate a disk I/O error.  This
24791 ** is used for testing the I/O recovery logic.
24792 */
24793 #ifdef SQLITE_TEST
24794 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
24795 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
24796 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
24797 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
24798 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
24799 SQLITE_API int sqlite3_diskfull_pending = 0;
24800 SQLITE_API int sqlite3_diskfull = 0;
24801 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
24802 #define SimulateIOError(CODE)  \
24803   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
24804        || sqlite3_io_error_pending-- == 1 )  \
24805               { local_ioerr(); CODE; }
24806 static void local_ioerr(){
24807   IOTRACE(("IOERR\n"));
24808   sqlite3_io_error_hit++;
24809   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
24810 }
24811 #define SimulateDiskfullError(CODE) \
24812    if( sqlite3_diskfull_pending ){ \
24813      if( sqlite3_diskfull_pending == 1 ){ \
24814        local_ioerr(); \
24815        sqlite3_diskfull = 1; \
24816        sqlite3_io_error_hit = 1; \
24817        CODE; \
24818      }else{ \
24819        sqlite3_diskfull_pending--; \
24820      } \
24821    }
24822 #else
24823 #define SimulateIOErrorBenign(X)
24824 #define SimulateIOError(A)
24825 #define SimulateDiskfullError(A)
24826 #endif
24827 
24828 /*
24829 ** When testing, keep a count of the number of open files.
24830 */
24831 #ifdef SQLITE_TEST
24832 SQLITE_API int sqlite3_open_file_count = 0;
24833 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
24834 #else
24835 #define OpenCounter(X)
24836 #endif
24837 
24838 #endif /* !defined(_OS_COMMON_H_) */
24839 
24840 /************** End of os_common.h *******************************************/
24841 /************** Continuing where we left off in os_unix.c ********************/
24842 
24843 /*
24844 ** Define various macros that are missing from some systems.
24845 */
24846 #ifndef O_LARGEFILE
24847 # define O_LARGEFILE 0
24848 #endif
24849 #ifdef SQLITE_DISABLE_LFS
24850 # undef O_LARGEFILE
24851 # define O_LARGEFILE 0
24852 #endif
24853 #ifndef O_NOFOLLOW
24854 # define O_NOFOLLOW 0
24855 #endif
24856 #ifndef O_BINARY
24857 # define O_BINARY 0
24858 #endif
24859 
24860 /*
24861 ** The threadid macro resolves to the thread-id or to 0.  Used for
24862 ** testing and debugging only.
24863 */
24864 #if SQLITE_THREADSAFE
24865 #define threadid pthread_self()
24866 #else
24867 #define threadid 0
24868 #endif
24869 
24870 /*
24871 ** Different Unix systems declare open() in different ways.  Same use
24872 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
24873 ** The difference is important when using a pointer to the function.
24874 **
24875 ** The safest way to deal with the problem is to always use this wrapper
24876 ** which always has the same well-defined interface.
24877 */
24878 static int posixOpen(const char *zFile, int flags, int mode){
24879   return open(zFile, flags, mode);
24880 }
24881 
24882 /* Forward reference */
24883 static int openDirectory(const char*, int*);
24884 
24885 /*
24886 ** Many system calls are accessed through pointer-to-functions so that
24887 ** they may be overridden at runtime to facilitate fault injection during
24888 ** testing and sandboxing.  The following array holds the names and pointers
24889 ** to all overrideable system calls.
24890 */
24891 static struct unix_syscall {
24892   const char *zName;            /* Name of the sytem call */
24893   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
24894   sqlite3_syscall_ptr pDefault; /* Default value */
24895 } aSyscall[] = {
24896   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
24897 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
24898 
24899   { "close",        (sqlite3_syscall_ptr)close,      0  },
24900 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
24901 
24902   { "access",       (sqlite3_syscall_ptr)access,     0  },
24903 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
24904 
24905   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
24906 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
24907 
24908   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
24909 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
24910 
24911 /*
24912 ** The DJGPP compiler environment looks mostly like Unix, but it
24913 ** lacks the fcntl() system call.  So redefine fcntl() to be something
24914 ** that always succeeds.  This means that locking does not occur under
24915 ** DJGPP.  But it is DOS - what did you expect?
24916 */
24917 #ifdef __DJGPP__
24918   { "fstat",        0,                 0  },
24919 #define osFstat(a,b,c)    0
24920 #else
24921   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
24922 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
24923 #endif
24924 
24925   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
24926 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
24927 
24928   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
24929 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
24930 
24931   { "read",         (sqlite3_syscall_ptr)read,       0  },
24932 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
24933 
24934 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24935   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
24936 #else
24937   { "pread",        (sqlite3_syscall_ptr)0,          0  },
24938 #endif
24939 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
24940 
24941 #if defined(USE_PREAD64)
24942   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
24943 #else
24944   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
24945 #endif
24946 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
24947 
24948   { "write",        (sqlite3_syscall_ptr)write,      0  },
24949 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
24950 
24951 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
24952   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
24953 #else
24954   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
24955 #endif
24956 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
24957                     aSyscall[12].pCurrent)
24958 
24959 #if defined(USE_PREAD64)
24960   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
24961 #else
24962   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
24963 #endif
24964 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
24965                     aSyscall[13].pCurrent)
24966 
24967 #if SQLITE_ENABLE_LOCKING_STYLE
24968   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
24969 #else
24970   { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
24971 #endif
24972 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
24973 
24974 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
24975   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
24976 #else
24977   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
24978 #endif
24979 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
24980 
24981   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
24982 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
24983 
24984   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
24985 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
24986 
24987 }; /* End of the overrideable system calls */
24988 
24989 /*
24990 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
24991 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
24992 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
24993 ** system call named zName.
24994 */
24995 static int unixSetSystemCall(
24996   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
24997   const char *zName,            /* Name of system call to override */
24998   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
24999 ){
25000   unsigned int i;
25001   int rc = SQLITE_NOTFOUND;
25002 
25003   UNUSED_PARAMETER(pNotUsed);
25004   if( zName==0 ){
25005     /* If no zName is given, restore all system calls to their default
25006     ** settings and return NULL
25007     */
25008     rc = SQLITE_OK;
25009     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25010       if( aSyscall[i].pDefault ){
25011         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25012       }
25013     }
25014   }else{
25015     /* If zName is specified, operate on only the one system call
25016     ** specified.
25017     */
25018     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25019       if( strcmp(zName, aSyscall[i].zName)==0 ){
25020         if( aSyscall[i].pDefault==0 ){
25021           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25022         }
25023         rc = SQLITE_OK;
25024         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25025         aSyscall[i].pCurrent = pNewFunc;
25026         break;
25027       }
25028     }
25029   }
25030   return rc;
25031 }
25032 
25033 /*
25034 ** Return the value of a system call.  Return NULL if zName is not a
25035 ** recognized system call name.  NULL is also returned if the system call
25036 ** is currently undefined.
25037 */
25038 static sqlite3_syscall_ptr unixGetSystemCall(
25039   sqlite3_vfs *pNotUsed,
25040   const char *zName
25041 ){
25042   unsigned int i;
25043 
25044   UNUSED_PARAMETER(pNotUsed);
25045   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25046     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25047   }
25048   return 0;
25049 }
25050 
25051 /*
25052 ** Return the name of the first system call after zName.  If zName==NULL
25053 ** then return the name of the first system call.  Return NULL if zName
25054 ** is the last system call or if zName is not the name of a valid
25055 ** system call.
25056 */
25057 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25058   int i = -1;
25059 
25060   UNUSED_PARAMETER(p);
25061   if( zName ){
25062     for(i=0; i<ArraySize(aSyscall)-1; i++){
25063       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25064     }
25065   }
25066   for(i++; i<ArraySize(aSyscall); i++){
25067     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25068   }
25069   return 0;
25070 }
25071 
25072 /*
25073 ** Retry open() calls that fail due to EINTR
25074 */
25075 static int robust_open(const char *z, int f, int m){
25076   int rc;
25077   do{ rc = osOpen(z,f,m); }while( rc<0 && errno==EINTR );
25078   return rc;
25079 }
25080 
25081 /*
25082 ** Helper functions to obtain and relinquish the global mutex. The
25083 ** global mutex is used to protect the unixInodeInfo and
25084 ** vxworksFileId objects used by this file, all of which may be
25085 ** shared by multiple threads.
25086 **
25087 ** Function unixMutexHeld() is used to assert() that the global mutex
25088 ** is held when required. This function is only used as part of assert()
25089 ** statements. e.g.
25090 **
25091 **   unixEnterMutex()
25092 **     assert( unixMutexHeld() );
25093 **   unixEnterLeave()
25094 */
25095 static void unixEnterMutex(void){
25096   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25097 }
25098 static void unixLeaveMutex(void){
25099   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25100 }
25101 #ifdef SQLITE_DEBUG
25102 static int unixMutexHeld(void) {
25103   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25104 }
25105 #endif
25106 
25107 
25108 #ifdef SQLITE_DEBUG
25109 /*
25110 ** Helper function for printing out trace information from debugging
25111 ** binaries. This returns the string represetation of the supplied
25112 ** integer lock-type.
25113 */
25114 static const char *azFileLock(int eFileLock){
25115   switch( eFileLock ){
25116     case NO_LOCK: return "NONE";
25117     case SHARED_LOCK: return "SHARED";
25118     case RESERVED_LOCK: return "RESERVED";
25119     case PENDING_LOCK: return "PENDING";
25120     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25121   }
25122   return "ERROR";
25123 }
25124 #endif
25125 
25126 #ifdef SQLITE_LOCK_TRACE
25127 /*
25128 ** Print out information about all locking operations.
25129 **
25130 ** This routine is used for troubleshooting locks on multithreaded
25131 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25132 ** command-line option on the compiler.  This code is normally
25133 ** turned off.
25134 */
25135 static int lockTrace(int fd, int op, struct flock *p){
25136   char *zOpName, *zType;
25137   int s;
25138   int savedErrno;
25139   if( op==F_GETLK ){
25140     zOpName = "GETLK";
25141   }else if( op==F_SETLK ){
25142     zOpName = "SETLK";
25143   }else{
25144     s = osFcntl(fd, op, p);
25145     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25146     return s;
25147   }
25148   if( p->l_type==F_RDLCK ){
25149     zType = "RDLCK";
25150   }else if( p->l_type==F_WRLCK ){
25151     zType = "WRLCK";
25152   }else if( p->l_type==F_UNLCK ){
25153     zType = "UNLCK";
25154   }else{
25155     assert( 0 );
25156   }
25157   assert( p->l_whence==SEEK_SET );
25158   s = osFcntl(fd, op, p);
25159   savedErrno = errno;
25160   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25161      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25162      (int)p->l_pid, s);
25163   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25164     struct flock l2;
25165     l2 = *p;
25166     osFcntl(fd, F_GETLK, &l2);
25167     if( l2.l_type==F_RDLCK ){
25168       zType = "RDLCK";
25169     }else if( l2.l_type==F_WRLCK ){
25170       zType = "WRLCK";
25171     }else if( l2.l_type==F_UNLCK ){
25172       zType = "UNLCK";
25173     }else{
25174       assert( 0 );
25175     }
25176     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25177        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25178   }
25179   errno = savedErrno;
25180   return s;
25181 }
25182 #undef osFcntl
25183 #define osFcntl lockTrace
25184 #endif /* SQLITE_LOCK_TRACE */
25185 
25186 /*
25187 ** Retry ftruncate() calls that fail due to EINTR
25188 */
25189 static int robust_ftruncate(int h, sqlite3_int64 sz){
25190   int rc;
25191   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25192   return rc;
25193 }
25194 
25195 /*
25196 ** This routine translates a standard POSIX errno code into something
25197 ** useful to the clients of the sqlite3 functions.  Specifically, it is
25198 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
25199 ** and a variety of "please close the file descriptor NOW" errors into
25200 ** SQLITE_IOERR
25201 **
25202 ** Errors during initialization of locks, or file system support for locks,
25203 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25204 */
25205 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25206   switch (posixError) {
25207 #if 0
25208   /* At one point this code was not commented out. In theory, this branch
25209   ** should never be hit, as this function should only be called after
25210   ** a locking-related function (i.e. fcntl()) has returned non-zero with
25211   ** the value of errno as the first argument. Since a system call has failed,
25212   ** errno should be non-zero.
25213   **
25214   ** Despite this, if errno really is zero, we still don't want to return
25215   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25216   ** propagated back to the caller. Commenting this branch out means errno==0
25217   ** will be handled by the "default:" case below.
25218   */
25219   case 0:
25220     return SQLITE_OK;
25221 #endif
25222 
25223   case EAGAIN:
25224   case ETIMEDOUT:
25225   case EBUSY:
25226   case EINTR:
25227   case ENOLCK:
25228     /* random NFS retry error, unless during file system support
25229      * introspection, in which it actually means what it says */
25230     return SQLITE_BUSY;
25231 
25232   case EACCES:
25233     /* EACCES is like EAGAIN during locking operations, but not any other time*/
25234     if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25235 	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25236 	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25237 	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25238       return SQLITE_BUSY;
25239     }
25240     /* else fall through */
25241   case EPERM:
25242     return SQLITE_PERM;
25243 
25244   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25245   ** this module never makes such a call. And the code in SQLite itself
25246   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25247   ** this case is also commented out. If the system does set errno to EDEADLK,
25248   ** the default SQLITE_IOERR_XXX code will be returned. */
25249 #if 0
25250   case EDEADLK:
25251     return SQLITE_IOERR_BLOCKED;
25252 #endif
25253 
25254 #if EOPNOTSUPP!=ENOTSUP
25255   case EOPNOTSUPP:
25256     /* something went terribly awry, unless during file system support
25257      * introspection, in which it actually means what it says */
25258 #endif
25259 #ifdef ENOTSUP
25260   case ENOTSUP:
25261     /* invalid fd, unless during file system support introspection, in which
25262      * it actually means what it says */
25263 #endif
25264   case EIO:
25265   case EBADF:
25266   case EINVAL:
25267   case ENOTCONN:
25268   case ENODEV:
25269   case ENXIO:
25270   case ENOENT:
25271 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25272   case ESTALE:
25273 #endif
25274   case ENOSYS:
25275     /* these should force the client to close the file and reconnect */
25276 
25277   default:
25278     return sqliteIOErr;
25279   }
25280 }
25281 
25282 
25283 
25284 /******************************************************************************
25285 ****************** Begin Unique File ID Utility Used By VxWorks ***************
25286 **
25287 ** On most versions of unix, we can get a unique ID for a file by concatenating
25288 ** the device number and the inode number.  But this does not work on VxWorks.
25289 ** On VxWorks, a unique file id must be based on the canonical filename.
25290 **
25291 ** A pointer to an instance of the following structure can be used as a
25292 ** unique file ID in VxWorks.  Each instance of this structure contains
25293 ** a copy of the canonical filename.  There is also a reference count.
25294 ** The structure is reclaimed when the number of pointers to it drops to
25295 ** zero.
25296 **
25297 ** There are never very many files open at one time and lookups are not
25298 ** a performance-critical path, so it is sufficient to put these
25299 ** structures on a linked list.
25300 */
25301 struct vxworksFileId {
25302   struct vxworksFileId *pNext;  /* Next in a list of them all */
25303   int nRef;                     /* Number of references to this one */
25304   int nName;                    /* Length of the zCanonicalName[] string */
25305   char *zCanonicalName;         /* Canonical filename */
25306 };
25307 
25308 #if OS_VXWORKS
25309 /*
25310 ** All unique filenames are held on a linked list headed by this
25311 ** variable:
25312 */
25313 static struct vxworksFileId *vxworksFileList = 0;
25314 
25315 /*
25316 ** Simplify a filename into its canonical form
25317 ** by making the following changes:
25318 **
25319 **  * removing any trailing and duplicate /
25320 **  * convert /./ into just /
25321 **  * convert /A/../ where A is any simple name into just /
25322 **
25323 ** Changes are made in-place.  Return the new name length.
25324 **
25325 ** The original filename is in z[0..n-1].  Return the number of
25326 ** characters in the simplified name.
25327 */
25328 static int vxworksSimplifyName(char *z, int n){
25329   int i, j;
25330   while( n>1 && z[n-1]=='/' ){ n--; }
25331   for(i=j=0; i<n; i++){
25332     if( z[i]=='/' ){
25333       if( z[i+1]=='/' ) continue;
25334       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25335         i += 1;
25336         continue;
25337       }
25338       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25339         while( j>0 && z[j-1]!='/' ){ j--; }
25340         if( j>0 ){ j--; }
25341         i += 2;
25342         continue;
25343       }
25344     }
25345     z[j++] = z[i];
25346   }
25347   z[j] = 0;
25348   return j;
25349 }
25350 
25351 /*
25352 ** Find a unique file ID for the given absolute pathname.  Return
25353 ** a pointer to the vxworksFileId object.  This pointer is the unique
25354 ** file ID.
25355 **
25356 ** The nRef field of the vxworksFileId object is incremented before
25357 ** the object is returned.  A new vxworksFileId object is created
25358 ** and added to the global list if necessary.
25359 **
25360 ** If a memory allocation error occurs, return NULL.
25361 */
25362 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25363   struct vxworksFileId *pNew;         /* search key and new file ID */
25364   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25365   int n;                              /* Length of zAbsoluteName string */
25366 
25367   assert( zAbsoluteName[0]=='/' );
25368   n = (int)strlen(zAbsoluteName);
25369   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25370   if( pNew==0 ) return 0;
25371   pNew->zCanonicalName = (char*)&pNew[1];
25372   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25373   n = vxworksSimplifyName(pNew->zCanonicalName, n);
25374 
25375   /* Search for an existing entry that matching the canonical name.
25376   ** If found, increment the reference count and return a pointer to
25377   ** the existing file ID.
25378   */
25379   unixEnterMutex();
25380   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25381     if( pCandidate->nName==n
25382      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25383     ){
25384        sqlite3_free(pNew);
25385        pCandidate->nRef++;
25386        unixLeaveMutex();
25387        return pCandidate;
25388     }
25389   }
25390 
25391   /* No match was found.  We will make a new file ID */
25392   pNew->nRef = 1;
25393   pNew->nName = n;
25394   pNew->pNext = vxworksFileList;
25395   vxworksFileList = pNew;
25396   unixLeaveMutex();
25397   return pNew;
25398 }
25399 
25400 /*
25401 ** Decrement the reference count on a vxworksFileId object.  Free
25402 ** the object when the reference count reaches zero.
25403 */
25404 static void vxworksReleaseFileId(struct vxworksFileId *pId){
25405   unixEnterMutex();
25406   assert( pId->nRef>0 );
25407   pId->nRef--;
25408   if( pId->nRef==0 ){
25409     struct vxworksFileId **pp;
25410     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25411     assert( *pp==pId );
25412     *pp = pId->pNext;
25413     sqlite3_free(pId);
25414   }
25415   unixLeaveMutex();
25416 }
25417 #endif /* OS_VXWORKS */
25418 /*************** End of Unique File ID Utility Used By VxWorks ****************
25419 ******************************************************************************/
25420 
25421 
25422 /******************************************************************************
25423 *************************** Posix Advisory Locking ****************************
25424 **
25425 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
25426 ** section 6.5.2.2 lines 483 through 490 specify that when a process
25427 ** sets or clears a lock, that operation overrides any prior locks set
25428 ** by the same process.  It does not explicitly say so, but this implies
25429 ** that it overrides locks set by the same process using a different
25430 ** file descriptor.  Consider this test case:
25431 **
25432 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25433 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25434 **
25435 ** Suppose ./file1 and ./file2 are really the same file (because
25436 ** one is a hard or symbolic link to the other) then if you set
25437 ** an exclusive lock on fd1, then try to get an exclusive lock
25438 ** on fd2, it works.  I would have expected the second lock to
25439 ** fail since there was already a lock on the file due to fd1.
25440 ** But not so.  Since both locks came from the same process, the
25441 ** second overrides the first, even though they were on different
25442 ** file descriptors opened on different file names.
25443 **
25444 ** This means that we cannot use POSIX locks to synchronize file access
25445 ** among competing threads of the same process.  POSIX locks will work fine
25446 ** to synchronize access for threads in separate processes, but not
25447 ** threads within the same process.
25448 **
25449 ** To work around the problem, SQLite has to manage file locks internally
25450 ** on its own.  Whenever a new database is opened, we have to find the
25451 ** specific inode of the database file (the inode is determined by the
25452 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
25453 ** and check for locks already existing on that inode.  When locks are
25454 ** created or removed, we have to look at our own internal record of the
25455 ** locks to see if another thread has previously set a lock on that same
25456 ** inode.
25457 **
25458 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25459 ** For VxWorks, we have to use the alternative unique ID system based on
25460 ** canonical filename and implemented in the previous division.)
25461 **
25462 ** The sqlite3_file structure for POSIX is no longer just an integer file
25463 ** descriptor.  It is now a structure that holds the integer file
25464 ** descriptor and a pointer to a structure that describes the internal
25465 ** locks on the corresponding inode.  There is one locking structure
25466 ** per inode, so if the same inode is opened twice, both unixFile structures
25467 ** point to the same locking structure.  The locking structure keeps
25468 ** a reference count (so we will know when to delete it) and a "cnt"
25469 ** field that tells us its internal lock status.  cnt==0 means the
25470 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25471 ** cnt>0 means there are cnt shared locks on the file.
25472 **
25473 ** Any attempt to lock or unlock a file first checks the locking
25474 ** structure.  The fcntl() system call is only invoked to set a
25475 ** POSIX lock if the internal lock structure transitions between
25476 ** a locked and an unlocked state.
25477 **
25478 ** But wait:  there are yet more problems with POSIX advisory locks.
25479 **
25480 ** If you close a file descriptor that points to a file that has locks,
25481 ** all locks on that file that are owned by the current process are
25482 ** released.  To work around this problem, each unixInodeInfo object
25483 ** maintains a count of the number of pending locks on tha inode.
25484 ** When an attempt is made to close an unixFile, if there are
25485 ** other unixFile open on the same inode that are holding locks, the call
25486 ** to close() the file descriptor is deferred until all of the locks clear.
25487 ** The unixInodeInfo structure keeps a list of file descriptors that need to
25488 ** be closed and that list is walked (and cleared) when the last lock
25489 ** clears.
25490 **
25491 ** Yet another problem:  LinuxThreads do not play well with posix locks.
25492 **
25493 ** Many older versions of linux use the LinuxThreads library which is
25494 ** not posix compliant.  Under LinuxThreads, a lock created by thread
25495 ** A cannot be modified or overridden by a different thread B.
25496 ** Only thread A can modify the lock.  Locking behavior is correct
25497 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
25498 ** on linux - with NPTL a lock created by thread A can override locks
25499 ** in thread B.  But there is no way to know at compile-time which
25500 ** threading library is being used.  So there is no way to know at
25501 ** compile-time whether or not thread A can override locks on thread B.
25502 ** One has to do a run-time check to discover the behavior of the
25503 ** current process.
25504 **
25505 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
25506 ** was dropped beginning with version 3.7.0.  SQLite will still work with
25507 ** LinuxThreads provided that (1) there is no more than one connection
25508 ** per database file in the same process and (2) database connections
25509 ** do not move across threads.
25510 */
25511 
25512 /*
25513 ** An instance of the following structure serves as the key used
25514 ** to locate a particular unixInodeInfo object.
25515 */
25516 struct unixFileId {
25517   dev_t dev;                  /* Device number */
25518 #if OS_VXWORKS
25519   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
25520 #else
25521   ino_t ino;                  /* Inode number */
25522 #endif
25523 };
25524 
25525 /*
25526 ** An instance of the following structure is allocated for each open
25527 ** inode.  Or, on LinuxThreads, there is one of these structures for
25528 ** each inode opened by each thread.
25529 **
25530 ** A single inode can have multiple file descriptors, so each unixFile
25531 ** structure contains a pointer to an instance of this object and this
25532 ** object keeps a count of the number of unixFile pointing to it.
25533 */
25534 struct unixInodeInfo {
25535   struct unixFileId fileId;       /* The lookup key */
25536   int nShared;                    /* Number of SHARED locks held */
25537   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
25538   unsigned char bProcessLock;     /* An exclusive process lock is held */
25539   int nRef;                       /* Number of pointers to this structure */
25540   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
25541   int nLock;                      /* Number of outstanding file locks */
25542   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
25543   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
25544   unixInodeInfo *pPrev;           /*    .... doubly linked */
25545 #if SQLITE_ENABLE_LOCKING_STYLE
25546   unsigned long long sharedByte;  /* for AFP simulated shared lock */
25547 #endif
25548 #if OS_VXWORKS
25549   sem_t *pSem;                    /* Named POSIX semaphore */
25550   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
25551 #endif
25552 };
25553 
25554 /*
25555 ** A lists of all unixInodeInfo objects.
25556 */
25557 static unixInodeInfo *inodeList = 0;
25558 
25559 /*
25560 **
25561 ** This function - unixLogError_x(), is only ever called via the macro
25562 ** unixLogError().
25563 **
25564 ** It is invoked after an error occurs in an OS function and errno has been
25565 ** set. It logs a message using sqlite3_log() containing the current value of
25566 ** errno and, if possible, the human-readable equivalent from strerror() or
25567 ** strerror_r().
25568 **
25569 ** The first argument passed to the macro should be the error code that
25570 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
25571 ** The two subsequent arguments should be the name of the OS function that
25572 ** failed (e.g. "unlink", "open") and the the associated file-system path,
25573 ** if any.
25574 */
25575 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
25576 static int unixLogErrorAtLine(
25577   int errcode,                    /* SQLite error code */
25578   const char *zFunc,              /* Name of OS function that failed */
25579   const char *zPath,              /* File path associated with error */
25580   int iLine                       /* Source line number where error occurred */
25581 ){
25582   char *zErr;                     /* Message from strerror() or equivalent */
25583   int iErrno = errno;             /* Saved syscall error number */
25584 
25585   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
25586   ** the strerror() function to obtain the human-readable error message
25587   ** equivalent to errno. Otherwise, use strerror_r().
25588   */
25589 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
25590   char aErr[80];
25591   memset(aErr, 0, sizeof(aErr));
25592   zErr = aErr;
25593 
25594   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
25595   ** assume that the system provides the the GNU version of strerror_r() that
25596   ** returns a pointer to a buffer containing the error message. That pointer
25597   ** may point to aErr[], or it may point to some static storage somewhere.
25598   ** Otherwise, assume that the system provides the POSIX version of
25599   ** strerror_r(), which always writes an error message into aErr[].
25600   **
25601   ** If the code incorrectly assumes that it is the POSIX version that is
25602   ** available, the error message will often be an empty string. Not a
25603   ** huge problem. Incorrectly concluding that the GNU version is available
25604   ** could lead to a segfault though.
25605   */
25606 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
25607   zErr =
25608 # endif
25609   strerror_r(iErrno, aErr, sizeof(aErr)-1);
25610 
25611 #elif SQLITE_THREADSAFE
25612   /* This is a threadsafe build, but strerror_r() is not available. */
25613   zErr = "";
25614 #else
25615   /* Non-threadsafe build, use strerror(). */
25616   zErr = strerror(iErrno);
25617 #endif
25618 
25619   assert( errcode!=SQLITE_OK );
25620   if( zPath==0 ) zPath = "";
25621   sqlite3_log(errcode,
25622       "os_unix.c:%d: (%d) %s(%s) - %s",
25623       iLine, iErrno, zFunc, zPath, zErr
25624   );
25625 
25626   return errcode;
25627 }
25628 
25629 /*
25630 ** Close a file descriptor.
25631 **
25632 ** We assume that close() almost always works, since it is only in a
25633 ** very sick application or on a very sick platform that it might fail.
25634 ** If it does fail, simply leak the file descriptor, but do log the
25635 ** error.
25636 **
25637 ** Note that it is not safe to retry close() after EINTR since the
25638 ** file descriptor might have already been reused by another thread.
25639 ** So we don't even try to recover from an EINTR.  Just log the error
25640 ** and move on.
25641 */
25642 static void robust_close(unixFile *pFile, int h, int lineno){
25643   if( osClose(h) ){
25644     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
25645                        pFile ? pFile->zPath : 0, lineno);
25646   }
25647 }
25648 
25649 /*
25650 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
25651 */
25652 static void closePendingFds(unixFile *pFile){
25653   unixInodeInfo *pInode = pFile->pInode;
25654   UnixUnusedFd *p;
25655   UnixUnusedFd *pNext;
25656   for(p=pInode->pUnused; p; p=pNext){
25657     pNext = p->pNext;
25658     robust_close(pFile, p->fd, __LINE__);
25659     sqlite3_free(p);
25660   }
25661   pInode->pUnused = 0;
25662 }
25663 
25664 /*
25665 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
25666 **
25667 ** The mutex entered using the unixEnterMutex() function must be held
25668 ** when this function is called.
25669 */
25670 static void releaseInodeInfo(unixFile *pFile){
25671   unixInodeInfo *pInode = pFile->pInode;
25672   assert( unixMutexHeld() );
25673   if( ALWAYS(pInode) ){
25674     pInode->nRef--;
25675     if( pInode->nRef==0 ){
25676       assert( pInode->pShmNode==0 );
25677       closePendingFds(pFile);
25678       if( pInode->pPrev ){
25679         assert( pInode->pPrev->pNext==pInode );
25680         pInode->pPrev->pNext = pInode->pNext;
25681       }else{
25682         assert( inodeList==pInode );
25683         inodeList = pInode->pNext;
25684       }
25685       if( pInode->pNext ){
25686         assert( pInode->pNext->pPrev==pInode );
25687         pInode->pNext->pPrev = pInode->pPrev;
25688       }
25689       sqlite3_free(pInode);
25690     }
25691   }
25692 }
25693 
25694 /*
25695 ** Given a file descriptor, locate the unixInodeInfo object that
25696 ** describes that file descriptor.  Create a new one if necessary.  The
25697 ** return value might be uninitialized if an error occurs.
25698 **
25699 ** The mutex entered using the unixEnterMutex() function must be held
25700 ** when this function is called.
25701 **
25702 ** Return an appropriate error code.
25703 */
25704 static int findInodeInfo(
25705   unixFile *pFile,               /* Unix file with file desc used in the key */
25706   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
25707 ){
25708   int rc;                        /* System call return code */
25709   int fd;                        /* The file descriptor for pFile */
25710   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
25711   struct stat statbuf;           /* Low-level file information */
25712   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
25713 
25714   assert( unixMutexHeld() );
25715 
25716   /* Get low-level information about the file that we can used to
25717   ** create a unique name for the file.
25718   */
25719   fd = pFile->h;
25720   rc = osFstat(fd, &statbuf);
25721   if( rc!=0 ){
25722     pFile->lastErrno = errno;
25723 #ifdef EOVERFLOW
25724     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
25725 #endif
25726     return SQLITE_IOERR;
25727   }
25728 
25729 #ifdef __APPLE__
25730   /* On OS X on an msdos filesystem, the inode number is reported
25731   ** incorrectly for zero-size files.  See ticket #3260.  To work
25732   ** around this problem (we consider it a bug in OS X, not SQLite)
25733   ** we always increase the file size to 1 by writing a single byte
25734   ** prior to accessing the inode number.  The one byte written is
25735   ** an ASCII 'S' character which also happens to be the first byte
25736   ** in the header of every SQLite database.  In this way, if there
25737   ** is a race condition such that another thread has already populated
25738   ** the first page of the database, no damage is done.
25739   */
25740   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
25741     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
25742     if( rc!=1 ){
25743       pFile->lastErrno = errno;
25744       return SQLITE_IOERR;
25745     }
25746     rc = osFstat(fd, &statbuf);
25747     if( rc!=0 ){
25748       pFile->lastErrno = errno;
25749       return SQLITE_IOERR;
25750     }
25751   }
25752 #endif
25753 
25754   memset(&fileId, 0, sizeof(fileId));
25755   fileId.dev = statbuf.st_dev;
25756 #if OS_VXWORKS
25757   fileId.pId = pFile->pId;
25758 #else
25759   fileId.ino = statbuf.st_ino;
25760 #endif
25761   pInode = inodeList;
25762   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
25763     pInode = pInode->pNext;
25764   }
25765   if( pInode==0 ){
25766     pInode = sqlite3_malloc( sizeof(*pInode) );
25767     if( pInode==0 ){
25768       return SQLITE_NOMEM;
25769     }
25770     memset(pInode, 0, sizeof(*pInode));
25771     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
25772     pInode->nRef = 1;
25773     pInode->pNext = inodeList;
25774     pInode->pPrev = 0;
25775     if( inodeList ) inodeList->pPrev = pInode;
25776     inodeList = pInode;
25777   }else{
25778     pInode->nRef++;
25779   }
25780   *ppInode = pInode;
25781   return SQLITE_OK;
25782 }
25783 
25784 
25785 /*
25786 ** This routine checks if there is a RESERVED lock held on the specified
25787 ** file by this or any other process. If such a lock is held, set *pResOut
25788 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25789 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25790 */
25791 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
25792   int rc = SQLITE_OK;
25793   int reserved = 0;
25794   unixFile *pFile = (unixFile*)id;
25795 
25796   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25797 
25798   assert( pFile );
25799   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25800 
25801   /* Check if a thread in this process holds such a lock */
25802   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25803     reserved = 1;
25804   }
25805 
25806   /* Otherwise see if some other process holds it.
25807   */
25808 #ifndef __DJGPP__
25809   if( !reserved && !pFile->pInode->bProcessLock ){
25810     struct flock lock;
25811     lock.l_whence = SEEK_SET;
25812     lock.l_start = RESERVED_BYTE;
25813     lock.l_len = 1;
25814     lock.l_type = F_WRLCK;
25815     if( osFcntl(pFile->h, F_GETLK, &lock) ){
25816       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
25817       pFile->lastErrno = errno;
25818     } else if( lock.l_type!=F_UNLCK ){
25819       reserved = 1;
25820     }
25821   }
25822 #endif
25823 
25824   unixLeaveMutex();
25825   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
25826 
25827   *pResOut = reserved;
25828   return rc;
25829 }
25830 
25831 /*
25832 ** Attempt to set a system-lock on the file pFile.  The lock is
25833 ** described by pLock.
25834 **
25835 ** If the pFile was opened read/write from unix-excl, then the only lock
25836 ** ever obtained is an exclusive lock, and it is obtained exactly once
25837 ** the first time any lock is attempted.  All subsequent system locking
25838 ** operations become no-ops.  Locking operations still happen internally,
25839 ** in order to coordinate access between separate database connections
25840 ** within this process, but all of that is handled in memory and the
25841 ** operating system does not participate.
25842 **
25843 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
25844 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
25845 ** and is read-only.
25846 **
25847 ** Zero is returned if the call completes successfully, or -1 if a call
25848 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
25849 */
25850 static int unixFileLock(unixFile *pFile, struct flock *pLock){
25851   int rc;
25852   unixInodeInfo *pInode = pFile->pInode;
25853   assert( unixMutexHeld() );
25854   assert( pInode!=0 );
25855   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
25856    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
25857   ){
25858     if( pInode->bProcessLock==0 ){
25859       struct flock lock;
25860       assert( pInode->nLock==0 );
25861       lock.l_whence = SEEK_SET;
25862       lock.l_start = SHARED_FIRST;
25863       lock.l_len = SHARED_SIZE;
25864       lock.l_type = F_WRLCK;
25865       rc = osFcntl(pFile->h, F_SETLK, &lock);
25866       if( rc<0 ) return rc;
25867       pInode->bProcessLock = 1;
25868       pInode->nLock++;
25869     }else{
25870       rc = 0;
25871     }
25872   }else{
25873     rc = osFcntl(pFile->h, F_SETLK, pLock);
25874   }
25875   return rc;
25876 }
25877 
25878 /*
25879 ** Lock the file with the lock specified by parameter eFileLock - one
25880 ** of the following:
25881 **
25882 **     (1) SHARED_LOCK
25883 **     (2) RESERVED_LOCK
25884 **     (3) PENDING_LOCK
25885 **     (4) EXCLUSIVE_LOCK
25886 **
25887 ** Sometimes when requesting one lock state, additional lock states
25888 ** are inserted in between.  The locking might fail on one of the later
25889 ** transitions leaving the lock state different from what it started but
25890 ** still short of its goal.  The following chart shows the allowed
25891 ** transitions and the inserted intermediate states:
25892 **
25893 **    UNLOCKED -> SHARED
25894 **    SHARED -> RESERVED
25895 **    SHARED -> (PENDING) -> EXCLUSIVE
25896 **    RESERVED -> (PENDING) -> EXCLUSIVE
25897 **    PENDING -> EXCLUSIVE
25898 **
25899 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25900 ** routine to lower a locking level.
25901 */
25902 static int unixLock(sqlite3_file *id, int eFileLock){
25903   /* The following describes the implementation of the various locks and
25904   ** lock transitions in terms of the POSIX advisory shared and exclusive
25905   ** lock primitives (called read-locks and write-locks below, to avoid
25906   ** confusion with SQLite lock names). The algorithms are complicated
25907   ** slightly in order to be compatible with windows systems simultaneously
25908   ** accessing the same database file, in case that is ever required.
25909   **
25910   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
25911   ** byte', each single bytes at well known offsets, and the 'shared byte
25912   ** range', a range of 510 bytes at a well known offset.
25913   **
25914   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
25915   ** byte'.  If this is successful, a random byte from the 'shared byte
25916   ** range' is read-locked and the lock on the 'pending byte' released.
25917   **
25918   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
25919   ** A RESERVED lock is implemented by grabbing a write-lock on the
25920   ** 'reserved byte'.
25921   **
25922   ** A process may only obtain a PENDING lock after it has obtained a
25923   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
25924   ** on the 'pending byte'. This ensures that no new SHARED locks can be
25925   ** obtained, but existing SHARED locks are allowed to persist. A process
25926   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
25927   ** This property is used by the algorithm for rolling back a journal file
25928   ** after a crash.
25929   **
25930   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
25931   ** implemented by obtaining a write-lock on the entire 'shared byte
25932   ** range'. Since all other locks require a read-lock on one of the bytes
25933   ** within this range, this ensures that no other locks are held on the
25934   ** database.
25935   **
25936   ** The reason a single byte cannot be used instead of the 'shared byte
25937   ** range' is that some versions of windows do not support read-locks. By
25938   ** locking a random byte from a range, concurrent SHARED locks may exist
25939   ** even if the locking primitive used is always a write-lock.
25940   */
25941   int rc = SQLITE_OK;
25942   unixFile *pFile = (unixFile*)id;
25943   unixInodeInfo *pInode = pFile->pInode;
25944   struct flock lock;
25945   int tErrno = 0;
25946 
25947   assert( pFile );
25948   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
25949       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25950       azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25951 
25952   /* If there is already a lock of this type or more restrictive on the
25953   ** unixFile, do nothing. Don't use the end_lock: exit path, as
25954   ** unixEnterMutex() hasn't been called yet.
25955   */
25956   if( pFile->eFileLock>=eFileLock ){
25957     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
25958             azFileLock(eFileLock)));
25959     return SQLITE_OK;
25960   }
25961 
25962   /* Make sure the locking sequence is correct.
25963   **  (1) We never move from unlocked to anything higher than shared lock.
25964   **  (2) SQLite never explicitly requests a pendig lock.
25965   **  (3) A shared lock is always held when a reserve lock is requested.
25966   */
25967   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25968   assert( eFileLock!=PENDING_LOCK );
25969   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25970 
25971   /* This mutex is needed because pFile->pInode is shared across threads
25972   */
25973   unixEnterMutex();
25974   pInode = pFile->pInode;
25975 
25976   /* If some thread using this PID has a lock via a different unixFile*
25977   ** handle that precludes the requested lock, return BUSY.
25978   */
25979   if( (pFile->eFileLock!=pInode->eFileLock &&
25980           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25981   ){
25982     rc = SQLITE_BUSY;
25983     goto end_lock;
25984   }
25985 
25986   /* If a SHARED lock is requested, and some thread using this PID already
25987   ** has a SHARED or RESERVED lock, then increment reference counts and
25988   ** return SQLITE_OK.
25989   */
25990   if( eFileLock==SHARED_LOCK &&
25991       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25992     assert( eFileLock==SHARED_LOCK );
25993     assert( pFile->eFileLock==0 );
25994     assert( pInode->nShared>0 );
25995     pFile->eFileLock = SHARED_LOCK;
25996     pInode->nShared++;
25997     pInode->nLock++;
25998     goto end_lock;
25999   }
26000 
26001 
26002   /* A PENDING lock is needed before acquiring a SHARED lock and before
26003   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26004   ** be released.
26005   */
26006   lock.l_len = 1L;
26007   lock.l_whence = SEEK_SET;
26008   if( eFileLock==SHARED_LOCK
26009       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26010   ){
26011     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26012     lock.l_start = PENDING_BYTE;
26013     if( unixFileLock(pFile, &lock) ){
26014       tErrno = errno;
26015       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26016       if( rc!=SQLITE_BUSY ){
26017         pFile->lastErrno = tErrno;
26018       }
26019       goto end_lock;
26020     }
26021   }
26022 
26023 
26024   /* If control gets to this point, then actually go ahead and make
26025   ** operating system calls for the specified lock.
26026   */
26027   if( eFileLock==SHARED_LOCK ){
26028     assert( pInode->nShared==0 );
26029     assert( pInode->eFileLock==0 );
26030     assert( rc==SQLITE_OK );
26031 
26032     /* Now get the read-lock */
26033     lock.l_start = SHARED_FIRST;
26034     lock.l_len = SHARED_SIZE;
26035     if( unixFileLock(pFile, &lock) ){
26036       tErrno = errno;
26037       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26038     }
26039 
26040     /* Drop the temporary PENDING lock */
26041     lock.l_start = PENDING_BYTE;
26042     lock.l_len = 1L;
26043     lock.l_type = F_UNLCK;
26044     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26045       /* This could happen with a network mount */
26046       tErrno = errno;
26047       rc = SQLITE_IOERR_UNLOCK;
26048     }
26049 
26050     if( rc ){
26051       if( rc!=SQLITE_BUSY ){
26052         pFile->lastErrno = tErrno;
26053       }
26054       goto end_lock;
26055     }else{
26056       pFile->eFileLock = SHARED_LOCK;
26057       pInode->nLock++;
26058       pInode->nShared = 1;
26059     }
26060   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26061     /* We are trying for an exclusive lock but another thread in this
26062     ** same process is still holding a shared lock. */
26063     rc = SQLITE_BUSY;
26064   }else{
26065     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26066     ** assumed that there is a SHARED or greater lock on the file
26067     ** already.
26068     */
26069     assert( 0!=pFile->eFileLock );
26070     lock.l_type = F_WRLCK;
26071 
26072     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26073     if( eFileLock==RESERVED_LOCK ){
26074       lock.l_start = RESERVED_BYTE;
26075       lock.l_len = 1L;
26076     }else{
26077       lock.l_start = SHARED_FIRST;
26078       lock.l_len = SHARED_SIZE;
26079     }
26080 
26081     if( unixFileLock(pFile, &lock) ){
26082       tErrno = errno;
26083       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26084       if( rc!=SQLITE_BUSY ){
26085         pFile->lastErrno = tErrno;
26086       }
26087     }
26088   }
26089 
26090 
26091 #ifndef NDEBUG
26092   /* Set up the transaction-counter change checking flags when
26093   ** transitioning from a SHARED to a RESERVED lock.  The change
26094   ** from SHARED to RESERVED marks the beginning of a normal
26095   ** write operation (not a hot journal rollback).
26096   */
26097   if( rc==SQLITE_OK
26098    && pFile->eFileLock<=SHARED_LOCK
26099    && eFileLock==RESERVED_LOCK
26100   ){
26101     pFile->transCntrChng = 0;
26102     pFile->dbUpdate = 0;
26103     pFile->inNormalWrite = 1;
26104   }
26105 #endif
26106 
26107 
26108   if( rc==SQLITE_OK ){
26109     pFile->eFileLock = eFileLock;
26110     pInode->eFileLock = eFileLock;
26111   }else if( eFileLock==EXCLUSIVE_LOCK ){
26112     pFile->eFileLock = PENDING_LOCK;
26113     pInode->eFileLock = PENDING_LOCK;
26114   }
26115 
26116 end_lock:
26117   unixLeaveMutex();
26118   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26119       rc==SQLITE_OK ? "ok" : "failed"));
26120   return rc;
26121 }
26122 
26123 /*
26124 ** Add the file descriptor used by file handle pFile to the corresponding
26125 ** pUnused list.
26126 */
26127 static void setPendingFd(unixFile *pFile){
26128   unixInodeInfo *pInode = pFile->pInode;
26129   UnixUnusedFd *p = pFile->pUnused;
26130   p->pNext = pInode->pUnused;
26131   pInode->pUnused = p;
26132   pFile->h = -1;
26133   pFile->pUnused = 0;
26134 }
26135 
26136 /*
26137 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26138 ** must be either NO_LOCK or SHARED_LOCK.
26139 **
26140 ** If the locking level of the file descriptor is already at or below
26141 ** the requested locking level, this routine is a no-op.
26142 **
26143 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26144 ** the byte range is divided into 2 parts and the first part is unlocked then
26145 ** set to a read lock, then the other part is simply unlocked.  This works
26146 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26147 ** remove the write lock on a region when a read lock is set.
26148 */
26149 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26150   unixFile *pFile = (unixFile*)id;
26151   unixInodeInfo *pInode;
26152   struct flock lock;
26153   int rc = SQLITE_OK;
26154   int h;
26155 
26156   assert( pFile );
26157   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26158       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26159       getpid()));
26160 
26161   assert( eFileLock<=SHARED_LOCK );
26162   if( pFile->eFileLock<=eFileLock ){
26163     return SQLITE_OK;
26164   }
26165   unixEnterMutex();
26166   h = pFile->h;
26167   pInode = pFile->pInode;
26168   assert( pInode->nShared!=0 );
26169   if( pFile->eFileLock>SHARED_LOCK ){
26170     assert( pInode->eFileLock==pFile->eFileLock );
26171     SimulateIOErrorBenign(1);
26172     SimulateIOError( h=(-1) )
26173     SimulateIOErrorBenign(0);
26174 
26175 #ifndef NDEBUG
26176     /* When reducing a lock such that other processes can start
26177     ** reading the database file again, make sure that the
26178     ** transaction counter was updated if any part of the database
26179     ** file changed.  If the transaction counter is not updated,
26180     ** other connections to the same file might not realize that
26181     ** the file has changed and hence might not know to flush their
26182     ** cache.  The use of a stale cache can lead to database corruption.
26183     */
26184 #if 0
26185     assert( pFile->inNormalWrite==0
26186          || pFile->dbUpdate==0
26187          || pFile->transCntrChng==1 );
26188 #endif
26189     pFile->inNormalWrite = 0;
26190 #endif
26191 
26192     /* downgrading to a shared lock on NFS involves clearing the write lock
26193     ** before establishing the readlock - to avoid a race condition we downgrade
26194     ** the lock in 2 blocks, so that part of the range will be covered by a
26195     ** write lock until the rest is covered by a read lock:
26196     **  1:   [WWWWW]
26197     **  2:   [....W]
26198     **  3:   [RRRRW]
26199     **  4:   [RRRR.]
26200     */
26201     if( eFileLock==SHARED_LOCK ){
26202 
26203 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26204       (void)handleNFSUnlock;
26205       assert( handleNFSUnlock==0 );
26206 #endif
26207 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26208       if( handleNFSUnlock ){
26209         int tErrno;               /* Error code from system call errors */
26210         off_t divSize = SHARED_SIZE - 1;
26211 
26212         lock.l_type = F_UNLCK;
26213         lock.l_whence = SEEK_SET;
26214         lock.l_start = SHARED_FIRST;
26215         lock.l_len = divSize;
26216         if( unixFileLock(pFile, &lock)==(-1) ){
26217           tErrno = errno;
26218           rc = SQLITE_IOERR_UNLOCK;
26219           if( IS_LOCK_ERROR(rc) ){
26220             pFile->lastErrno = tErrno;
26221           }
26222           goto end_unlock;
26223         }
26224         lock.l_type = F_RDLCK;
26225         lock.l_whence = SEEK_SET;
26226         lock.l_start = SHARED_FIRST;
26227         lock.l_len = divSize;
26228         if( unixFileLock(pFile, &lock)==(-1) ){
26229           tErrno = errno;
26230           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26231           if( IS_LOCK_ERROR(rc) ){
26232             pFile->lastErrno = tErrno;
26233           }
26234           goto end_unlock;
26235         }
26236         lock.l_type = F_UNLCK;
26237         lock.l_whence = SEEK_SET;
26238         lock.l_start = SHARED_FIRST+divSize;
26239         lock.l_len = SHARED_SIZE-divSize;
26240         if( unixFileLock(pFile, &lock)==(-1) ){
26241           tErrno = errno;
26242           rc = SQLITE_IOERR_UNLOCK;
26243           if( IS_LOCK_ERROR(rc) ){
26244             pFile->lastErrno = tErrno;
26245           }
26246           goto end_unlock;
26247         }
26248       }else
26249 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26250       {
26251         lock.l_type = F_RDLCK;
26252         lock.l_whence = SEEK_SET;
26253         lock.l_start = SHARED_FIRST;
26254         lock.l_len = SHARED_SIZE;
26255         if( unixFileLock(pFile, &lock) ){
26256           /* In theory, the call to unixFileLock() cannot fail because another
26257           ** process is holding an incompatible lock. If it does, this
26258           ** indicates that the other process is not following the locking
26259           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26260           ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26261           ** an assert to fail). */
26262           rc = SQLITE_IOERR_RDLOCK;
26263           pFile->lastErrno = errno;
26264           goto end_unlock;
26265         }
26266       }
26267     }
26268     lock.l_type = F_UNLCK;
26269     lock.l_whence = SEEK_SET;
26270     lock.l_start = PENDING_BYTE;
26271     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26272     if( unixFileLock(pFile, &lock)==0 ){
26273       pInode->eFileLock = SHARED_LOCK;
26274     }else{
26275       rc = SQLITE_IOERR_UNLOCK;
26276       pFile->lastErrno = errno;
26277       goto end_unlock;
26278     }
26279   }
26280   if( eFileLock==NO_LOCK ){
26281     /* Decrement the shared lock counter.  Release the lock using an
26282     ** OS call only when all threads in this same process have released
26283     ** the lock.
26284     */
26285     pInode->nShared--;
26286     if( pInode->nShared==0 ){
26287       lock.l_type = F_UNLCK;
26288       lock.l_whence = SEEK_SET;
26289       lock.l_start = lock.l_len = 0L;
26290       SimulateIOErrorBenign(1);
26291       SimulateIOError( h=(-1) )
26292       SimulateIOErrorBenign(0);
26293       if( unixFileLock(pFile, &lock)==0 ){
26294         pInode->eFileLock = NO_LOCK;
26295       }else{
26296         rc = SQLITE_IOERR_UNLOCK;
26297 	pFile->lastErrno = errno;
26298         pInode->eFileLock = NO_LOCK;
26299         pFile->eFileLock = NO_LOCK;
26300       }
26301     }
26302 
26303     /* Decrement the count of locks against this same file.  When the
26304     ** count reaches zero, close any other file descriptors whose close
26305     ** was deferred because of outstanding locks.
26306     */
26307     pInode->nLock--;
26308     assert( pInode->nLock>=0 );
26309     if( pInode->nLock==0 ){
26310       closePendingFds(pFile);
26311     }
26312   }
26313 
26314 end_unlock:
26315   unixLeaveMutex();
26316   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26317   return rc;
26318 }
26319 
26320 /*
26321 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26322 ** must be either NO_LOCK or SHARED_LOCK.
26323 **
26324 ** If the locking level of the file descriptor is already at or below
26325 ** the requested locking level, this routine is a no-op.
26326 */
26327 static int unixUnlock(sqlite3_file *id, int eFileLock){
26328   return posixUnlock(id, eFileLock, 0);
26329 }
26330 
26331 /*
26332 ** This function performs the parts of the "close file" operation
26333 ** common to all locking schemes. It closes the directory and file
26334 ** handles, if they are valid, and sets all fields of the unixFile
26335 ** structure to 0.
26336 **
26337 ** It is *not* necessary to hold the mutex when this routine is called,
26338 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
26339 ** vxworksReleaseFileId() routine.
26340 */
26341 static int closeUnixFile(sqlite3_file *id){
26342   unixFile *pFile = (unixFile*)id;
26343   if( pFile->h>=0 ){
26344     robust_close(pFile, pFile->h, __LINE__);
26345     pFile->h = -1;
26346   }
26347 #if OS_VXWORKS
26348   if( pFile->pId ){
26349     if( pFile->isDelete ){
26350       osUnlink(pFile->pId->zCanonicalName);
26351     }
26352     vxworksReleaseFileId(pFile->pId);
26353     pFile->pId = 0;
26354   }
26355 #endif
26356   OSTRACE(("CLOSE   %-3d\n", pFile->h));
26357   OpenCounter(-1);
26358   sqlite3_free(pFile->pUnused);
26359   memset(pFile, 0, sizeof(unixFile));
26360   return SQLITE_OK;
26361 }
26362 
26363 /*
26364 ** Close a file.
26365 */
26366 static int unixClose(sqlite3_file *id){
26367   int rc = SQLITE_OK;
26368   unixFile *pFile = (unixFile *)id;
26369   unixUnlock(id, NO_LOCK);
26370   unixEnterMutex();
26371 
26372   /* unixFile.pInode is always valid here. Otherwise, a different close
26373   ** routine (e.g. nolockClose()) would be called instead.
26374   */
26375   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26376   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26377     /* If there are outstanding locks, do not actually close the file just
26378     ** yet because that would clear those locks.  Instead, add the file
26379     ** descriptor to pInode->pUnused list.  It will be automatically closed
26380     ** when the last lock is cleared.
26381     */
26382     setPendingFd(pFile);
26383   }
26384   releaseInodeInfo(pFile);
26385   rc = closeUnixFile(id);
26386   unixLeaveMutex();
26387   return rc;
26388 }
26389 
26390 /************** End of the posix advisory lock implementation *****************
26391 ******************************************************************************/
26392 
26393 /******************************************************************************
26394 ****************************** No-op Locking **********************************
26395 **
26396 ** Of the various locking implementations available, this is by far the
26397 ** simplest:  locking is ignored.  No attempt is made to lock the database
26398 ** file for reading or writing.
26399 **
26400 ** This locking mode is appropriate for use on read-only databases
26401 ** (ex: databases that are burned into CD-ROM, for example.)  It can
26402 ** also be used if the application employs some external mechanism to
26403 ** prevent simultaneous access of the same database by two or more
26404 ** database connections.  But there is a serious risk of database
26405 ** corruption if this locking mode is used in situations where multiple
26406 ** database connections are accessing the same database file at the same
26407 ** time and one or more of those connections are writing.
26408 */
26409 
26410 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26411   UNUSED_PARAMETER(NotUsed);
26412   *pResOut = 0;
26413   return SQLITE_OK;
26414 }
26415 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26416   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26417   return SQLITE_OK;
26418 }
26419 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26420   UNUSED_PARAMETER2(NotUsed, NotUsed2);
26421   return SQLITE_OK;
26422 }
26423 
26424 /*
26425 ** Close the file.
26426 */
26427 static int nolockClose(sqlite3_file *id) {
26428   return closeUnixFile(id);
26429 }
26430 
26431 /******************* End of the no-op lock implementation *********************
26432 ******************************************************************************/
26433 
26434 /******************************************************************************
26435 ************************* Begin dot-file Locking ******************************
26436 **
26437 ** The dotfile locking implementation uses the existance of separate lock
26438 ** files in order to control access to the database.  This works on just
26439 ** about every filesystem imaginable.  But there are serious downsides:
26440 **
26441 **    (1)  There is zero concurrency.  A single reader blocks all other
26442 **         connections from reading or writing the database.
26443 **
26444 **    (2)  An application crash or power loss can leave stale lock files
26445 **         sitting around that need to be cleared manually.
26446 **
26447 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
26448 ** other locking strategy is available.
26449 **
26450 ** Dotfile locking works by creating a file in the same directory as the
26451 ** database and with the same name but with a ".lock" extension added.
26452 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
26453 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26454 */
26455 
26456 /*
26457 ** The file suffix added to the data base filename in order to create the
26458 ** lock file.
26459 */
26460 #define DOTLOCK_SUFFIX ".lock"
26461 
26462 /*
26463 ** This routine checks if there is a RESERVED lock held on the specified
26464 ** file by this or any other process. If such a lock is held, set *pResOut
26465 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26466 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26467 **
26468 ** In dotfile locking, either a lock exists or it does not.  So in this
26469 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
26470 ** is held on the file and false if the file is unlocked.
26471 */
26472 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26473   int rc = SQLITE_OK;
26474   int reserved = 0;
26475   unixFile *pFile = (unixFile*)id;
26476 
26477   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26478 
26479   assert( pFile );
26480 
26481   /* Check if a thread in this process holds such a lock */
26482   if( pFile->eFileLock>SHARED_LOCK ){
26483     /* Either this connection or some other connection in the same process
26484     ** holds a lock on the file.  No need to check further. */
26485     reserved = 1;
26486   }else{
26487     /* The lock is held if and only if the lockfile exists */
26488     const char *zLockFile = (const char*)pFile->lockingContext;
26489     reserved = osAccess(zLockFile, 0)==0;
26490   }
26491   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26492   *pResOut = reserved;
26493   return rc;
26494 }
26495 
26496 /*
26497 ** Lock the file with the lock specified by parameter eFileLock - one
26498 ** of the following:
26499 **
26500 **     (1) SHARED_LOCK
26501 **     (2) RESERVED_LOCK
26502 **     (3) PENDING_LOCK
26503 **     (4) EXCLUSIVE_LOCK
26504 **
26505 ** Sometimes when requesting one lock state, additional lock states
26506 ** are inserted in between.  The locking might fail on one of the later
26507 ** transitions leaving the lock state different from what it started but
26508 ** still short of its goal.  The following chart shows the allowed
26509 ** transitions and the inserted intermediate states:
26510 **
26511 **    UNLOCKED -> SHARED
26512 **    SHARED -> RESERVED
26513 **    SHARED -> (PENDING) -> EXCLUSIVE
26514 **    RESERVED -> (PENDING) -> EXCLUSIVE
26515 **    PENDING -> EXCLUSIVE
26516 **
26517 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26518 ** routine to lower a locking level.
26519 **
26520 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
26521 ** But we track the other locking levels internally.
26522 */
26523 static int dotlockLock(sqlite3_file *id, int eFileLock) {
26524   unixFile *pFile = (unixFile*)id;
26525   int fd;
26526   char *zLockFile = (char *)pFile->lockingContext;
26527   int rc = SQLITE_OK;
26528 
26529 
26530   /* If we have any lock, then the lock file already exists.  All we have
26531   ** to do is adjust our internal record of the lock level.
26532   */
26533   if( pFile->eFileLock > NO_LOCK ){
26534     pFile->eFileLock = eFileLock;
26535     /* Always update the timestamp on the old file */
26536 #ifdef HAVE_UTIME
26537     utime(zLockFile, NULL);
26538 #else
26539     utimes(zLockFile, NULL);
26540 #endif
26541     return SQLITE_OK;
26542   }
26543 
26544   /* grab an exclusive lock */
26545   fd = robust_open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
26546   if( fd<0 ){
26547     /* failed to open/create the file, someone else may have stolen the lock */
26548     int tErrno = errno;
26549     if( EEXIST == tErrno ){
26550       rc = SQLITE_BUSY;
26551     } else {
26552       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26553       if( IS_LOCK_ERROR(rc) ){
26554         pFile->lastErrno = tErrno;
26555       }
26556     }
26557     return rc;
26558   }
26559   robust_close(pFile, fd, __LINE__);
26560 
26561   /* got it, set the type and return ok */
26562   pFile->eFileLock = eFileLock;
26563   return rc;
26564 }
26565 
26566 /*
26567 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26568 ** must be either NO_LOCK or SHARED_LOCK.
26569 **
26570 ** If the locking level of the file descriptor is already at or below
26571 ** the requested locking level, this routine is a no-op.
26572 **
26573 ** When the locking level reaches NO_LOCK, delete the lock file.
26574 */
26575 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
26576   unixFile *pFile = (unixFile*)id;
26577   char *zLockFile = (char *)pFile->lockingContext;
26578 
26579   assert( pFile );
26580   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
26581 	   pFile->eFileLock, getpid()));
26582   assert( eFileLock<=SHARED_LOCK );
26583 
26584   /* no-op if possible */
26585   if( pFile->eFileLock==eFileLock ){
26586     return SQLITE_OK;
26587   }
26588 
26589   /* To downgrade to shared, simply update our internal notion of the
26590   ** lock state.  No need to mess with the file on disk.
26591   */
26592   if( eFileLock==SHARED_LOCK ){
26593     pFile->eFileLock = SHARED_LOCK;
26594     return SQLITE_OK;
26595   }
26596 
26597   /* To fully unlock the database, delete the lock file */
26598   assert( eFileLock==NO_LOCK );
26599   if( osUnlink(zLockFile) ){
26600     int rc = 0;
26601     int tErrno = errno;
26602     if( ENOENT != tErrno ){
26603       rc = SQLITE_IOERR_UNLOCK;
26604     }
26605     if( IS_LOCK_ERROR(rc) ){
26606       pFile->lastErrno = tErrno;
26607     }
26608     return rc;
26609   }
26610   pFile->eFileLock = NO_LOCK;
26611   return SQLITE_OK;
26612 }
26613 
26614 /*
26615 ** Close a file.  Make sure the lock has been released before closing.
26616 */
26617 static int dotlockClose(sqlite3_file *id) {
26618   int rc;
26619   if( id ){
26620     unixFile *pFile = (unixFile*)id;
26621     dotlockUnlock(id, NO_LOCK);
26622     sqlite3_free(pFile->lockingContext);
26623   }
26624   rc = closeUnixFile(id);
26625   return rc;
26626 }
26627 /****************** End of the dot-file lock implementation *******************
26628 ******************************************************************************/
26629 
26630 /******************************************************************************
26631 ************************** Begin flock Locking ********************************
26632 **
26633 ** Use the flock() system call to do file locking.
26634 **
26635 ** flock() locking is like dot-file locking in that the various
26636 ** fine-grain locking levels supported by SQLite are collapsed into
26637 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
26638 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
26639 ** still works when you do this, but concurrency is reduced since
26640 ** only a single process can be reading the database at a time.
26641 **
26642 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
26643 ** compiling for VXWORKS.
26644 */
26645 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
26646 
26647 /*
26648 ** Retry flock() calls that fail with EINTR
26649 */
26650 #ifdef EINTR
26651 static int robust_flock(int fd, int op){
26652   int rc;
26653   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
26654   return rc;
26655 }
26656 #else
26657 # define robust_flock(a,b) flock(a,b)
26658 #endif
26659 
26660 
26661 /*
26662 ** This routine checks if there is a RESERVED lock held on the specified
26663 ** file by this or any other process. If such a lock is held, set *pResOut
26664 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26665 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26666 */
26667 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
26668   int rc = SQLITE_OK;
26669   int reserved = 0;
26670   unixFile *pFile = (unixFile*)id;
26671 
26672   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26673 
26674   assert( pFile );
26675 
26676   /* Check if a thread in this process holds such a lock */
26677   if( pFile->eFileLock>SHARED_LOCK ){
26678     reserved = 1;
26679   }
26680 
26681   /* Otherwise see if some other process holds it. */
26682   if( !reserved ){
26683     /* attempt to get the lock */
26684     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
26685     if( !lrc ){
26686       /* got the lock, unlock it */
26687       lrc = robust_flock(pFile->h, LOCK_UN);
26688       if ( lrc ) {
26689         int tErrno = errno;
26690         /* unlock failed with an error */
26691         lrc = SQLITE_IOERR_UNLOCK;
26692         if( IS_LOCK_ERROR(lrc) ){
26693           pFile->lastErrno = tErrno;
26694           rc = lrc;
26695         }
26696       }
26697     } else {
26698       int tErrno = errno;
26699       reserved = 1;
26700       /* someone else might have it reserved */
26701       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26702       if( IS_LOCK_ERROR(lrc) ){
26703         pFile->lastErrno = tErrno;
26704         rc = lrc;
26705       }
26706     }
26707   }
26708   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
26709 
26710 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26711   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26712     rc = SQLITE_OK;
26713     reserved=1;
26714   }
26715 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26716   *pResOut = reserved;
26717   return rc;
26718 }
26719 
26720 /*
26721 ** Lock the file with the lock specified by parameter eFileLock - one
26722 ** of the following:
26723 **
26724 **     (1) SHARED_LOCK
26725 **     (2) RESERVED_LOCK
26726 **     (3) PENDING_LOCK
26727 **     (4) EXCLUSIVE_LOCK
26728 **
26729 ** Sometimes when requesting one lock state, additional lock states
26730 ** are inserted in between.  The locking might fail on one of the later
26731 ** transitions leaving the lock state different from what it started but
26732 ** still short of its goal.  The following chart shows the allowed
26733 ** transitions and the inserted intermediate states:
26734 **
26735 **    UNLOCKED -> SHARED
26736 **    SHARED -> RESERVED
26737 **    SHARED -> (PENDING) -> EXCLUSIVE
26738 **    RESERVED -> (PENDING) -> EXCLUSIVE
26739 **    PENDING -> EXCLUSIVE
26740 **
26741 ** flock() only really support EXCLUSIVE locks.  We track intermediate
26742 ** lock states in the sqlite3_file structure, but all locks SHARED or
26743 ** above are really EXCLUSIVE locks and exclude all other processes from
26744 ** access the file.
26745 **
26746 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26747 ** routine to lower a locking level.
26748 */
26749 static int flockLock(sqlite3_file *id, int eFileLock) {
26750   int rc = SQLITE_OK;
26751   unixFile *pFile = (unixFile*)id;
26752 
26753   assert( pFile );
26754 
26755   /* if we already have a lock, it is exclusive.
26756   ** Just adjust level and punt on outta here. */
26757   if (pFile->eFileLock > NO_LOCK) {
26758     pFile->eFileLock = eFileLock;
26759     return SQLITE_OK;
26760   }
26761 
26762   /* grab an exclusive lock */
26763 
26764   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
26765     int tErrno = errno;
26766     /* didn't get, must be busy */
26767     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26768     if( IS_LOCK_ERROR(rc) ){
26769       pFile->lastErrno = tErrno;
26770     }
26771   } else {
26772     /* got it, set the type and return ok */
26773     pFile->eFileLock = eFileLock;
26774   }
26775   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
26776            rc==SQLITE_OK ? "ok" : "failed"));
26777 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26778   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
26779     rc = SQLITE_BUSY;
26780   }
26781 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26782   return rc;
26783 }
26784 
26785 
26786 /*
26787 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26788 ** must be either NO_LOCK or SHARED_LOCK.
26789 **
26790 ** If the locking level of the file descriptor is already at or below
26791 ** the requested locking level, this routine is a no-op.
26792 */
26793 static int flockUnlock(sqlite3_file *id, int eFileLock) {
26794   unixFile *pFile = (unixFile*)id;
26795 
26796   assert( pFile );
26797   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
26798            pFile->eFileLock, getpid()));
26799   assert( eFileLock<=SHARED_LOCK );
26800 
26801   /* no-op if possible */
26802   if( pFile->eFileLock==eFileLock ){
26803     return SQLITE_OK;
26804   }
26805 
26806   /* shared can just be set because we always have an exclusive */
26807   if (eFileLock==SHARED_LOCK) {
26808     pFile->eFileLock = eFileLock;
26809     return SQLITE_OK;
26810   }
26811 
26812   /* no, really, unlock. */
26813   if( robust_flock(pFile->h, LOCK_UN) ){
26814 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
26815     return SQLITE_OK;
26816 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
26817     return SQLITE_IOERR_UNLOCK;
26818   }else{
26819     pFile->eFileLock = NO_LOCK;
26820     return SQLITE_OK;
26821   }
26822 }
26823 
26824 /*
26825 ** Close a file.
26826 */
26827 static int flockClose(sqlite3_file *id) {
26828   if( id ){
26829     flockUnlock(id, NO_LOCK);
26830   }
26831   return closeUnixFile(id);
26832 }
26833 
26834 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
26835 
26836 /******************* End of the flock lock implementation *********************
26837 ******************************************************************************/
26838 
26839 /******************************************************************************
26840 ************************ Begin Named Semaphore Locking ************************
26841 **
26842 ** Named semaphore locking is only supported on VxWorks.
26843 **
26844 ** Semaphore locking is like dot-lock and flock in that it really only
26845 ** supports EXCLUSIVE locking.  Only a single process can read or write
26846 ** the database file at a time.  This reduces potential concurrency, but
26847 ** makes the lock implementation much easier.
26848 */
26849 #if OS_VXWORKS
26850 
26851 /*
26852 ** This routine checks if there is a RESERVED lock held on the specified
26853 ** file by this or any other process. If such a lock is held, set *pResOut
26854 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26855 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26856 */
26857 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
26858   int rc = SQLITE_OK;
26859   int reserved = 0;
26860   unixFile *pFile = (unixFile*)id;
26861 
26862   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26863 
26864   assert( pFile );
26865 
26866   /* Check if a thread in this process holds such a lock */
26867   if( pFile->eFileLock>SHARED_LOCK ){
26868     reserved = 1;
26869   }
26870 
26871   /* Otherwise see if some other process holds it. */
26872   if( !reserved ){
26873     sem_t *pSem = pFile->pInode->pSem;
26874     struct stat statBuf;
26875 
26876     if( sem_trywait(pSem)==-1 ){
26877       int tErrno = errno;
26878       if( EAGAIN != tErrno ){
26879         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
26880         pFile->lastErrno = tErrno;
26881       } else {
26882         /* someone else has the lock when we are in NO_LOCK */
26883         reserved = (pFile->eFileLock < SHARED_LOCK);
26884       }
26885     }else{
26886       /* we could have it if we want it */
26887       sem_post(pSem);
26888     }
26889   }
26890   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
26891 
26892   *pResOut = reserved;
26893   return rc;
26894 }
26895 
26896 /*
26897 ** Lock the file with the lock specified by parameter eFileLock - one
26898 ** of the following:
26899 **
26900 **     (1) SHARED_LOCK
26901 **     (2) RESERVED_LOCK
26902 **     (3) PENDING_LOCK
26903 **     (4) EXCLUSIVE_LOCK
26904 **
26905 ** Sometimes when requesting one lock state, additional lock states
26906 ** are inserted in between.  The locking might fail on one of the later
26907 ** transitions leaving the lock state different from what it started but
26908 ** still short of its goal.  The following chart shows the allowed
26909 ** transitions and the inserted intermediate states:
26910 **
26911 **    UNLOCKED -> SHARED
26912 **    SHARED -> RESERVED
26913 **    SHARED -> (PENDING) -> EXCLUSIVE
26914 **    RESERVED -> (PENDING) -> EXCLUSIVE
26915 **    PENDING -> EXCLUSIVE
26916 **
26917 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
26918 ** lock states in the sqlite3_file structure, but all locks SHARED or
26919 ** above are really EXCLUSIVE locks and exclude all other processes from
26920 ** access the file.
26921 **
26922 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26923 ** routine to lower a locking level.
26924 */
26925 static int semLock(sqlite3_file *id, int eFileLock) {
26926   unixFile *pFile = (unixFile*)id;
26927   int fd;
26928   sem_t *pSem = pFile->pInode->pSem;
26929   int rc = SQLITE_OK;
26930 
26931   /* if we already have a lock, it is exclusive.
26932   ** Just adjust level and punt on outta here. */
26933   if (pFile->eFileLock > NO_LOCK) {
26934     pFile->eFileLock = eFileLock;
26935     rc = SQLITE_OK;
26936     goto sem_end_lock;
26937   }
26938 
26939   /* lock semaphore now but bail out when already locked. */
26940   if( sem_trywait(pSem)==-1 ){
26941     rc = SQLITE_BUSY;
26942     goto sem_end_lock;
26943   }
26944 
26945   /* got it, set the type and return ok */
26946   pFile->eFileLock = eFileLock;
26947 
26948  sem_end_lock:
26949   return rc;
26950 }
26951 
26952 /*
26953 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26954 ** must be either NO_LOCK or SHARED_LOCK.
26955 **
26956 ** If the locking level of the file descriptor is already at or below
26957 ** the requested locking level, this routine is a no-op.
26958 */
26959 static int semUnlock(sqlite3_file *id, int eFileLock) {
26960   unixFile *pFile = (unixFile*)id;
26961   sem_t *pSem = pFile->pInode->pSem;
26962 
26963   assert( pFile );
26964   assert( pSem );
26965   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
26966 	   pFile->eFileLock, getpid()));
26967   assert( eFileLock<=SHARED_LOCK );
26968 
26969   /* no-op if possible */
26970   if( pFile->eFileLock==eFileLock ){
26971     return SQLITE_OK;
26972   }
26973 
26974   /* shared can just be set because we always have an exclusive */
26975   if (eFileLock==SHARED_LOCK) {
26976     pFile->eFileLock = eFileLock;
26977     return SQLITE_OK;
26978   }
26979 
26980   /* no, really unlock. */
26981   if ( sem_post(pSem)==-1 ) {
26982     int rc, tErrno = errno;
26983     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
26984     if( IS_LOCK_ERROR(rc) ){
26985       pFile->lastErrno = tErrno;
26986     }
26987     return rc;
26988   }
26989   pFile->eFileLock = NO_LOCK;
26990   return SQLITE_OK;
26991 }
26992 
26993 /*
26994  ** Close a file.
26995  */
26996 static int semClose(sqlite3_file *id) {
26997   if( id ){
26998     unixFile *pFile = (unixFile*)id;
26999     semUnlock(id, NO_LOCK);
27000     assert( pFile );
27001     unixEnterMutex();
27002     releaseInodeInfo(pFile);
27003     unixLeaveMutex();
27004     closeUnixFile(id);
27005   }
27006   return SQLITE_OK;
27007 }
27008 
27009 #endif /* OS_VXWORKS */
27010 /*
27011 ** Named semaphore locking is only available on VxWorks.
27012 **
27013 *************** End of the named semaphore lock implementation ****************
27014 ******************************************************************************/
27015 
27016 
27017 /******************************************************************************
27018 *************************** Begin AFP Locking *********************************
27019 **
27020 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27021 ** on Apple Macintosh computers - both OS9 and OSX.
27022 **
27023 ** Third-party implementations of AFP are available.  But this code here
27024 ** only works on OSX.
27025 */
27026 
27027 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27028 /*
27029 ** The afpLockingContext structure contains all afp lock specific state
27030 */
27031 typedef struct afpLockingContext afpLockingContext;
27032 struct afpLockingContext {
27033   int reserved;
27034   const char *dbPath;             /* Name of the open file */
27035 };
27036 
27037 struct ByteRangeLockPB2
27038 {
27039   unsigned long long offset;        /* offset to first byte to lock */
27040   unsigned long long length;        /* nbr of bytes to lock */
27041   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27042   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27043   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27044   int fd;                           /* file desc to assoc this lock with */
27045 };
27046 
27047 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27048 
27049 /*
27050 ** This is a utility for setting or clearing a bit-range lock on an
27051 ** AFP filesystem.
27052 **
27053 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27054 */
27055 static int afpSetLock(
27056   const char *path,              /* Name of the file to be locked or unlocked */
27057   unixFile *pFile,               /* Open file descriptor on path */
27058   unsigned long long offset,     /* First byte to be locked */
27059   unsigned long long length,     /* Number of bytes to lock */
27060   int setLockFlag                /* True to set lock.  False to clear lock */
27061 ){
27062   struct ByteRangeLockPB2 pb;
27063   int err;
27064 
27065   pb.unLockFlag = setLockFlag ? 0 : 1;
27066   pb.startEndFlag = 0;
27067   pb.offset = offset;
27068   pb.length = length;
27069   pb.fd = pFile->h;
27070 
27071   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27072     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27073     offset, length));
27074   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27075   if ( err==-1 ) {
27076     int rc;
27077     int tErrno = errno;
27078     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27079              path, tErrno, strerror(tErrno)));
27080 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27081     rc = SQLITE_BUSY;
27082 #else
27083     rc = sqliteErrorFromPosixError(tErrno,
27084                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27085 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27086     if( IS_LOCK_ERROR(rc) ){
27087       pFile->lastErrno = tErrno;
27088     }
27089     return rc;
27090   } else {
27091     return SQLITE_OK;
27092   }
27093 }
27094 
27095 /*
27096 ** This routine checks if there is a RESERVED lock held on the specified
27097 ** file by this or any other process. If such a lock is held, set *pResOut
27098 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27099 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27100 */
27101 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27102   int rc = SQLITE_OK;
27103   int reserved = 0;
27104   unixFile *pFile = (unixFile*)id;
27105   afpLockingContext *context;
27106 
27107   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27108 
27109   assert( pFile );
27110   context = (afpLockingContext *) pFile->lockingContext;
27111   if( context->reserved ){
27112     *pResOut = 1;
27113     return SQLITE_OK;
27114   }
27115   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27116 
27117   /* Check if a thread in this process holds such a lock */
27118   if( pFile->pInode->eFileLock>SHARED_LOCK ){
27119     reserved = 1;
27120   }
27121 
27122   /* Otherwise see if some other process holds it.
27123    */
27124   if( !reserved ){
27125     /* lock the RESERVED byte */
27126     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27127     if( SQLITE_OK==lrc ){
27128       /* if we succeeded in taking the reserved lock, unlock it to restore
27129       ** the original state */
27130       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27131     } else {
27132       /* if we failed to get the lock then someone else must have it */
27133       reserved = 1;
27134     }
27135     if( IS_LOCK_ERROR(lrc) ){
27136       rc=lrc;
27137     }
27138   }
27139 
27140   unixLeaveMutex();
27141   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27142 
27143   *pResOut = reserved;
27144   return rc;
27145 }
27146 
27147 /*
27148 ** Lock the file with the lock specified by parameter eFileLock - one
27149 ** of the following:
27150 **
27151 **     (1) SHARED_LOCK
27152 **     (2) RESERVED_LOCK
27153 **     (3) PENDING_LOCK
27154 **     (4) EXCLUSIVE_LOCK
27155 **
27156 ** Sometimes when requesting one lock state, additional lock states
27157 ** are inserted in between.  The locking might fail on one of the later
27158 ** transitions leaving the lock state different from what it started but
27159 ** still short of its goal.  The following chart shows the allowed
27160 ** transitions and the inserted intermediate states:
27161 **
27162 **    UNLOCKED -> SHARED
27163 **    SHARED -> RESERVED
27164 **    SHARED -> (PENDING) -> EXCLUSIVE
27165 **    RESERVED -> (PENDING) -> EXCLUSIVE
27166 **    PENDING -> EXCLUSIVE
27167 **
27168 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27169 ** routine to lower a locking level.
27170 */
27171 static int afpLock(sqlite3_file *id, int eFileLock){
27172   int rc = SQLITE_OK;
27173   unixFile *pFile = (unixFile*)id;
27174   unixInodeInfo *pInode = pFile->pInode;
27175   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27176 
27177   assert( pFile );
27178   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27179            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27180            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27181 
27182   /* If there is already a lock of this type or more restrictive on the
27183   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27184   ** unixEnterMutex() hasn't been called yet.
27185   */
27186   if( pFile->eFileLock>=eFileLock ){
27187     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27188            azFileLock(eFileLock)));
27189     return SQLITE_OK;
27190   }
27191 
27192   /* Make sure the locking sequence is correct
27193   **  (1) We never move from unlocked to anything higher than shared lock.
27194   **  (2) SQLite never explicitly requests a pendig lock.
27195   **  (3) A shared lock is always held when a reserve lock is requested.
27196   */
27197   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27198   assert( eFileLock!=PENDING_LOCK );
27199   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27200 
27201   /* This mutex is needed because pFile->pInode is shared across threads
27202   */
27203   unixEnterMutex();
27204   pInode = pFile->pInode;
27205 
27206   /* If some thread using this PID has a lock via a different unixFile*
27207   ** handle that precludes the requested lock, return BUSY.
27208   */
27209   if( (pFile->eFileLock!=pInode->eFileLock &&
27210        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27211      ){
27212     rc = SQLITE_BUSY;
27213     goto afp_end_lock;
27214   }
27215 
27216   /* If a SHARED lock is requested, and some thread using this PID already
27217   ** has a SHARED or RESERVED lock, then increment reference counts and
27218   ** return SQLITE_OK.
27219   */
27220   if( eFileLock==SHARED_LOCK &&
27221      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27222     assert( eFileLock==SHARED_LOCK );
27223     assert( pFile->eFileLock==0 );
27224     assert( pInode->nShared>0 );
27225     pFile->eFileLock = SHARED_LOCK;
27226     pInode->nShared++;
27227     pInode->nLock++;
27228     goto afp_end_lock;
27229   }
27230 
27231   /* A PENDING lock is needed before acquiring a SHARED lock and before
27232   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27233   ** be released.
27234   */
27235   if( eFileLock==SHARED_LOCK
27236       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27237   ){
27238     int failed;
27239     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27240     if (failed) {
27241       rc = failed;
27242       goto afp_end_lock;
27243     }
27244   }
27245 
27246   /* If control gets to this point, then actually go ahead and make
27247   ** operating system calls for the specified lock.
27248   */
27249   if( eFileLock==SHARED_LOCK ){
27250     int lrc1, lrc2, lrc1Errno = 0;
27251     long lk, mask;
27252 
27253     assert( pInode->nShared==0 );
27254     assert( pInode->eFileLock==0 );
27255 
27256     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27257     /* Now get the read-lock SHARED_LOCK */
27258     /* note that the quality of the randomness doesn't matter that much */
27259     lk = random();
27260     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27261     lrc1 = afpSetLock(context->dbPath, pFile,
27262           SHARED_FIRST+pInode->sharedByte, 1, 1);
27263     if( IS_LOCK_ERROR(lrc1) ){
27264       lrc1Errno = pFile->lastErrno;
27265     }
27266     /* Drop the temporary PENDING lock */
27267     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27268 
27269     if( IS_LOCK_ERROR(lrc1) ) {
27270       pFile->lastErrno = lrc1Errno;
27271       rc = lrc1;
27272       goto afp_end_lock;
27273     } else if( IS_LOCK_ERROR(lrc2) ){
27274       rc = lrc2;
27275       goto afp_end_lock;
27276     } else if( lrc1 != SQLITE_OK ) {
27277       rc = lrc1;
27278     } else {
27279       pFile->eFileLock = SHARED_LOCK;
27280       pInode->nLock++;
27281       pInode->nShared = 1;
27282     }
27283   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27284     /* We are trying for an exclusive lock but another thread in this
27285      ** same process is still holding a shared lock. */
27286     rc = SQLITE_BUSY;
27287   }else{
27288     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27289     ** assumed that there is a SHARED or greater lock on the file
27290     ** already.
27291     */
27292     int failed = 0;
27293     assert( 0!=pFile->eFileLock );
27294     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27295         /* Acquire a RESERVED lock */
27296         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27297       if( !failed ){
27298         context->reserved = 1;
27299       }
27300     }
27301     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27302       /* Acquire an EXCLUSIVE lock */
27303 
27304       /* Remove the shared lock before trying the range.  we'll need to
27305       ** reestablish the shared lock if we can't get the  afpUnlock
27306       */
27307       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27308                          pInode->sharedByte, 1, 0)) ){
27309         int failed2 = SQLITE_OK;
27310         /* now attemmpt to get the exclusive lock range */
27311         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27312                                SHARED_SIZE, 1);
27313         if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27314                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27315           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27316           ** a critical I/O error
27317           */
27318           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27319                SQLITE_IOERR_LOCK;
27320           goto afp_end_lock;
27321         }
27322       }else{
27323         rc = failed;
27324       }
27325     }
27326     if( failed ){
27327       rc = failed;
27328     }
27329   }
27330 
27331   if( rc==SQLITE_OK ){
27332     pFile->eFileLock = eFileLock;
27333     pInode->eFileLock = eFileLock;
27334   }else if( eFileLock==EXCLUSIVE_LOCK ){
27335     pFile->eFileLock = PENDING_LOCK;
27336     pInode->eFileLock = PENDING_LOCK;
27337   }
27338 
27339 afp_end_lock:
27340   unixLeaveMutex();
27341   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27342          rc==SQLITE_OK ? "ok" : "failed"));
27343   return rc;
27344 }
27345 
27346 /*
27347 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27348 ** must be either NO_LOCK or SHARED_LOCK.
27349 **
27350 ** If the locking level of the file descriptor is already at or below
27351 ** the requested locking level, this routine is a no-op.
27352 */
27353 static int afpUnlock(sqlite3_file *id, int eFileLock) {
27354   int rc = SQLITE_OK;
27355   unixFile *pFile = (unixFile*)id;
27356   unixInodeInfo *pInode;
27357   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27358   int skipShared = 0;
27359 #ifdef SQLITE_TEST
27360   int h = pFile->h;
27361 #endif
27362 
27363   assert( pFile );
27364   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27365            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27366            getpid()));
27367 
27368   assert( eFileLock<=SHARED_LOCK );
27369   if( pFile->eFileLock<=eFileLock ){
27370     return SQLITE_OK;
27371   }
27372   unixEnterMutex();
27373   pInode = pFile->pInode;
27374   assert( pInode->nShared!=0 );
27375   if( pFile->eFileLock>SHARED_LOCK ){
27376     assert( pInode->eFileLock==pFile->eFileLock );
27377     SimulateIOErrorBenign(1);
27378     SimulateIOError( h=(-1) )
27379     SimulateIOErrorBenign(0);
27380 
27381 #ifndef NDEBUG
27382     /* When reducing a lock such that other processes can start
27383     ** reading the database file again, make sure that the
27384     ** transaction counter was updated if any part of the database
27385     ** file changed.  If the transaction counter is not updated,
27386     ** other connections to the same file might not realize that
27387     ** the file has changed and hence might not know to flush their
27388     ** cache.  The use of a stale cache can lead to database corruption.
27389     */
27390     assert( pFile->inNormalWrite==0
27391            || pFile->dbUpdate==0
27392            || pFile->transCntrChng==1 );
27393     pFile->inNormalWrite = 0;
27394 #endif
27395 
27396     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27397       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27398       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27399         /* only re-establish the shared lock if necessary */
27400         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27401         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27402       } else {
27403         skipShared = 1;
27404       }
27405     }
27406     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27407       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27408     }
27409     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27410       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27411       if( !rc ){
27412         context->reserved = 0;
27413       }
27414     }
27415     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27416       pInode->eFileLock = SHARED_LOCK;
27417     }
27418   }
27419   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27420 
27421     /* Decrement the shared lock counter.  Release the lock using an
27422     ** OS call only when all threads in this same process have released
27423     ** the lock.
27424     */
27425     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27426     pInode->nShared--;
27427     if( pInode->nShared==0 ){
27428       SimulateIOErrorBenign(1);
27429       SimulateIOError( h=(-1) )
27430       SimulateIOErrorBenign(0);
27431       if( !skipShared ){
27432         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27433       }
27434       if( !rc ){
27435         pInode->eFileLock = NO_LOCK;
27436         pFile->eFileLock = NO_LOCK;
27437       }
27438     }
27439     if( rc==SQLITE_OK ){
27440       pInode->nLock--;
27441       assert( pInode->nLock>=0 );
27442       if( pInode->nLock==0 ){
27443         closePendingFds(pFile);
27444       }
27445     }
27446   }
27447 
27448   unixLeaveMutex();
27449   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27450   return rc;
27451 }
27452 
27453 /*
27454 ** Close a file & cleanup AFP specific locking context
27455 */
27456 static int afpClose(sqlite3_file *id) {
27457   int rc = SQLITE_OK;
27458   if( id ){
27459     unixFile *pFile = (unixFile*)id;
27460     afpUnlock(id, NO_LOCK);
27461     unixEnterMutex();
27462     if( pFile->pInode && pFile->pInode->nLock ){
27463       /* If there are outstanding locks, do not actually close the file just
27464       ** yet because that would clear those locks.  Instead, add the file
27465       ** descriptor to pInode->aPending.  It will be automatically closed when
27466       ** the last lock is cleared.
27467       */
27468       setPendingFd(pFile);
27469     }
27470     releaseInodeInfo(pFile);
27471     sqlite3_free(pFile->lockingContext);
27472     rc = closeUnixFile(id);
27473     unixLeaveMutex();
27474   }
27475   return rc;
27476 }
27477 
27478 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27479 /*
27480 ** The code above is the AFP lock implementation.  The code is specific
27481 ** to MacOSX and does not work on other unix platforms.  No alternative
27482 ** is available.  If you don't compile for a mac, then the "unix-afp"
27483 ** VFS is not available.
27484 **
27485 ********************* End of the AFP lock implementation **********************
27486 ******************************************************************************/
27487 
27488 /******************************************************************************
27489 *************************** Begin NFS Locking ********************************/
27490 
27491 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27492 /*
27493  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27494  ** must be either NO_LOCK or SHARED_LOCK.
27495  **
27496  ** If the locking level of the file descriptor is already at or below
27497  ** the requested locking level, this routine is a no-op.
27498  */
27499 static int nfsUnlock(sqlite3_file *id, int eFileLock){
27500   return posixUnlock(id, eFileLock, 1);
27501 }
27502 
27503 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27504 /*
27505 ** The code above is the NFS lock implementation.  The code is specific
27506 ** to MacOSX and does not work on other unix platforms.  No alternative
27507 ** is available.
27508 **
27509 ********************* End of the NFS lock implementation **********************
27510 ******************************************************************************/
27511 
27512 /******************************************************************************
27513 **************** Non-locking sqlite3_file methods *****************************
27514 **
27515 ** The next division contains implementations for all methods of the
27516 ** sqlite3_file object other than the locking methods.  The locking
27517 ** methods were defined in divisions above (one locking method per
27518 ** division).  Those methods that are common to all locking modes
27519 ** are gather together into this division.
27520 */
27521 
27522 /*
27523 ** Seek to the offset passed as the second argument, then read cnt
27524 ** bytes into pBuf. Return the number of bytes actually read.
27525 **
27526 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27527 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27528 ** one system to another.  Since SQLite does not define USE_PREAD
27529 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27530 ** See tickets #2741 and #2681.
27531 **
27532 ** To avoid stomping the errno value on a failed read the lastErrno value
27533 ** is set before returning.
27534 */
27535 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
27536   int got;
27537 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27538   i64 newOffset;
27539 #endif
27540   TIMER_START;
27541 #if defined(USE_PREAD)
27542   do{ got = osPread(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27543   SimulateIOError( got = -1 );
27544 #elif defined(USE_PREAD64)
27545   do{ got = osPread64(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR);
27546   SimulateIOError( got = -1 );
27547 #else
27548   newOffset = lseek(id->h, offset, SEEK_SET);
27549   SimulateIOError( newOffset-- );
27550   if( newOffset!=offset ){
27551     if( newOffset == -1 ){
27552       ((unixFile*)id)->lastErrno = errno;
27553     }else{
27554       ((unixFile*)id)->lastErrno = 0;
27555     }
27556     return -1;
27557   }
27558   do{ got = osRead(id->h, pBuf, cnt); }while( got<0 && errno==EINTR );
27559 #endif
27560   TIMER_END;
27561   if( got<0 ){
27562     ((unixFile*)id)->lastErrno = errno;
27563   }
27564   OSTRACE(("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27565   return got;
27566 }
27567 
27568 /*
27569 ** Read data from a file into a buffer.  Return SQLITE_OK if all
27570 ** bytes were read successfully and SQLITE_IOERR if anything goes
27571 ** wrong.
27572 */
27573 static int unixRead(
27574   sqlite3_file *id,
27575   void *pBuf,
27576   int amt,
27577   sqlite3_int64 offset
27578 ){
27579   unixFile *pFile = (unixFile *)id;
27580   int got;
27581   assert( id );
27582 
27583   /* If this is a database file (not a journal, master-journal or temp
27584   ** file), the bytes in the locking range should never be read or written. */
27585 #if 0
27586   assert( pFile->pUnused==0
27587        || offset>=PENDING_BYTE+512
27588        || offset+amt<=PENDING_BYTE
27589   );
27590 #endif
27591 
27592   got = seekAndRead(pFile, offset, pBuf, amt);
27593   if( got==amt ){
27594     return SQLITE_OK;
27595   }else if( got<0 ){
27596     /* lastErrno set by seekAndRead */
27597     return SQLITE_IOERR_READ;
27598   }else{
27599     pFile->lastErrno = 0; /* not a system error */
27600     /* Unread parts of the buffer must be zero-filled */
27601     memset(&((char*)pBuf)[got], 0, amt-got);
27602     return SQLITE_IOERR_SHORT_READ;
27603   }
27604 }
27605 
27606 /*
27607 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
27608 ** Return the number of bytes actually read.  Update the offset.
27609 **
27610 ** To avoid stomping the errno value on a failed write the lastErrno value
27611 ** is set before returning.
27612 */
27613 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
27614   int got;
27615 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
27616   i64 newOffset;
27617 #endif
27618   TIMER_START;
27619 #if defined(USE_PREAD)
27620   do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
27621 #elif defined(USE_PREAD64)
27622   do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
27623 #else
27624   do{
27625     newOffset = lseek(id->h, offset, SEEK_SET);
27626     SimulateIOError( newOffset-- );
27627     if( newOffset!=offset ){
27628       if( newOffset == -1 ){
27629         ((unixFile*)id)->lastErrno = errno;
27630       }else{
27631         ((unixFile*)id)->lastErrno = 0;
27632       }
27633       return -1;
27634     }
27635     got = osWrite(id->h, pBuf, cnt);
27636   }while( got<0 && errno==EINTR );
27637 #endif
27638   TIMER_END;
27639   if( got<0 ){
27640     ((unixFile*)id)->lastErrno = errno;
27641   }
27642 
27643   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
27644   return got;
27645 }
27646 
27647 
27648 /*
27649 ** Write data from a buffer into a file.  Return SQLITE_OK on success
27650 ** or some other error code on failure.
27651 */
27652 static int unixWrite(
27653   sqlite3_file *id,
27654   const void *pBuf,
27655   int amt,
27656   sqlite3_int64 offset
27657 ){
27658   unixFile *pFile = (unixFile*)id;
27659   int wrote = 0;
27660   assert( id );
27661   assert( amt>0 );
27662 
27663   /* If this is a database file (not a journal, master-journal or temp
27664   ** file), the bytes in the locking range should never be read or written. */
27665 #if 0
27666   assert( pFile->pUnused==0
27667        || offset>=PENDING_BYTE+512
27668        || offset+amt<=PENDING_BYTE
27669   );
27670 #endif
27671 
27672 #ifndef NDEBUG
27673   /* If we are doing a normal write to a database file (as opposed to
27674   ** doing a hot-journal rollback or a write to some file other than a
27675   ** normal database file) then record the fact that the database
27676   ** has changed.  If the transaction counter is modified, record that
27677   ** fact too.
27678   */
27679   if( pFile->inNormalWrite ){
27680     pFile->dbUpdate = 1;  /* The database has been modified */
27681     if( offset<=24 && offset+amt>=27 ){
27682       int rc;
27683       char oldCntr[4];
27684       SimulateIOErrorBenign(1);
27685       rc = seekAndRead(pFile, 24, oldCntr, 4);
27686       SimulateIOErrorBenign(0);
27687       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
27688         pFile->transCntrChng = 1;  /* The transaction counter has changed */
27689       }
27690     }
27691   }
27692 #endif
27693 
27694   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
27695     amt -= wrote;
27696     offset += wrote;
27697     pBuf = &((char*)pBuf)[wrote];
27698   }
27699   SimulateIOError(( wrote=(-1), amt=1 ));
27700   SimulateDiskfullError(( wrote=0, amt=1 ));
27701 
27702   if( amt>0 ){
27703     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
27704       /* lastErrno set by seekAndWrite */
27705       return SQLITE_IOERR_WRITE;
27706     }else{
27707       pFile->lastErrno = 0; /* not a system error */
27708       return SQLITE_FULL;
27709     }
27710   }
27711 
27712   return SQLITE_OK;
27713 }
27714 
27715 #ifdef SQLITE_TEST
27716 /*
27717 ** Count the number of fullsyncs and normal syncs.  This is used to test
27718 ** that syncs and fullsyncs are occurring at the right times.
27719 */
27720 SQLITE_API int sqlite3_sync_count = 0;
27721 SQLITE_API int sqlite3_fullsync_count = 0;
27722 #endif
27723 
27724 /*
27725 ** We do not trust systems to provide a working fdatasync().  Some do.
27726 ** Others do no.  To be safe, we will stick with the (slightly slower)
27727 ** fsync(). If you know that your system does support fdatasync() correctly,
27728 ** then simply compile with -Dfdatasync=fdatasync
27729 */
27730 #if !defined(fdatasync)
27731 # define fdatasync fsync
27732 #endif
27733 
27734 /*
27735 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
27736 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
27737 ** only available on Mac OS X.  But that could change.
27738 */
27739 #ifdef F_FULLFSYNC
27740 # define HAVE_FULLFSYNC 1
27741 #else
27742 # define HAVE_FULLFSYNC 0
27743 #endif
27744 
27745 
27746 /*
27747 ** The fsync() system call does not work as advertised on many
27748 ** unix systems.  The following procedure is an attempt to make
27749 ** it work better.
27750 **
27751 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
27752 ** for testing when we want to run through the test suite quickly.
27753 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
27754 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
27755 ** or power failure will likely corrupt the database file.
27756 **
27757 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
27758 ** The idea behind dataOnly is that it should only write the file content
27759 ** to disk, not the inode.  We only set dataOnly if the file size is
27760 ** unchanged since the file size is part of the inode.  However,
27761 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
27762 ** file size has changed.  The only real difference between fdatasync()
27763 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
27764 ** inode if the mtime or owner or other inode attributes have changed.
27765 ** We only care about the file size, not the other file attributes, so
27766 ** as far as SQLite is concerned, an fdatasync() is always adequate.
27767 ** So, we always use fdatasync() if it is available, regardless of
27768 ** the value of the dataOnly flag.
27769 */
27770 static int full_fsync(int fd, int fullSync, int dataOnly){
27771   int rc;
27772 
27773   /* The following "ifdef/elif/else/" block has the same structure as
27774   ** the one below. It is replicated here solely to avoid cluttering
27775   ** up the real code with the UNUSED_PARAMETER() macros.
27776   */
27777 #ifdef SQLITE_NO_SYNC
27778   UNUSED_PARAMETER(fd);
27779   UNUSED_PARAMETER(fullSync);
27780   UNUSED_PARAMETER(dataOnly);
27781 #elif HAVE_FULLFSYNC
27782   UNUSED_PARAMETER(dataOnly);
27783 #else
27784   UNUSED_PARAMETER(fullSync);
27785   UNUSED_PARAMETER(dataOnly);
27786 #endif
27787 
27788   /* Record the number of times that we do a normal fsync() and
27789   ** FULLSYNC.  This is used during testing to verify that this procedure
27790   ** gets called with the correct arguments.
27791   */
27792 #ifdef SQLITE_TEST
27793   if( fullSync ) sqlite3_fullsync_count++;
27794   sqlite3_sync_count++;
27795 #endif
27796 
27797   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27798   ** no-op
27799   */
27800 #ifdef SQLITE_NO_SYNC
27801   rc = SQLITE_OK;
27802 #elif HAVE_FULLFSYNC
27803   if( fullSync ){
27804     rc = osFcntl(fd, F_FULLFSYNC, 0);
27805   }else{
27806     rc = 1;
27807   }
27808   /* If the FULLFSYNC failed, fall back to attempting an fsync().
27809   ** It shouldn't be possible for fullfsync to fail on the local
27810   ** file system (on OSX), so failure indicates that FULLFSYNC
27811   ** isn't supported for this file system. So, attempt an fsync
27812   ** and (for now) ignore the overhead of a superfluous fcntl call.
27813   ** It'd be better to detect fullfsync support once and avoid
27814   ** the fcntl call every time sync is called.
27815   */
27816   if( rc ) rc = fsync(fd);
27817 
27818 #elif defined(__APPLE__)
27819   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
27820   ** so currently we default to the macro that redefines fdatasync to fsync
27821   */
27822   rc = fsync(fd);
27823 #else
27824   rc = fdatasync(fd);
27825 #if OS_VXWORKS
27826   if( rc==-1 && errno==ENOTSUP ){
27827     rc = fsync(fd);
27828   }
27829 #endif /* OS_VXWORKS */
27830 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
27831 
27832   if( OS_VXWORKS && rc!= -1 ){
27833     rc = 0;
27834   }
27835   return rc;
27836 }
27837 
27838 /*
27839 ** Open a file descriptor to the directory containing file zFilename.
27840 ** If successful, *pFd is set to the opened file descriptor and
27841 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
27842 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
27843 ** value.
27844 **
27845 ** The directory file descriptor is used for only one thing - to
27846 ** fsync() a directory to make sure file creation and deletion events
27847 ** are flushed to disk.  Such fsyncs are not needed on newer
27848 ** journaling filesystems, but are required on older filesystems.
27849 **
27850 ** This routine can be overridden using the xSetSysCall interface.
27851 ** The ability to override this routine was added in support of the
27852 ** chromium sandbox.  Opening a directory is a security risk (we are
27853 ** told) so making it overrideable allows the chromium sandbox to
27854 ** replace this routine with a harmless no-op.  To make this routine
27855 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
27856 ** *pFd set to a negative number.
27857 **
27858 ** If SQLITE_OK is returned, the caller is responsible for closing
27859 ** the file descriptor *pFd using close().
27860 */
27861 static int openDirectory(const char *zFilename, int *pFd){
27862   int ii;
27863   int fd = -1;
27864   char zDirname[MAX_PATHNAME+1];
27865 
27866   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
27867   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
27868   if( ii>0 ){
27869     zDirname[ii] = '\0';
27870     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
27871     if( fd>=0 ){
27872 #ifdef FD_CLOEXEC
27873       osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
27874 #endif
27875       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
27876     }
27877   }
27878   *pFd = fd;
27879   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
27880 }
27881 
27882 /*
27883 ** Make sure all writes to a particular file are committed to disk.
27884 **
27885 ** If dataOnly==0 then both the file itself and its metadata (file
27886 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
27887 ** file data is synced.
27888 **
27889 ** Under Unix, also make sure that the directory entry for the file
27890 ** has been created by fsync-ing the directory that contains the file.
27891 ** If we do not do this and we encounter a power failure, the directory
27892 ** entry for the journal might not exist after we reboot.  The next
27893 ** SQLite to access the file will not know that the journal exists (because
27894 ** the directory entry for the journal was never created) and the transaction
27895 ** will not roll back - possibly leading to database corruption.
27896 */
27897 static int unixSync(sqlite3_file *id, int flags){
27898   int rc;
27899   unixFile *pFile = (unixFile*)id;
27900 
27901   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
27902   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
27903 
27904   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
27905   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
27906       || (flags&0x0F)==SQLITE_SYNC_FULL
27907   );
27908 
27909   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
27910   ** line is to test that doing so does not cause any problems.
27911   */
27912   SimulateDiskfullError( return SQLITE_FULL );
27913 
27914   assert( pFile );
27915   OSTRACE(("SYNC    %-3d\n", pFile->h));
27916   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
27917   SimulateIOError( rc=1 );
27918   if( rc ){
27919     pFile->lastErrno = errno;
27920     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
27921   }
27922 
27923   /* Also fsync the directory containing the file if the DIRSYNC flag
27924   ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
27925   ** are unable to fsync a directory, so ignore errors on the fsync.
27926   */
27927   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
27928     int dirfd;
27929     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
27930             HAVE_FULLFSYNC, isFullsync));
27931     rc = osOpenDirectory(pFile->zPath, &dirfd);
27932     if( rc==SQLITE_OK && dirfd>=0 ){
27933       full_fsync(dirfd, 0, 0);
27934       robust_close(pFile, dirfd, __LINE__);
27935     }else if( rc==SQLITE_CANTOPEN ){
27936       rc = SQLITE_OK;
27937     }
27938     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
27939   }
27940   return rc;
27941 }
27942 
27943 /*
27944 ** Truncate an open file to a specified size
27945 */
27946 static int unixTruncate(sqlite3_file *id, i64 nByte){
27947   unixFile *pFile = (unixFile *)id;
27948   int rc;
27949   assert( pFile );
27950   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
27951 
27952   /* If the user has configured a chunk-size for this file, truncate the
27953   ** file so that it consists of an integer number of chunks (i.e. the
27954   ** actual file size after the operation may be larger than the requested
27955   ** size).
27956   */
27957   if( pFile->szChunk ){
27958     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
27959   }
27960 
27961   rc = robust_ftruncate(pFile->h, (off_t)nByte);
27962   if( rc ){
27963     pFile->lastErrno = errno;
27964     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
27965   }else{
27966 #ifndef NDEBUG
27967     /* If we are doing a normal write to a database file (as opposed to
27968     ** doing a hot-journal rollback or a write to some file other than a
27969     ** normal database file) and we truncate the file to zero length,
27970     ** that effectively updates the change counter.  This might happen
27971     ** when restoring a database using the backup API from a zero-length
27972     ** source.
27973     */
27974     if( pFile->inNormalWrite && nByte==0 ){
27975       pFile->transCntrChng = 1;
27976     }
27977 #endif
27978 
27979     return SQLITE_OK;
27980   }
27981 }
27982 
27983 /*
27984 ** Determine the current size of a file in bytes
27985 */
27986 static int unixFileSize(sqlite3_file *id, i64 *pSize){
27987   int rc;
27988   struct stat buf;
27989   assert( id );
27990   rc = osFstat(((unixFile*)id)->h, &buf);
27991   SimulateIOError( rc=1 );
27992   if( rc!=0 ){
27993     ((unixFile*)id)->lastErrno = errno;
27994     return SQLITE_IOERR_FSTAT;
27995   }
27996   *pSize = buf.st_size;
27997 
27998   /* When opening a zero-size database, the findInodeInfo() procedure
27999   ** writes a single byte into that file in order to work around a bug
28000   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28001   ** layers, we need to report this file size as zero even though it is
28002   ** really 1.   Ticket #3260.
28003   */
28004   if( *pSize==1 ) *pSize = 0;
28005 
28006 
28007   return SQLITE_OK;
28008 }
28009 
28010 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28011 /*
28012 ** Handler for proxy-locking file-control verbs.  Defined below in the
28013 ** proxying locking division.
28014 */
28015 static int proxyFileControl(sqlite3_file*,int,void*);
28016 #endif
28017 
28018 /*
28019 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28020 ** file-control operation.  Enlarge the database to nBytes in size
28021 ** (rounded up to the next chunk-size).  If the database is already
28022 ** nBytes or larger, this routine is a no-op.
28023 */
28024 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28025   if( pFile->szChunk>0 ){
28026     i64 nSize;                    /* Required file size */
28027     struct stat buf;              /* Used to hold return values of fstat() */
28028 
28029     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28030 
28031     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28032     if( nSize>(i64)buf.st_size ){
28033 
28034 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28035       /* The code below is handling the return value of osFallocate()
28036       ** correctly. posix_fallocate() is defined to "returns zero on success,
28037       ** or an error number on  failure". See the manpage for details. */
28038       int err;
28039       do{
28040         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28041       }while( err==EINTR );
28042       if( err ) return SQLITE_IOERR_WRITE;
28043 #else
28044       /* If the OS does not have posix_fallocate(), fake it. First use
28045       ** ftruncate() to set the file size, then write a single byte to
28046       ** the last byte in each block within the extended region. This
28047       ** is the same technique used by glibc to implement posix_fallocate()
28048       ** on systems that do not have a real fallocate() system call.
28049       */
28050       int nBlk = buf.st_blksize;  /* File-system block size */
28051       i64 iWrite;                 /* Next offset to write to */
28052 
28053       if( robust_ftruncate(pFile->h, nSize) ){
28054         pFile->lastErrno = errno;
28055         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28056       }
28057       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28058       while( iWrite<nSize ){
28059         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28060         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28061         iWrite += nBlk;
28062       }
28063 #endif
28064     }
28065   }
28066 
28067   return SQLITE_OK;
28068 }
28069 
28070 /*
28071 ** Information and control of an open file handle.
28072 */
28073 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28074   unixFile *pFile = (unixFile*)id;
28075   switch( op ){
28076     case SQLITE_FCNTL_LOCKSTATE: {
28077       *(int*)pArg = pFile->eFileLock;
28078       return SQLITE_OK;
28079     }
28080     case SQLITE_LAST_ERRNO: {
28081       *(int*)pArg = pFile->lastErrno;
28082       return SQLITE_OK;
28083     }
28084     case SQLITE_FCNTL_CHUNK_SIZE: {
28085       pFile->szChunk = *(int *)pArg;
28086       return SQLITE_OK;
28087     }
28088     case SQLITE_FCNTL_SIZE_HINT: {
28089       int rc;
28090       SimulateIOErrorBenign(1);
28091       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28092       SimulateIOErrorBenign(0);
28093       return rc;
28094     }
28095     case SQLITE_FCNTL_PERSIST_WAL: {
28096       int bPersist = *(int*)pArg;
28097       if( bPersist<0 ){
28098         *(int*)pArg = (pFile->ctrlFlags & UNIXFILE_PERSIST_WAL)!=0;
28099       }else if( bPersist==0 ){
28100         pFile->ctrlFlags &= ~UNIXFILE_PERSIST_WAL;
28101       }else{
28102         pFile->ctrlFlags |= UNIXFILE_PERSIST_WAL;
28103       }
28104       return SQLITE_OK;
28105     }
28106 #ifndef NDEBUG
28107     /* The pager calls this method to signal that it has done
28108     ** a rollback and that the database is therefore unchanged and
28109     ** it hence it is OK for the transaction change counter to be
28110     ** unchanged.
28111     */
28112     case SQLITE_FCNTL_DB_UNCHANGED: {
28113       ((unixFile*)id)->dbUpdate = 0;
28114       return SQLITE_OK;
28115     }
28116 #endif
28117 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28118     case SQLITE_SET_LOCKPROXYFILE:
28119     case SQLITE_GET_LOCKPROXYFILE: {
28120       return proxyFileControl(id,op,pArg);
28121     }
28122 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28123     case SQLITE_FCNTL_SYNC_OMITTED: {
28124       return SQLITE_OK;  /* A no-op */
28125     }
28126   }
28127   return SQLITE_NOTFOUND;
28128 }
28129 
28130 /*
28131 ** Return the sector size in bytes of the underlying block device for
28132 ** the specified file. This is almost always 512 bytes, but may be
28133 ** larger for some devices.
28134 **
28135 ** SQLite code assumes this function cannot fail. It also assumes that
28136 ** if two files are created in the same file-system directory (i.e.
28137 ** a database and its journal file) that the sector size will be the
28138 ** same for both.
28139 */
28140 static int unixSectorSize(sqlite3_file *NotUsed){
28141   UNUSED_PARAMETER(NotUsed);
28142   return SQLITE_DEFAULT_SECTOR_SIZE;
28143 }
28144 
28145 /*
28146 ** Return the device characteristics for the file. This is always 0 for unix.
28147 */
28148 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
28149   UNUSED_PARAMETER(NotUsed);
28150   return 0;
28151 }
28152 
28153 #ifndef SQLITE_OMIT_WAL
28154 
28155 
28156 /*
28157 ** Object used to represent an shared memory buffer.
28158 **
28159 ** When multiple threads all reference the same wal-index, each thread
28160 ** has its own unixShm object, but they all point to a single instance
28161 ** of this unixShmNode object.  In other words, each wal-index is opened
28162 ** only once per process.
28163 **
28164 ** Each unixShmNode object is connected to a single unixInodeInfo object.
28165 ** We could coalesce this object into unixInodeInfo, but that would mean
28166 ** every open file that does not use shared memory (in other words, most
28167 ** open files) would have to carry around this extra information.  So
28168 ** the unixInodeInfo object contains a pointer to this unixShmNode object
28169 ** and the unixShmNode object is created only when needed.
28170 **
28171 ** unixMutexHeld() must be true when creating or destroying
28172 ** this object or while reading or writing the following fields:
28173 **
28174 **      nRef
28175 **
28176 ** The following fields are read-only after the object is created:
28177 **
28178 **      fid
28179 **      zFilename
28180 **
28181 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28182 ** unixMutexHeld() is true when reading or writing any other field
28183 ** in this structure.
28184 */
28185 struct unixShmNode {
28186   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28187   sqlite3_mutex *mutex;      /* Mutex to access this object */
28188   char *zFilename;           /* Name of the mmapped file */
28189   int h;                     /* Open file descriptor */
28190   int szRegion;              /* Size of shared-memory regions */
28191   u16 nRegion;               /* Size of array apRegion */
28192   u8 isReadonly;             /* True if read-only */
28193   char **apRegion;           /* Array of mapped shared-memory regions */
28194   int nRef;                  /* Number of unixShm objects pointing to this */
28195   unixShm *pFirst;           /* All unixShm objects pointing to this */
28196 #ifdef SQLITE_DEBUG
28197   u8 exclMask;               /* Mask of exclusive locks held */
28198   u8 sharedMask;             /* Mask of shared locks held */
28199   u8 nextShmId;              /* Next available unixShm.id value */
28200 #endif
28201 };
28202 
28203 /*
28204 ** Structure used internally by this VFS to record the state of an
28205 ** open shared memory connection.
28206 **
28207 ** The following fields are initialized when this object is created and
28208 ** are read-only thereafter:
28209 **
28210 **    unixShm.pFile
28211 **    unixShm.id
28212 **
28213 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
28214 ** while accessing any read/write fields.
28215 */
28216 struct unixShm {
28217   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28218   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28219   u8 hasMutex;               /* True if holding the unixShmNode mutex */
28220   u8 id;                     /* Id of this connection within its unixShmNode */
28221   u16 sharedMask;            /* Mask of shared locks held */
28222   u16 exclMask;              /* Mask of exclusive locks held */
28223 };
28224 
28225 /*
28226 ** Constants used for locking
28227 */
28228 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28229 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28230 
28231 /*
28232 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28233 **
28234 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28235 ** otherwise.
28236 */
28237 static int unixShmSystemLock(
28238   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28239   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28240   int ofst,              /* First byte of the locking range */
28241   int n                  /* Number of bytes to lock */
28242 ){
28243   struct flock f;       /* The posix advisory locking structure */
28244   int rc = SQLITE_OK;   /* Result code form fcntl() */
28245 
28246   /* Access to the unixShmNode object is serialized by the caller */
28247   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28248 
28249   /* Shared locks never span more than one byte */
28250   assert( n==1 || lockType!=F_RDLCK );
28251 
28252   /* Locks are within range */
28253   assert( n>=1 && n<SQLITE_SHM_NLOCK );
28254 
28255   if( pShmNode->h>=0 ){
28256     /* Initialize the locking parameters */
28257     memset(&f, 0, sizeof(f));
28258     f.l_type = lockType;
28259     f.l_whence = SEEK_SET;
28260     f.l_start = ofst;
28261     f.l_len = n;
28262 
28263     rc = osFcntl(pShmNode->h, F_SETLK, &f);
28264     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28265   }
28266 
28267   /* Update the global lock state and do debug tracing */
28268 #ifdef SQLITE_DEBUG
28269   { u16 mask;
28270   OSTRACE(("SHM-LOCK "));
28271   mask = (1<<(ofst+n)) - (1<<ofst);
28272   if( rc==SQLITE_OK ){
28273     if( lockType==F_UNLCK ){
28274       OSTRACE(("unlock %d ok", ofst));
28275       pShmNode->exclMask &= ~mask;
28276       pShmNode->sharedMask &= ~mask;
28277     }else if( lockType==F_RDLCK ){
28278       OSTRACE(("read-lock %d ok", ofst));
28279       pShmNode->exclMask &= ~mask;
28280       pShmNode->sharedMask |= mask;
28281     }else{
28282       assert( lockType==F_WRLCK );
28283       OSTRACE(("write-lock %d ok", ofst));
28284       pShmNode->exclMask |= mask;
28285       pShmNode->sharedMask &= ~mask;
28286     }
28287   }else{
28288     if( lockType==F_UNLCK ){
28289       OSTRACE(("unlock %d failed", ofst));
28290     }else if( lockType==F_RDLCK ){
28291       OSTRACE(("read-lock failed"));
28292     }else{
28293       assert( lockType==F_WRLCK );
28294       OSTRACE(("write-lock %d failed", ofst));
28295     }
28296   }
28297   OSTRACE((" - afterwards %03x,%03x\n",
28298            pShmNode->sharedMask, pShmNode->exclMask));
28299   }
28300 #endif
28301 
28302   return rc;
28303 }
28304 
28305 
28306 /*
28307 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28308 **
28309 ** This is not a VFS shared-memory method; it is a utility function called
28310 ** by VFS shared-memory methods.
28311 */
28312 static void unixShmPurge(unixFile *pFd){
28313   unixShmNode *p = pFd->pInode->pShmNode;
28314   assert( unixMutexHeld() );
28315   if( p && p->nRef==0 ){
28316     int i;
28317     assert( p->pInode==pFd->pInode );
28318     sqlite3_mutex_free(p->mutex);
28319     for(i=0; i<p->nRegion; i++){
28320       if( p->h>=0 ){
28321         munmap(p->apRegion[i], p->szRegion);
28322       }else{
28323         sqlite3_free(p->apRegion[i]);
28324       }
28325     }
28326     sqlite3_free(p->apRegion);
28327     if( p->h>=0 ){
28328       robust_close(pFd, p->h, __LINE__);
28329       p->h = -1;
28330     }
28331     p->pInode->pShmNode = 0;
28332     sqlite3_free(p);
28333   }
28334 }
28335 
28336 /*
28337 ** Open a shared-memory area associated with open database file pDbFd.
28338 ** This particular implementation uses mmapped files.
28339 **
28340 ** The file used to implement shared-memory is in the same directory
28341 ** as the open database file and has the same name as the open database
28342 ** file with the "-shm" suffix added.  For example, if the database file
28343 ** is "/home/user1/config.db" then the file that is created and mmapped
28344 ** for shared memory will be called "/home/user1/config.db-shm".
28345 **
28346 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
28347 ** some other tmpfs mount. But if a file in a different directory
28348 ** from the database file is used, then differing access permissions
28349 ** or a chroot() might cause two different processes on the same
28350 ** database to end up using different files for shared memory -
28351 ** meaning that their memory would not really be shared - resulting
28352 ** in database corruption.  Nevertheless, this tmpfs file usage
28353 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28354 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28355 ** option results in an incompatible build of SQLite;  builds of SQLite
28356 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28357 ** same database file at the same time, database corruption will likely
28358 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28359 ** "unsupported" and may go away in a future SQLite release.
28360 **
28361 ** When opening a new shared-memory file, if no other instances of that
28362 ** file are currently open, in this process or in other processes, then
28363 ** the file must be truncated to zero length or have its header cleared.
28364 **
28365 ** If the original database file (pDbFd) is using the "unix-excl" VFS
28366 ** that means that an exclusive lock is held on the database file and
28367 ** that no other processes are able to read or write the database.  In
28368 ** that case, we do not really need shared memory.  No shared memory
28369 ** file is created.  The shared memory will be simulated with heap memory.
28370 */
28371 static int unixOpenSharedMemory(unixFile *pDbFd){
28372   struct unixShm *p = 0;          /* The connection to be opened */
28373   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
28374   int rc;                         /* Result code */
28375   unixInodeInfo *pInode;          /* The inode of fd */
28376   char *zShmFilename;             /* Name of the file used for SHM */
28377   int nShmFilename;               /* Size of the SHM filename in bytes */
28378 
28379   /* Allocate space for the new unixShm object. */
28380   p = sqlite3_malloc( sizeof(*p) );
28381   if( p==0 ) return SQLITE_NOMEM;
28382   memset(p, 0, sizeof(*p));
28383   assert( pDbFd->pShm==0 );
28384 
28385   /* Check to see if a unixShmNode object already exists. Reuse an existing
28386   ** one if present. Create a new one if necessary.
28387   */
28388   unixEnterMutex();
28389   pInode = pDbFd->pInode;
28390   pShmNode = pInode->pShmNode;
28391   if( pShmNode==0 ){
28392     struct stat sStat;                 /* fstat() info for database file */
28393 
28394     /* Call fstat() to figure out the permissions on the database file. If
28395     ** a new *-shm file is created, an attempt will be made to create it
28396     ** with the same permissions. The actual permissions the file is created
28397     ** with are subject to the current umask setting.
28398     */
28399     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28400       rc = SQLITE_IOERR_FSTAT;
28401       goto shm_open_err;
28402     }
28403 
28404 #ifdef SQLITE_SHM_DIRECTORY
28405     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 30;
28406 #else
28407     nShmFilename = 5 + (int)strlen(pDbFd->zPath);
28408 #endif
28409     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28410     if( pShmNode==0 ){
28411       rc = SQLITE_NOMEM;
28412       goto shm_open_err;
28413     }
28414     memset(pShmNode, 0, sizeof(*pShmNode));
28415     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28416 #ifdef SQLITE_SHM_DIRECTORY
28417     sqlite3_snprintf(nShmFilename, zShmFilename,
28418                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28419                      (u32)sStat.st_ino, (u32)sStat.st_dev);
28420 #else
28421     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28422     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28423 #endif
28424     pShmNode->h = -1;
28425     pDbFd->pInode->pShmNode = pShmNode;
28426     pShmNode->pInode = pDbFd->pInode;
28427     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28428     if( pShmNode->mutex==0 ){
28429       rc = SQLITE_NOMEM;
28430       goto shm_open_err;
28431     }
28432 
28433     if( pInode->bProcessLock==0 ){
28434       pShmNode->h = robust_open(zShmFilename, O_RDWR|O_CREAT,
28435                                (sStat.st_mode & 0777));
28436       if( pShmNode->h<0 ){
28437         const char *zRO;
28438         zRO = sqlite3_uri_parameter(pDbFd->zPath, "readonly_shm");
28439         if( zRO && sqlite3GetBoolean(zRO) ){
28440           pShmNode->h = robust_open(zShmFilename, O_RDONLY,
28441                                     (sStat.st_mode & 0777));
28442           pShmNode->isReadonly = 1;
28443         }
28444         if( pShmNode->h<0 ){
28445           rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28446           goto shm_open_err;
28447         }
28448       }
28449 
28450       /* Check to see if another process is holding the dead-man switch.
28451       ** If not, truncate the file to zero length.
28452       */
28453       rc = SQLITE_OK;
28454       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28455         if( robust_ftruncate(pShmNode->h, 0) ){
28456           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28457         }
28458       }
28459       if( rc==SQLITE_OK ){
28460         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28461       }
28462       if( rc ) goto shm_open_err;
28463     }
28464   }
28465 
28466   /* Make the new connection a child of the unixShmNode */
28467   p->pShmNode = pShmNode;
28468 #ifdef SQLITE_DEBUG
28469   p->id = pShmNode->nextShmId++;
28470 #endif
28471   pShmNode->nRef++;
28472   pDbFd->pShm = p;
28473   unixLeaveMutex();
28474 
28475   /* The reference count on pShmNode has already been incremented under
28476   ** the cover of the unixEnterMutex() mutex and the pointer from the
28477   ** new (struct unixShm) object to the pShmNode has been set. All that is
28478   ** left to do is to link the new object into the linked list starting
28479   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
28480   ** mutex.
28481   */
28482   sqlite3_mutex_enter(pShmNode->mutex);
28483   p->pNext = pShmNode->pFirst;
28484   pShmNode->pFirst = p;
28485   sqlite3_mutex_leave(pShmNode->mutex);
28486   return SQLITE_OK;
28487 
28488   /* Jump here on any error */
28489 shm_open_err:
28490   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
28491   sqlite3_free(p);
28492   unixLeaveMutex();
28493   return rc;
28494 }
28495 
28496 /*
28497 ** This function is called to obtain a pointer to region iRegion of the
28498 ** shared-memory associated with the database file fd. Shared-memory regions
28499 ** are numbered starting from zero. Each shared-memory region is szRegion
28500 ** bytes in size.
28501 **
28502 ** If an error occurs, an error code is returned and *pp is set to NULL.
28503 **
28504 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
28505 ** region has not been allocated (by any client, including one running in a
28506 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
28507 ** bExtend is non-zero and the requested shared-memory region has not yet
28508 ** been allocated, it is allocated by this function.
28509 **
28510 ** If the shared-memory region has already been allocated or is allocated by
28511 ** this call as described above, then it is mapped into this processes
28512 ** address space (if it is not already), *pp is set to point to the mapped
28513 ** memory and SQLITE_OK returned.
28514 */
28515 static int unixShmMap(
28516   sqlite3_file *fd,               /* Handle open on database file */
28517   int iRegion,                    /* Region to retrieve */
28518   int szRegion,                   /* Size of regions */
28519   int bExtend,                    /* True to extend file if necessary */
28520   void volatile **pp              /* OUT: Mapped memory */
28521 ){
28522   unixFile *pDbFd = (unixFile*)fd;
28523   unixShm *p;
28524   unixShmNode *pShmNode;
28525   int rc = SQLITE_OK;
28526 
28527   /* If the shared-memory file has not yet been opened, open it now. */
28528   if( pDbFd->pShm==0 ){
28529     rc = unixOpenSharedMemory(pDbFd);
28530     if( rc!=SQLITE_OK ) return rc;
28531   }
28532 
28533   p = pDbFd->pShm;
28534   pShmNode = p->pShmNode;
28535   sqlite3_mutex_enter(pShmNode->mutex);
28536   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
28537   assert( pShmNode->pInode==pDbFd->pInode );
28538   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28539   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28540 
28541   if( pShmNode->nRegion<=iRegion ){
28542     char **apNew;                      /* New apRegion[] array */
28543     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
28544     struct stat sStat;                 /* Used by fstat() */
28545 
28546     pShmNode->szRegion = szRegion;
28547 
28548     if( pShmNode->h>=0 ){
28549       /* The requested region is not mapped into this processes address space.
28550       ** Check to see if it has been allocated (i.e. if the wal-index file is
28551       ** large enough to contain the requested region).
28552       */
28553       if( osFstat(pShmNode->h, &sStat) ){
28554         rc = SQLITE_IOERR_SHMSIZE;
28555         goto shmpage_out;
28556       }
28557 
28558       if( sStat.st_size<nByte ){
28559         /* The requested memory region does not exist. If bExtend is set to
28560         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
28561         **
28562         ** Alternatively, if bExtend is true, use ftruncate() to allocate
28563         ** the requested memory region.
28564         */
28565         if( !bExtend ) goto shmpage_out;
28566         if( robust_ftruncate(pShmNode->h, nByte) ){
28567           rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
28568                             pShmNode->zFilename);
28569           goto shmpage_out;
28570         }
28571       }
28572     }
28573 
28574     /* Map the requested memory region into this processes address space. */
28575     apNew = (char **)sqlite3_realloc(
28576         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
28577     );
28578     if( !apNew ){
28579       rc = SQLITE_IOERR_NOMEM;
28580       goto shmpage_out;
28581     }
28582     pShmNode->apRegion = apNew;
28583     while(pShmNode->nRegion<=iRegion){
28584       void *pMem;
28585       if( pShmNode->h>=0 ){
28586         pMem = mmap(0, szRegion,
28587             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
28588             MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
28589         );
28590         if( pMem==MAP_FAILED ){
28591           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
28592           goto shmpage_out;
28593         }
28594       }else{
28595         pMem = sqlite3_malloc(szRegion);
28596         if( pMem==0 ){
28597           rc = SQLITE_NOMEM;
28598           goto shmpage_out;
28599         }
28600         memset(pMem, 0, szRegion);
28601       }
28602       pShmNode->apRegion[pShmNode->nRegion] = pMem;
28603       pShmNode->nRegion++;
28604     }
28605   }
28606 
28607 shmpage_out:
28608   if( pShmNode->nRegion>iRegion ){
28609     *pp = pShmNode->apRegion[iRegion];
28610   }else{
28611     *pp = 0;
28612   }
28613   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
28614   sqlite3_mutex_leave(pShmNode->mutex);
28615   return rc;
28616 }
28617 
28618 /*
28619 ** Change the lock state for a shared-memory segment.
28620 **
28621 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
28622 ** different here than in posix.  In xShmLock(), one can go from unlocked
28623 ** to shared and back or from unlocked to exclusive and back.  But one may
28624 ** not go from shared to exclusive or from exclusive to shared.
28625 */
28626 static int unixShmLock(
28627   sqlite3_file *fd,          /* Database file holding the shared memory */
28628   int ofst,                  /* First lock to acquire or release */
28629   int n,                     /* Number of locks to acquire or release */
28630   int flags                  /* What to do with the lock */
28631 ){
28632   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
28633   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
28634   unixShm *pX;                          /* For looping over all siblings */
28635   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
28636   int rc = SQLITE_OK;                   /* Result code */
28637   u16 mask;                             /* Mask of locks to take or release */
28638 
28639   assert( pShmNode==pDbFd->pInode->pShmNode );
28640   assert( pShmNode->pInode==pDbFd->pInode );
28641   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
28642   assert( n>=1 );
28643   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
28644        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
28645        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
28646        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
28647   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
28648   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
28649   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
28650 
28651   mask = (1<<(ofst+n)) - (1<<ofst);
28652   assert( n>1 || mask==(1<<ofst) );
28653   sqlite3_mutex_enter(pShmNode->mutex);
28654   if( flags & SQLITE_SHM_UNLOCK ){
28655     u16 allMask = 0; /* Mask of locks held by siblings */
28656 
28657     /* See if any siblings hold this same lock */
28658     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28659       if( pX==p ) continue;
28660       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
28661       allMask |= pX->sharedMask;
28662     }
28663 
28664     /* Unlock the system-level locks */
28665     if( (mask & allMask)==0 ){
28666       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
28667     }else{
28668       rc = SQLITE_OK;
28669     }
28670 
28671     /* Undo the local locks */
28672     if( rc==SQLITE_OK ){
28673       p->exclMask &= ~mask;
28674       p->sharedMask &= ~mask;
28675     }
28676   }else if( flags & SQLITE_SHM_SHARED ){
28677     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
28678 
28679     /* Find out which shared locks are already held by sibling connections.
28680     ** If any sibling already holds an exclusive lock, go ahead and return
28681     ** SQLITE_BUSY.
28682     */
28683     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28684       if( (pX->exclMask & mask)!=0 ){
28685         rc = SQLITE_BUSY;
28686         break;
28687       }
28688       allShared |= pX->sharedMask;
28689     }
28690 
28691     /* Get shared locks at the system level, if necessary */
28692     if( rc==SQLITE_OK ){
28693       if( (allShared & mask)==0 ){
28694         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
28695       }else{
28696         rc = SQLITE_OK;
28697       }
28698     }
28699 
28700     /* Get the local shared locks */
28701     if( rc==SQLITE_OK ){
28702       p->sharedMask |= mask;
28703     }
28704   }else{
28705     /* Make sure no sibling connections hold locks that will block this
28706     ** lock.  If any do, return SQLITE_BUSY right away.
28707     */
28708     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
28709       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
28710         rc = SQLITE_BUSY;
28711         break;
28712       }
28713     }
28714 
28715     /* Get the exclusive locks at the system level.  Then if successful
28716     ** also mark the local connection as being locked.
28717     */
28718     if( rc==SQLITE_OK ){
28719       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
28720       if( rc==SQLITE_OK ){
28721         assert( (p->sharedMask & mask)==0 );
28722         p->exclMask |= mask;
28723       }
28724     }
28725   }
28726   sqlite3_mutex_leave(pShmNode->mutex);
28727   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
28728            p->id, getpid(), p->sharedMask, p->exclMask));
28729   return rc;
28730 }
28731 
28732 /*
28733 ** Implement a memory barrier or memory fence on shared memory.
28734 **
28735 ** All loads and stores begun before the barrier must complete before
28736 ** any load or store begun after the barrier.
28737 */
28738 static void unixShmBarrier(
28739   sqlite3_file *fd                /* Database file holding the shared memory */
28740 ){
28741   UNUSED_PARAMETER(fd);
28742   unixEnterMutex();
28743   unixLeaveMutex();
28744 }
28745 
28746 /*
28747 ** Close a connection to shared-memory.  Delete the underlying
28748 ** storage if deleteFlag is true.
28749 **
28750 ** If there is no shared memory associated with the connection then this
28751 ** routine is a harmless no-op.
28752 */
28753 static int unixShmUnmap(
28754   sqlite3_file *fd,               /* The underlying database file */
28755   int deleteFlag                  /* Delete shared-memory if true */
28756 ){
28757   unixShm *p;                     /* The connection to be closed */
28758   unixShmNode *pShmNode;          /* The underlying shared-memory file */
28759   unixShm **pp;                   /* For looping over sibling connections */
28760   unixFile *pDbFd;                /* The underlying database file */
28761 
28762   pDbFd = (unixFile*)fd;
28763   p = pDbFd->pShm;
28764   if( p==0 ) return SQLITE_OK;
28765   pShmNode = p->pShmNode;
28766 
28767   assert( pShmNode==pDbFd->pInode->pShmNode );
28768   assert( pShmNode->pInode==pDbFd->pInode );
28769 
28770   /* Remove connection p from the set of connections associated
28771   ** with pShmNode */
28772   sqlite3_mutex_enter(pShmNode->mutex);
28773   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
28774   *pp = p->pNext;
28775 
28776   /* Free the connection p */
28777   sqlite3_free(p);
28778   pDbFd->pShm = 0;
28779   sqlite3_mutex_leave(pShmNode->mutex);
28780 
28781   /* If pShmNode->nRef has reached 0, then close the underlying
28782   ** shared-memory file, too */
28783   unixEnterMutex();
28784   assert( pShmNode->nRef>0 );
28785   pShmNode->nRef--;
28786   if( pShmNode->nRef==0 ){
28787     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
28788     unixShmPurge(pDbFd);
28789   }
28790   unixLeaveMutex();
28791 
28792   return SQLITE_OK;
28793 }
28794 
28795 
28796 #else
28797 # define unixShmMap     0
28798 # define unixShmLock    0
28799 # define unixShmBarrier 0
28800 # define unixShmUnmap   0
28801 #endif /* #ifndef SQLITE_OMIT_WAL */
28802 
28803 /*
28804 ** Here ends the implementation of all sqlite3_file methods.
28805 **
28806 ********************** End sqlite3_file Methods *******************************
28807 ******************************************************************************/
28808 
28809 /*
28810 ** This division contains definitions of sqlite3_io_methods objects that
28811 ** implement various file locking strategies.  It also contains definitions
28812 ** of "finder" functions.  A finder-function is used to locate the appropriate
28813 ** sqlite3_io_methods object for a particular database file.  The pAppData
28814 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
28815 ** the correct finder-function for that VFS.
28816 **
28817 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
28818 ** object.  The only interesting finder-function is autolockIoFinder, which
28819 ** looks at the filesystem type and tries to guess the best locking
28820 ** strategy from that.
28821 **
28822 ** For finder-funtion F, two objects are created:
28823 **
28824 **    (1) The real finder-function named "FImpt()".
28825 **
28826 **    (2) A constant pointer to this function named just "F".
28827 **
28828 **
28829 ** A pointer to the F pointer is used as the pAppData value for VFS
28830 ** objects.  We have to do this instead of letting pAppData point
28831 ** directly at the finder-function since C90 rules prevent a void*
28832 ** from be cast into a function pointer.
28833 **
28834 **
28835 ** Each instance of this macro generates two objects:
28836 **
28837 **   *  A constant sqlite3_io_methods object call METHOD that has locking
28838 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
28839 **
28840 **   *  An I/O method finder function called FINDER that returns a pointer
28841 **      to the METHOD object in the previous bullet.
28842 */
28843 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
28844 static const sqlite3_io_methods METHOD = {                                   \
28845    VERSION,                    /* iVersion */                                \
28846    CLOSE,                      /* xClose */                                  \
28847    unixRead,                   /* xRead */                                   \
28848    unixWrite,                  /* xWrite */                                  \
28849    unixTruncate,               /* xTruncate */                               \
28850    unixSync,                   /* xSync */                                   \
28851    unixFileSize,               /* xFileSize */                               \
28852    LOCK,                       /* xLock */                                   \
28853    UNLOCK,                     /* xUnlock */                                 \
28854    CKLOCK,                     /* xCheckReservedLock */                      \
28855    unixFileControl,            /* xFileControl */                            \
28856    unixSectorSize,             /* xSectorSize */                             \
28857    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
28858    unixShmMap,                 /* xShmMap */                                 \
28859    unixShmLock,                /* xShmLock */                                \
28860    unixShmBarrier,             /* xShmBarrier */                             \
28861    unixShmUnmap                /* xShmUnmap */                               \
28862 };                                                                           \
28863 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
28864   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
28865   return &METHOD;                                                            \
28866 }                                                                            \
28867 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
28868     = FINDER##Impl;
28869 
28870 /*
28871 ** Here are all of the sqlite3_io_methods objects for each of the
28872 ** locking strategies.  Functions that return pointers to these methods
28873 ** are also created.
28874 */
28875 IOMETHODS(
28876   posixIoFinder,            /* Finder function name */
28877   posixIoMethods,           /* sqlite3_io_methods object name */
28878   2,                        /* shared memory is enabled */
28879   unixClose,                /* xClose method */
28880   unixLock,                 /* xLock method */
28881   unixUnlock,               /* xUnlock method */
28882   unixCheckReservedLock     /* xCheckReservedLock method */
28883 )
28884 IOMETHODS(
28885   nolockIoFinder,           /* Finder function name */
28886   nolockIoMethods,          /* sqlite3_io_methods object name */
28887   1,                        /* shared memory is disabled */
28888   nolockClose,              /* xClose method */
28889   nolockLock,               /* xLock method */
28890   nolockUnlock,             /* xUnlock method */
28891   nolockCheckReservedLock   /* xCheckReservedLock method */
28892 )
28893 IOMETHODS(
28894   dotlockIoFinder,          /* Finder function name */
28895   dotlockIoMethods,         /* sqlite3_io_methods object name */
28896   1,                        /* shared memory is disabled */
28897   dotlockClose,             /* xClose method */
28898   dotlockLock,              /* xLock method */
28899   dotlockUnlock,            /* xUnlock method */
28900   dotlockCheckReservedLock  /* xCheckReservedLock method */
28901 )
28902 
28903 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28904 IOMETHODS(
28905   flockIoFinder,            /* Finder function name */
28906   flockIoMethods,           /* sqlite3_io_methods object name */
28907   1,                        /* shared memory is disabled */
28908   flockClose,               /* xClose method */
28909   flockLock,                /* xLock method */
28910   flockUnlock,              /* xUnlock method */
28911   flockCheckReservedLock    /* xCheckReservedLock method */
28912 )
28913 #endif
28914 
28915 #if OS_VXWORKS
28916 IOMETHODS(
28917   semIoFinder,              /* Finder function name */
28918   semIoMethods,             /* sqlite3_io_methods object name */
28919   1,                        /* shared memory is disabled */
28920   semClose,                 /* xClose method */
28921   semLock,                  /* xLock method */
28922   semUnlock,                /* xUnlock method */
28923   semCheckReservedLock      /* xCheckReservedLock method */
28924 )
28925 #endif
28926 
28927 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28928 IOMETHODS(
28929   afpIoFinder,              /* Finder function name */
28930   afpIoMethods,             /* sqlite3_io_methods object name */
28931   1,                        /* shared memory is disabled */
28932   afpClose,                 /* xClose method */
28933   afpLock,                  /* xLock method */
28934   afpUnlock,                /* xUnlock method */
28935   afpCheckReservedLock      /* xCheckReservedLock method */
28936 )
28937 #endif
28938 
28939 /*
28940 ** The proxy locking method is a "super-method" in the sense that it
28941 ** opens secondary file descriptors for the conch and lock files and
28942 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28943 ** secondary files.  For this reason, the division that implements
28944 ** proxy locking is located much further down in the file.  But we need
28945 ** to go ahead and define the sqlite3_io_methods and finder function
28946 ** for proxy locking here.  So we forward declare the I/O methods.
28947 */
28948 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28949 static int proxyClose(sqlite3_file*);
28950 static int proxyLock(sqlite3_file*, int);
28951 static int proxyUnlock(sqlite3_file*, int);
28952 static int proxyCheckReservedLock(sqlite3_file*, int*);
28953 IOMETHODS(
28954   proxyIoFinder,            /* Finder function name */
28955   proxyIoMethods,           /* sqlite3_io_methods object name */
28956   1,                        /* shared memory is disabled */
28957   proxyClose,               /* xClose method */
28958   proxyLock,                /* xLock method */
28959   proxyUnlock,              /* xUnlock method */
28960   proxyCheckReservedLock    /* xCheckReservedLock method */
28961 )
28962 #endif
28963 
28964 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28965 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28966 IOMETHODS(
28967   nfsIoFinder,               /* Finder function name */
28968   nfsIoMethods,              /* sqlite3_io_methods object name */
28969   1,                         /* shared memory is disabled */
28970   unixClose,                 /* xClose method */
28971   unixLock,                  /* xLock method */
28972   nfsUnlock,                 /* xUnlock method */
28973   unixCheckReservedLock      /* xCheckReservedLock method */
28974 )
28975 #endif
28976 
28977 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28978 /*
28979 ** This "finder" function attempts to determine the best locking strategy
28980 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28981 ** object that implements that strategy.
28982 **
28983 ** This is for MacOSX only.
28984 */
28985 static const sqlite3_io_methods *autolockIoFinderImpl(
28986   const char *filePath,    /* name of the database file */
28987   unixFile *pNew           /* open file object for the database file */
28988 ){
28989   static const struct Mapping {
28990     const char *zFilesystem;              /* Filesystem type name */
28991     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28992   } aMap[] = {
28993     { "hfs",    &posixIoMethods },
28994     { "ufs",    &posixIoMethods },
28995     { "afpfs",  &afpIoMethods },
28996     { "smbfs",  &afpIoMethods },
28997     { "webdav", &nolockIoMethods },
28998     { 0, 0 }
28999   };
29000   int i;
29001   struct statfs fsInfo;
29002   struct flock lockInfo;
29003 
29004   if( !filePath ){
29005     /* If filePath==NULL that means we are dealing with a transient file
29006     ** that does not need to be locked. */
29007     return &nolockIoMethods;
29008   }
29009   if( statfs(filePath, &fsInfo) != -1 ){
29010     if( fsInfo.f_flags & MNT_RDONLY ){
29011       return &nolockIoMethods;
29012     }
29013     for(i=0; aMap[i].zFilesystem; i++){
29014       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29015         return aMap[i].pMethods;
29016       }
29017     }
29018   }
29019 
29020   /* Default case. Handles, amongst others, "nfs".
29021   ** Test byte-range lock using fcntl(). If the call succeeds,
29022   ** assume that the file-system supports POSIX style locks.
29023   */
29024   lockInfo.l_len = 1;
29025   lockInfo.l_start = 0;
29026   lockInfo.l_whence = SEEK_SET;
29027   lockInfo.l_type = F_RDLCK;
29028   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29029     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29030       return &nfsIoMethods;
29031     } else {
29032       return &posixIoMethods;
29033     }
29034   }else{
29035     return &dotlockIoMethods;
29036   }
29037 }
29038 static const sqlite3_io_methods
29039   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29040 
29041 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29042 
29043 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29044 /*
29045 ** This "finder" function attempts to determine the best locking strategy
29046 ** for the database file "filePath".  It then returns the sqlite3_io_methods
29047 ** object that implements that strategy.
29048 **
29049 ** This is for VXWorks only.
29050 */
29051 static const sqlite3_io_methods *autolockIoFinderImpl(
29052   const char *filePath,    /* name of the database file */
29053   unixFile *pNew           /* the open file object */
29054 ){
29055   struct flock lockInfo;
29056 
29057   if( !filePath ){
29058     /* If filePath==NULL that means we are dealing with a transient file
29059     ** that does not need to be locked. */
29060     return &nolockIoMethods;
29061   }
29062 
29063   /* Test if fcntl() is supported and use POSIX style locks.
29064   ** Otherwise fall back to the named semaphore method.
29065   */
29066   lockInfo.l_len = 1;
29067   lockInfo.l_start = 0;
29068   lockInfo.l_whence = SEEK_SET;
29069   lockInfo.l_type = F_RDLCK;
29070   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29071     return &posixIoMethods;
29072   }else{
29073     return &semIoMethods;
29074   }
29075 }
29076 static const sqlite3_io_methods
29077   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29078 
29079 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29080 
29081 /*
29082 ** An abstract type for a pointer to a IO method finder function:
29083 */
29084 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29085 
29086 
29087 /****************************************************************************
29088 **************************** sqlite3_vfs methods ****************************
29089 **
29090 ** This division contains the implementation of methods on the
29091 ** sqlite3_vfs object.
29092 */
29093 
29094 /*
29095 ** Initialize the contents of the unixFile structure pointed to by pId.
29096 */
29097 static int fillInUnixFile(
29098   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29099   int h,                  /* Open file descriptor of file being opened */
29100   int syncDir,            /* True to sync directory on first sync */
29101   sqlite3_file *pId,      /* Write to the unixFile structure here */
29102   const char *zFilename,  /* Name of the file being opened */
29103   int noLock,             /* Omit locking if true */
29104   int isDelete,           /* Delete on close if true */
29105   int isReadOnly          /* True if the file is opened read-only */
29106 ){
29107   const sqlite3_io_methods *pLockingStyle;
29108   unixFile *pNew = (unixFile *)pId;
29109   int rc = SQLITE_OK;
29110 
29111   assert( pNew->pInode==NULL );
29112 
29113   /* Parameter isDelete is only used on vxworks. Express this explicitly
29114   ** here to prevent compiler warnings about unused parameters.
29115   */
29116   UNUSED_PARAMETER(isDelete);
29117 
29118   /* Usually the path zFilename should not be a relative pathname. The
29119   ** exception is when opening the proxy "conch" file in builds that
29120   ** include the special Apple locking styles.
29121   */
29122 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29123   assert( zFilename==0 || zFilename[0]=='/'
29124     || pVfs->pAppData==(void*)&autolockIoFinder );
29125 #else
29126   assert( zFilename==0 || zFilename[0]=='/' );
29127 #endif
29128 
29129   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29130   pNew->h = h;
29131   pNew->zPath = zFilename;
29132   if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29133     pNew->ctrlFlags = UNIXFILE_EXCL;
29134   }else{
29135     pNew->ctrlFlags = 0;
29136   }
29137   if( isReadOnly ){
29138     pNew->ctrlFlags |= UNIXFILE_RDONLY;
29139   }
29140   if( syncDir ){
29141     pNew->ctrlFlags |= UNIXFILE_DIRSYNC;
29142   }
29143 
29144 #if OS_VXWORKS
29145   pNew->pId = vxworksFindFileId(zFilename);
29146   if( pNew->pId==0 ){
29147     noLock = 1;
29148     rc = SQLITE_NOMEM;
29149   }
29150 #endif
29151 
29152   if( noLock ){
29153     pLockingStyle = &nolockIoMethods;
29154   }else{
29155     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29156 #if SQLITE_ENABLE_LOCKING_STYLE
29157     /* Cache zFilename in the locking context (AFP and dotlock override) for
29158     ** proxyLock activation is possible (remote proxy is based on db name)
29159     ** zFilename remains valid until file is closed, to support */
29160     pNew->lockingContext = (void*)zFilename;
29161 #endif
29162   }
29163 
29164   if( pLockingStyle == &posixIoMethods
29165 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29166     || pLockingStyle == &nfsIoMethods
29167 #endif
29168   ){
29169     unixEnterMutex();
29170     rc = findInodeInfo(pNew, &pNew->pInode);
29171     if( rc!=SQLITE_OK ){
29172       /* If an error occured in findInodeInfo(), close the file descriptor
29173       ** immediately, before releasing the mutex. findInodeInfo() may fail
29174       ** in two scenarios:
29175       **
29176       **   (a) A call to fstat() failed.
29177       **   (b) A malloc failed.
29178       **
29179       ** Scenario (b) may only occur if the process is holding no other
29180       ** file descriptors open on the same file. If there were other file
29181       ** descriptors on this file, then no malloc would be required by
29182       ** findInodeInfo(). If this is the case, it is quite safe to close
29183       ** handle h - as it is guaranteed that no posix locks will be released
29184       ** by doing so.
29185       **
29186       ** If scenario (a) caused the error then things are not so safe. The
29187       ** implicit assumption here is that if fstat() fails, things are in
29188       ** such bad shape that dropping a lock or two doesn't matter much.
29189       */
29190       robust_close(pNew, h, __LINE__);
29191       h = -1;
29192     }
29193     unixLeaveMutex();
29194   }
29195 
29196 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29197   else if( pLockingStyle == &afpIoMethods ){
29198     /* AFP locking uses the file path so it needs to be included in
29199     ** the afpLockingContext.
29200     */
29201     afpLockingContext *pCtx;
29202     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29203     if( pCtx==0 ){
29204       rc = SQLITE_NOMEM;
29205     }else{
29206       /* NB: zFilename exists and remains valid until the file is closed
29207       ** according to requirement F11141.  So we do not need to make a
29208       ** copy of the filename. */
29209       pCtx->dbPath = zFilename;
29210       pCtx->reserved = 0;
29211       srandomdev();
29212       unixEnterMutex();
29213       rc = findInodeInfo(pNew, &pNew->pInode);
29214       if( rc!=SQLITE_OK ){
29215         sqlite3_free(pNew->lockingContext);
29216         robust_close(pNew, h, __LINE__);
29217         h = -1;
29218       }
29219       unixLeaveMutex();
29220     }
29221   }
29222 #endif
29223 
29224   else if( pLockingStyle == &dotlockIoMethods ){
29225     /* Dotfile locking uses the file path so it needs to be included in
29226     ** the dotlockLockingContext
29227     */
29228     char *zLockFile;
29229     int nFilename;
29230     nFilename = (int)strlen(zFilename) + 6;
29231     zLockFile = (char *)sqlite3_malloc(nFilename);
29232     if( zLockFile==0 ){
29233       rc = SQLITE_NOMEM;
29234     }else{
29235       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29236     }
29237     pNew->lockingContext = zLockFile;
29238   }
29239 
29240 #if OS_VXWORKS
29241   else if( pLockingStyle == &semIoMethods ){
29242     /* Named semaphore locking uses the file path so it needs to be
29243     ** included in the semLockingContext
29244     */
29245     unixEnterMutex();
29246     rc = findInodeInfo(pNew, &pNew->pInode);
29247     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29248       char *zSemName = pNew->pInode->aSemName;
29249       int n;
29250       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29251                        pNew->pId->zCanonicalName);
29252       for( n=1; zSemName[n]; n++ )
29253         if( zSemName[n]=='/' ) zSemName[n] = '_';
29254       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29255       if( pNew->pInode->pSem == SEM_FAILED ){
29256         rc = SQLITE_NOMEM;
29257         pNew->pInode->aSemName[0] = '\0';
29258       }
29259     }
29260     unixLeaveMutex();
29261   }
29262 #endif
29263 
29264   pNew->lastErrno = 0;
29265 #if OS_VXWORKS
29266   if( rc!=SQLITE_OK ){
29267     if( h>=0 ) robust_close(pNew, h, __LINE__);
29268     h = -1;
29269     osUnlink(zFilename);
29270     isDelete = 0;
29271   }
29272   pNew->isDelete = isDelete;
29273 #endif
29274   if( rc!=SQLITE_OK ){
29275     if( h>=0 ) robust_close(pNew, h, __LINE__);
29276   }else{
29277     pNew->pMethod = pLockingStyle;
29278     OpenCounter(+1);
29279   }
29280   return rc;
29281 }
29282 
29283 /*
29284 ** Return the name of a directory in which to put temporary files.
29285 ** If no suitable temporary file directory can be found, return NULL.
29286 */
29287 static const char *unixTempFileDir(void){
29288   static const char *azDirs[] = {
29289      0,
29290      0,
29291      "/var/tmp",
29292      "/usr/tmp",
29293      "/tmp",
29294      0        /* List terminator */
29295   };
29296   unsigned int i;
29297   struct stat buf;
29298   const char *zDir = 0;
29299 
29300   azDirs[0] = sqlite3_temp_directory;
29301   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29302   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29303     if( zDir==0 ) continue;
29304     if( osStat(zDir, &buf) ) continue;
29305     if( !S_ISDIR(buf.st_mode) ) continue;
29306     if( osAccess(zDir, 07) ) continue;
29307     break;
29308   }
29309   return zDir;
29310 }
29311 
29312 /*
29313 ** Create a temporary file name in zBuf.  zBuf must be allocated
29314 ** by the calling process and must be big enough to hold at least
29315 ** pVfs->mxPathname bytes.
29316 */
29317 static int unixGetTempname(int nBuf, char *zBuf){
29318   static const unsigned char zChars[] =
29319     "abcdefghijklmnopqrstuvwxyz"
29320     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29321     "0123456789";
29322   unsigned int i, j;
29323   const char *zDir;
29324 
29325   /* It's odd to simulate an io-error here, but really this is just
29326   ** using the io-error infrastructure to test that SQLite handles this
29327   ** function failing.
29328   */
29329   SimulateIOError( return SQLITE_IOERR );
29330 
29331   zDir = unixTempFileDir();
29332   if( zDir==0 ) zDir = ".";
29333 
29334   /* Check that the output buffer is large enough for the temporary file
29335   ** name. If it is not, return SQLITE_ERROR.
29336   */
29337   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
29338     return SQLITE_ERROR;
29339   }
29340 
29341   do{
29342     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29343     j = (int)strlen(zBuf);
29344     sqlite3_randomness(15, &zBuf[j]);
29345     for(i=0; i<15; i++, j++){
29346       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29347     }
29348     zBuf[j] = 0;
29349   }while( osAccess(zBuf,0)==0 );
29350   return SQLITE_OK;
29351 }
29352 
29353 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29354 /*
29355 ** Routine to transform a unixFile into a proxy-locking unixFile.
29356 ** Implementation in the proxy-lock division, but used by unixOpen()
29357 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
29358 */
29359 static int proxyTransformUnixFile(unixFile*, const char*);
29360 #endif
29361 
29362 /*
29363 ** Search for an unused file descriptor that was opened on the database
29364 ** file (not a journal or master-journal file) identified by pathname
29365 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29366 ** argument to this function.
29367 **
29368 ** Such a file descriptor may exist if a database connection was closed
29369 ** but the associated file descriptor could not be closed because some
29370 ** other file descriptor open on the same file is holding a file-lock.
29371 ** Refer to comments in the unixClose() function and the lengthy comment
29372 ** describing "Posix Advisory Locking" at the start of this file for
29373 ** further details. Also, ticket #4018.
29374 **
29375 ** If a suitable file descriptor is found, then it is returned. If no
29376 ** such file descriptor is located, -1 is returned.
29377 */
29378 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29379   UnixUnusedFd *pUnused = 0;
29380 
29381   /* Do not search for an unused file descriptor on vxworks. Not because
29382   ** vxworks would not benefit from the change (it might, we're not sure),
29383   ** but because no way to test it is currently available. It is better
29384   ** not to risk breaking vxworks support for the sake of such an obscure
29385   ** feature.  */
29386 #if !OS_VXWORKS
29387   struct stat sStat;                   /* Results of stat() call */
29388 
29389   /* A stat() call may fail for various reasons. If this happens, it is
29390   ** almost certain that an open() call on the same path will also fail.
29391   ** For this reason, if an error occurs in the stat() call here, it is
29392   ** ignored and -1 is returned. The caller will try to open a new file
29393   ** descriptor on the same path, fail, and return an error to SQLite.
29394   **
29395   ** Even if a subsequent open() call does succeed, the consequences of
29396   ** not searching for a resusable file descriptor are not dire.  */
29397   if( 0==osStat(zPath, &sStat) ){
29398     unixInodeInfo *pInode;
29399 
29400     unixEnterMutex();
29401     pInode = inodeList;
29402     while( pInode && (pInode->fileId.dev!=sStat.st_dev
29403                      || pInode->fileId.ino!=sStat.st_ino) ){
29404        pInode = pInode->pNext;
29405     }
29406     if( pInode ){
29407       UnixUnusedFd **pp;
29408       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29409       pUnused = *pp;
29410       if( pUnused ){
29411         *pp = pUnused->pNext;
29412       }
29413     }
29414     unixLeaveMutex();
29415   }
29416 #endif    /* if !OS_VXWORKS */
29417   return pUnused;
29418 }
29419 
29420 /*
29421 ** This function is called by unixOpen() to determine the unix permissions
29422 ** to create new files with. If no error occurs, then SQLITE_OK is returned
29423 ** and a value suitable for passing as the third argument to open(2) is
29424 ** written to *pMode. If an IO error occurs, an SQLite error code is
29425 ** returned and the value of *pMode is not modified.
29426 **
29427 ** If the file being opened is a temporary file, it is always created with
29428 ** the octal permissions 0600 (read/writable by owner only). If the file
29429 ** is a database or master journal file, it is created with the permissions
29430 ** mask SQLITE_DEFAULT_FILE_PERMISSIONS.
29431 **
29432 ** Finally, if the file being opened is a WAL or regular journal file, then
29433 ** this function queries the file-system for the permissions on the
29434 ** corresponding database file and sets *pMode to this value. Whenever
29435 ** possible, WAL and journal files are created using the same permissions
29436 ** as the associated database file.
29437 **
29438 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29439 ** original filename is unavailable.  But 8_3_NAMES is only used for
29440 ** FAT filesystems and permissions do not matter there, so just use
29441 ** the default permissions.
29442 */
29443 static int findCreateFileMode(
29444   const char *zPath,              /* Path of file (possibly) being created */
29445   int flags,                      /* Flags passed as 4th argument to xOpen() */
29446   mode_t *pMode                   /* OUT: Permissions to open file with */
29447 ){
29448   int rc = SQLITE_OK;             /* Return Code */
29449   *pMode = SQLITE_DEFAULT_FILE_PERMISSIONS;
29450   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29451     char zDb[MAX_PATHNAME+1];     /* Database file path */
29452     int nDb;                      /* Number of valid bytes in zDb */
29453     struct stat sStat;            /* Output of stat() on database file */
29454 
29455     /* zPath is a path to a WAL or journal file. The following block derives
29456     ** the path to the associated database file from zPath. This block handles
29457     ** the following naming conventions:
29458     **
29459     **   "<path to db>-journal"
29460     **   "<path to db>-wal"
29461     **   "<path to db>-journalNN"
29462     **   "<path to db>-walNN"
29463     **
29464     ** where NN is a 4 digit decimal number. The NN naming schemes are
29465     ** used by the test_multiplex.c module.
29466     */
29467     nDb = sqlite3Strlen30(zPath) - 1;
29468     while( nDb>0 && zPath[nDb]!='-' ) nDb--;
29469     if( nDb==0 ) return SQLITE_OK;
29470     memcpy(zDb, zPath, nDb);
29471     zDb[nDb] = '\0';
29472 
29473     if( 0==osStat(zDb, &sStat) ){
29474       *pMode = sStat.st_mode & 0777;
29475     }else{
29476       rc = SQLITE_IOERR_FSTAT;
29477     }
29478   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29479     *pMode = 0600;
29480   }
29481   return rc;
29482 }
29483 
29484 /*
29485 ** Open the file zPath.
29486 **
29487 ** Previously, the SQLite OS layer used three functions in place of this
29488 ** one:
29489 **
29490 **     sqlite3OsOpenReadWrite();
29491 **     sqlite3OsOpenReadOnly();
29492 **     sqlite3OsOpenExclusive();
29493 **
29494 ** These calls correspond to the following combinations of flags:
29495 **
29496 **     ReadWrite() ->     (READWRITE | CREATE)
29497 **     ReadOnly()  ->     (READONLY)
29498 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
29499 **
29500 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
29501 ** true, the file was configured to be automatically deleted when the
29502 ** file handle closed. To achieve the same effect using this new
29503 ** interface, add the DELETEONCLOSE flag to those specified above for
29504 ** OpenExclusive().
29505 */
29506 static int unixOpen(
29507   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
29508   const char *zPath,           /* Pathname of file to be opened */
29509   sqlite3_file *pFile,         /* The file descriptor to be filled in */
29510   int flags,                   /* Input flags to control the opening */
29511   int *pOutFlags               /* Output flags returned to SQLite core */
29512 ){
29513   unixFile *p = (unixFile *)pFile;
29514   int fd = -1;                   /* File descriptor returned by open() */
29515   int openFlags = 0;             /* Flags to pass to open() */
29516   int eType = flags&0xFFFFFF00;  /* Type of file to open */
29517   int noLock;                    /* True to omit locking primitives */
29518   int rc = SQLITE_OK;            /* Function Return Code */
29519 
29520   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
29521   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
29522   int isCreate     = (flags & SQLITE_OPEN_CREATE);
29523   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
29524   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
29525 #if SQLITE_ENABLE_LOCKING_STYLE
29526   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
29527 #endif
29528 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29529   struct statfs fsInfo;
29530 #endif
29531 
29532   /* If creating a master or main-file journal, this function will open
29533   ** a file-descriptor on the directory too. The first time unixSync()
29534   ** is called the directory file descriptor will be fsync()ed and close()d.
29535   */
29536   int syncDir = (isCreate && (
29537         eType==SQLITE_OPEN_MASTER_JOURNAL
29538      || eType==SQLITE_OPEN_MAIN_JOURNAL
29539      || eType==SQLITE_OPEN_WAL
29540   ));
29541 
29542   /* If argument zPath is a NULL pointer, this function is required to open
29543   ** a temporary file. Use this buffer to store the file name in.
29544   */
29545   char zTmpname[MAX_PATHNAME+1];
29546   const char *zName = zPath;
29547 
29548   /* Check the following statements are true:
29549   **
29550   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
29551   **   (b) if CREATE is set, then READWRITE must also be set, and
29552   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
29553   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
29554   */
29555   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
29556   assert(isCreate==0 || isReadWrite);
29557   assert(isExclusive==0 || isCreate);
29558   assert(isDelete==0 || isCreate);
29559 
29560   /* The main DB, main journal, WAL file and master journal are never
29561   ** automatically deleted. Nor are they ever temporary files.  */
29562   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
29563   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
29564   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
29565   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
29566 
29567   /* Assert that the upper layer has set one of the "file-type" flags. */
29568   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
29569        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
29570        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
29571        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
29572   );
29573 
29574   memset(p, 0, sizeof(unixFile));
29575 
29576   if( eType==SQLITE_OPEN_MAIN_DB ){
29577     UnixUnusedFd *pUnused;
29578     pUnused = findReusableFd(zName, flags);
29579     if( pUnused ){
29580       fd = pUnused->fd;
29581     }else{
29582       pUnused = sqlite3_malloc(sizeof(*pUnused));
29583       if( !pUnused ){
29584         return SQLITE_NOMEM;
29585       }
29586     }
29587     p->pUnused = pUnused;
29588   }else if( !zName ){
29589     /* If zName is NULL, the upper layer is requesting a temp file. */
29590     assert(isDelete && !syncDir);
29591     rc = unixGetTempname(MAX_PATHNAME+1, zTmpname);
29592     if( rc!=SQLITE_OK ){
29593       return rc;
29594     }
29595     zName = zTmpname;
29596   }
29597 
29598   /* Determine the value of the flags parameter passed to POSIX function
29599   ** open(). These must be calculated even if open() is not called, as
29600   ** they may be stored as part of the file handle and used by the
29601   ** 'conch file' locking functions later on.  */
29602   if( isReadonly )  openFlags |= O_RDONLY;
29603   if( isReadWrite ) openFlags |= O_RDWR;
29604   if( isCreate )    openFlags |= O_CREAT;
29605   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
29606   openFlags |= (O_LARGEFILE|O_BINARY);
29607 
29608   if( fd<0 ){
29609     mode_t openMode;              /* Permissions to create file with */
29610     rc = findCreateFileMode(zName, flags, &openMode);
29611     if( rc!=SQLITE_OK ){
29612       assert( !p->pUnused );
29613       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
29614       return rc;
29615     }
29616     fd = robust_open(zName, openFlags, openMode);
29617     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
29618     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
29619       /* Failed to open the file for read/write access. Try read-only. */
29620       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
29621       openFlags &= ~(O_RDWR|O_CREAT);
29622       flags |= SQLITE_OPEN_READONLY;
29623       openFlags |= O_RDONLY;
29624       isReadonly = 1;
29625       fd = robust_open(zName, openFlags, openMode);
29626     }
29627     if( fd<0 ){
29628       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
29629       goto open_finished;
29630     }
29631   }
29632   assert( fd>=0 );
29633   if( pOutFlags ){
29634     *pOutFlags = flags;
29635   }
29636 
29637   if( p->pUnused ){
29638     p->pUnused->fd = fd;
29639     p->pUnused->flags = flags;
29640   }
29641 
29642   if( isDelete ){
29643 #if OS_VXWORKS
29644     zPath = zName;
29645 #else
29646     osUnlink(zName);
29647 #endif
29648   }
29649 #if SQLITE_ENABLE_LOCKING_STYLE
29650   else{
29651     p->openFlags = openFlags;
29652   }
29653 #endif
29654 
29655 #ifdef FD_CLOEXEC
29656   osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29657 #endif
29658 
29659   noLock = eType!=SQLITE_OPEN_MAIN_DB;
29660 
29661 
29662 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29663   if( fstatfs(fd, &fsInfo) == -1 ){
29664     ((unixFile*)pFile)->lastErrno = errno;
29665     robust_close(p, fd, __LINE__);
29666     return SQLITE_IOERR_ACCESS;
29667   }
29668   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
29669     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
29670   }
29671 #endif
29672 
29673 #if SQLITE_ENABLE_LOCKING_STYLE
29674 #if SQLITE_PREFER_PROXY_LOCKING
29675   isAutoProxy = 1;
29676 #endif
29677   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
29678     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
29679     int useProxy = 0;
29680 
29681     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
29682     ** never use proxy, NULL means use proxy for non-local files only.  */
29683     if( envforce!=NULL ){
29684       useProxy = atoi(envforce)>0;
29685     }else{
29686       if( statfs(zPath, &fsInfo) == -1 ){
29687         /* In theory, the close(fd) call is sub-optimal. If the file opened
29688         ** with fd is a database file, and there are other connections open
29689         ** on that file that are currently holding advisory locks on it,
29690         ** then the call to close() will cancel those locks. In practice,
29691         ** we're assuming that statfs() doesn't fail very often. At least
29692         ** not while other file descriptors opened by the same process on
29693         ** the same file are working.  */
29694         p->lastErrno = errno;
29695         robust_close(p, fd, __LINE__);
29696         rc = SQLITE_IOERR_ACCESS;
29697         goto open_finished;
29698       }
29699       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
29700     }
29701     if( useProxy ){
29702       rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29703                           isDelete, isReadonly);
29704       if( rc==SQLITE_OK ){
29705         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
29706         if( rc!=SQLITE_OK ){
29707           /* Use unixClose to clean up the resources added in fillInUnixFile
29708           ** and clear all the structure's references.  Specifically,
29709           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
29710           */
29711           unixClose(pFile);
29712           return rc;
29713         }
29714       }
29715       goto open_finished;
29716     }
29717   }
29718 #endif
29719 
29720   rc = fillInUnixFile(pVfs, fd, syncDir, pFile, zPath, noLock,
29721                       isDelete, isReadonly);
29722 open_finished:
29723   if( rc!=SQLITE_OK ){
29724     sqlite3_free(p->pUnused);
29725   }
29726   return rc;
29727 }
29728 
29729 
29730 /*
29731 ** Delete the file at zPath. If the dirSync argument is true, fsync()
29732 ** the directory after deleting the file.
29733 */
29734 static int unixDelete(
29735   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
29736   const char *zPath,        /* Name of file to be deleted */
29737   int dirSync               /* If true, fsync() directory after deleting file */
29738 ){
29739   int rc = SQLITE_OK;
29740   UNUSED_PARAMETER(NotUsed);
29741   SimulateIOError(return SQLITE_IOERR_DELETE);
29742   if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
29743     return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
29744   }
29745 #ifndef SQLITE_DISABLE_DIRSYNC
29746   if( dirSync ){
29747     int fd;
29748     rc = osOpenDirectory(zPath, &fd);
29749     if( rc==SQLITE_OK ){
29750 #if OS_VXWORKS
29751       if( fsync(fd)==-1 )
29752 #else
29753       if( fsync(fd) )
29754 #endif
29755       {
29756         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
29757       }
29758       robust_close(0, fd, __LINE__);
29759     }else if( rc==SQLITE_CANTOPEN ){
29760       rc = SQLITE_OK;
29761     }
29762   }
29763 #endif
29764   return rc;
29765 }
29766 
29767 /*
29768 ** Test the existance of or access permissions of file zPath. The
29769 ** test performed depends on the value of flags:
29770 **
29771 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
29772 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
29773 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
29774 **
29775 ** Otherwise return 0.
29776 */
29777 static int unixAccess(
29778   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
29779   const char *zPath,      /* Path of the file to examine */
29780   int flags,              /* What do we want to learn about the zPath file? */
29781   int *pResOut            /* Write result boolean here */
29782 ){
29783   int amode = 0;
29784   UNUSED_PARAMETER(NotUsed);
29785   SimulateIOError( return SQLITE_IOERR_ACCESS; );
29786   switch( flags ){
29787     case SQLITE_ACCESS_EXISTS:
29788       amode = F_OK;
29789       break;
29790     case SQLITE_ACCESS_READWRITE:
29791       amode = W_OK|R_OK;
29792       break;
29793     case SQLITE_ACCESS_READ:
29794       amode = R_OK;
29795       break;
29796 
29797     default:
29798       assert(!"Invalid flags argument");
29799   }
29800   *pResOut = (osAccess(zPath, amode)==0);
29801   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
29802     struct stat buf;
29803     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
29804       *pResOut = 0;
29805     }
29806   }
29807   return SQLITE_OK;
29808 }
29809 
29810 
29811 /*
29812 ** Turn a relative pathname into a full pathname. The relative path
29813 ** is stored as a nul-terminated string in the buffer pointed to by
29814 ** zPath.
29815 **
29816 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
29817 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
29818 ** this buffer before returning.
29819 */
29820 static int unixFullPathname(
29821   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29822   const char *zPath,            /* Possibly relative input path */
29823   int nOut,                     /* Size of output buffer in bytes */
29824   char *zOut                    /* Output buffer */
29825 ){
29826 
29827   /* It's odd to simulate an io-error here, but really this is just
29828   ** using the io-error infrastructure to test that SQLite handles this
29829   ** function failing. This function could fail if, for example, the
29830   ** current working directory has been unlinked.
29831   */
29832   SimulateIOError( return SQLITE_ERROR );
29833 
29834   assert( pVfs->mxPathname==MAX_PATHNAME );
29835   UNUSED_PARAMETER(pVfs);
29836 
29837   zOut[nOut-1] = '\0';
29838   if( zPath[0]=='/' ){
29839     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29840   }else{
29841     int nCwd;
29842     if( osGetcwd(zOut, nOut-1)==0 ){
29843       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29844     }
29845     nCwd = (int)strlen(zOut);
29846     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29847   }
29848   return SQLITE_OK;
29849 }
29850 
29851 
29852 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29853 /*
29854 ** Interfaces for opening a shared library, finding entry points
29855 ** within the shared library, and closing the shared library.
29856 */
29857 #include <dlfcn.h>
29858 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29859   UNUSED_PARAMETER(NotUsed);
29860   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29861 }
29862 
29863 /*
29864 ** SQLite calls this function immediately after a call to unixDlSym() or
29865 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29866 ** message is available, it is written to zBufOut. If no error message
29867 ** is available, zBufOut is left unmodified and SQLite uses a default
29868 ** error message.
29869 */
29870 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29871   const char *zErr;
29872   UNUSED_PARAMETER(NotUsed);
29873   unixEnterMutex();
29874   zErr = dlerror();
29875   if( zErr ){
29876     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29877   }
29878   unixLeaveMutex();
29879 }
29880 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29881   /*
29882   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29883   ** cast into a pointer to a function.  And yet the library dlsym() routine
29884   ** returns a void* which is really a pointer to a function.  So how do we
29885   ** use dlsym() with -pedantic-errors?
29886   **
29887   ** Variable x below is defined to be a pointer to a function taking
29888   ** parameters void* and const char* and returning a pointer to a function.
29889   ** We initialize x by assigning it a pointer to the dlsym() function.
29890   ** (That assignment requires a cast.)  Then we call the function that
29891   ** x points to.
29892   **
29893   ** This work-around is unlikely to work correctly on any system where
29894   ** you really cannot cast a function pointer into void*.  But then, on the
29895   ** other hand, dlsym() will not work on such a system either, so we have
29896   ** not really lost anything.
29897   */
29898   void (*(*x)(void*,const char*))(void);
29899   UNUSED_PARAMETER(NotUsed);
29900   x = (void(*(*)(void*,const char*))(void))dlsym;
29901   return (*x)(p, zSym);
29902 }
29903 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29904   UNUSED_PARAMETER(NotUsed);
29905   dlclose(pHandle);
29906 }
29907 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29908   #define unixDlOpen  0
29909   #define unixDlError 0
29910   #define unixDlSym   0
29911   #define unixDlClose 0
29912 #endif
29913 
29914 /*
29915 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29916 */
29917 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29918   UNUSED_PARAMETER(NotUsed);
29919   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29920 
29921   /* We have to initialize zBuf to prevent valgrind from reporting
29922   ** errors.  The reports issued by valgrind are incorrect - we would
29923   ** prefer that the randomness be increased by making use of the
29924   ** uninitialized space in zBuf - but valgrind errors tend to worry
29925   ** some users.  Rather than argue, it seems easier just to initialize
29926   ** the whole array and silence valgrind, even if that means less randomness
29927   ** in the random seed.
29928   **
29929   ** When testing, initializing zBuf[] to zero is all we do.  That means
29930   ** that we always use the same random number sequence.  This makes the
29931   ** tests repeatable.
29932   */
29933   memset(zBuf, 0, nBuf);
29934 #if !defined(SQLITE_TEST)
29935   {
29936     int pid, fd;
29937     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29938     if( fd<0 ){
29939       time_t t;
29940       time(&t);
29941       memcpy(zBuf, &t, sizeof(t));
29942       pid = getpid();
29943       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29944       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29945       nBuf = sizeof(t) + sizeof(pid);
29946     }else{
29947       do{ nBuf = osRead(fd, zBuf, nBuf); }while( nBuf<0 && errno==EINTR );
29948       robust_close(0, fd, __LINE__);
29949     }
29950   }
29951 #endif
29952   return nBuf;
29953 }
29954 
29955 
29956 /*
29957 ** Sleep for a little while.  Return the amount of time slept.
29958 ** The argument is the number of microseconds we want to sleep.
29959 ** The return value is the number of microseconds of sleep actually
29960 ** requested from the underlying operating system, a number which
29961 ** might be greater than or equal to the argument, but not less
29962 ** than the argument.
29963 */
29964 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29965 #if OS_VXWORKS
29966   struct timespec sp;
29967 
29968   sp.tv_sec = microseconds / 1000000;
29969   sp.tv_nsec = (microseconds % 1000000) * 1000;
29970   nanosleep(&sp, NULL);
29971   UNUSED_PARAMETER(NotUsed);
29972   return microseconds;
29973 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29974   usleep(microseconds);
29975   UNUSED_PARAMETER(NotUsed);
29976   return microseconds;
29977 #else
29978   int seconds = (microseconds+999999)/1000000;
29979   sleep(seconds);
29980   UNUSED_PARAMETER(NotUsed);
29981   return seconds*1000000;
29982 #endif
29983 }
29984 
29985 /*
29986 ** The following variable, if set to a non-zero value, is interpreted as
29987 ** the number of seconds since 1970 and is used to set the result of
29988 ** sqlite3OsCurrentTime() during testing.
29989 */
29990 #ifdef SQLITE_TEST
29991 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29992 #endif
29993 
29994 /*
29995 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29996 ** the current time and date as a Julian Day number times 86_400_000.  In
29997 ** other words, write into *piNow the number of milliseconds since the Julian
29998 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29999 ** proleptic Gregorian calendar.
30000 **
30001 ** On success, return 0.  Return 1 if the time and date cannot be found.
30002 */
30003 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30004   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30005 #if defined(NO_GETTOD)
30006   time_t t;
30007   time(&t);
30008   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30009 #elif OS_VXWORKS
30010   struct timespec sNow;
30011   clock_gettime(CLOCK_REALTIME, &sNow);
30012   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30013 #else
30014   struct timeval sNow;
30015   gettimeofday(&sNow, 0);
30016   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30017 #endif
30018 
30019 #ifdef SQLITE_TEST
30020   if( sqlite3_current_time ){
30021     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30022   }
30023 #endif
30024   UNUSED_PARAMETER(NotUsed);
30025   return 0;
30026 }
30027 
30028 /*
30029 ** Find the current time (in Universal Coordinated Time).  Write the
30030 ** current time and date as a Julian Day number into *prNow and
30031 ** return 0.  Return 1 if the time and date cannot be found.
30032 */
30033 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30034   sqlite3_int64 i;
30035   UNUSED_PARAMETER(NotUsed);
30036   unixCurrentTimeInt64(0, &i);
30037   *prNow = i/86400000.0;
30038   return 0;
30039 }
30040 
30041 /*
30042 ** We added the xGetLastError() method with the intention of providing
30043 ** better low-level error messages when operating-system problems come up
30044 ** during SQLite operation.  But so far, none of that has been implemented
30045 ** in the core.  So this routine is never called.  For now, it is merely
30046 ** a place-holder.
30047 */
30048 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30049   UNUSED_PARAMETER(NotUsed);
30050   UNUSED_PARAMETER(NotUsed2);
30051   UNUSED_PARAMETER(NotUsed3);
30052   return 0;
30053 }
30054 
30055 
30056 /*
30057 ************************ End of sqlite3_vfs methods ***************************
30058 ******************************************************************************/
30059 
30060 /******************************************************************************
30061 ************************** Begin Proxy Locking ********************************
30062 **
30063 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30064 ** other locking methods on secondary lock files.  Proxy locking is a
30065 ** meta-layer over top of the primitive locking implemented above.  For
30066 ** this reason, the division that implements of proxy locking is deferred
30067 ** until late in the file (here) after all of the other I/O methods have
30068 ** been defined - so that the primitive locking methods are available
30069 ** as services to help with the implementation of proxy locking.
30070 **
30071 ****
30072 **
30073 ** The default locking schemes in SQLite use byte-range locks on the
30074 ** database file to coordinate safe, concurrent access by multiple readers
30075 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30076 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30077 ** as POSIX read & write locks over fixed set of locations (via fsctl),
30078 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
30079 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30080 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30081 ** address in the shared range is taken for a SHARED lock, the entire
30082 ** shared range is taken for an EXCLUSIVE lock):
30083 **
30084 **      PENDING_BYTE        0x40000000
30085 **      RESERVED_BYTE       0x40000001
30086 **      SHARED_RANGE        0x40000002 -> 0x40000200
30087 **
30088 ** This works well on the local file system, but shows a nearly 100x
30089 ** slowdown in read performance on AFP because the AFP client disables
30090 ** the read cache when byte-range locks are present.  Enabling the read
30091 ** cache exposes a cache coherency problem that is present on all OS X
30092 ** supported network file systems.  NFS and AFP both observe the
30093 ** close-to-open semantics for ensuring cache coherency
30094 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30095 ** address the requirements for concurrent database access by multiple
30096 ** readers and writers
30097 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30098 **
30099 ** To address the performance and cache coherency issues, proxy file locking
30100 ** changes the way database access is controlled by limiting access to a
30101 ** single host at a time and moving file locks off of the database file
30102 ** and onto a proxy file on the local file system.
30103 **
30104 **
30105 ** Using proxy locks
30106 ** -----------------
30107 **
30108 ** C APIs
30109 **
30110 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30111 **                       <proxy_path> | ":auto:");
30112 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30113 **
30114 **
30115 ** SQL pragmas
30116 **
30117 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30118 **  PRAGMA [database.]lock_proxy_file
30119 **
30120 ** Specifying ":auto:" means that if there is a conch file with a matching
30121 ** host ID in it, the proxy path in the conch file will be used, otherwise
30122 ** a proxy path based on the user's temp dir
30123 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30124 ** actual proxy file name is generated from the name and path of the
30125 ** database file.  For example:
30126 **
30127 **       For database path "/Users/me/foo.db"
30128 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30129 **
30130 ** Once a lock proxy is configured for a database connection, it can not
30131 ** be removed, however it may be switched to a different proxy path via
30132 ** the above APIs (assuming the conch file is not being held by another
30133 ** connection or process).
30134 **
30135 **
30136 ** How proxy locking works
30137 ** -----------------------
30138 **
30139 ** Proxy file locking relies primarily on two new supporting files:
30140 **
30141 **   *  conch file to limit access to the database file to a single host
30142 **      at a time
30143 **
30144 **   *  proxy file to act as a proxy for the advisory locks normally
30145 **      taken on the database
30146 **
30147 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
30148 ** by taking an sqlite-style shared lock on the conch file, reading the
30149 ** contents and comparing the host's unique host ID (see below) and lock
30150 ** proxy path against the values stored in the conch.  The conch file is
30151 ** stored in the same directory as the database file and the file name
30152 ** is patterned after the database file name as ".<databasename>-conch".
30153 ** If the conch file does not exist, or it's contents do not match the
30154 ** host ID and/or proxy path, then the lock is escalated to an exclusive
30155 ** lock and the conch file contents is updated with the host ID and proxy
30156 ** path and the lock is downgraded to a shared lock again.  If the conch
30157 ** is held by another process (with a shared lock), the exclusive lock
30158 ** will fail and SQLITE_BUSY is returned.
30159 **
30160 ** The proxy file - a single-byte file used for all advisory file locks
30161 ** normally taken on the database file.   This allows for safe sharing
30162 ** of the database file for multiple readers and writers on the same
30163 ** host (the conch ensures that they all use the same local lock file).
30164 **
30165 ** Requesting the lock proxy does not immediately take the conch, it is
30166 ** only taken when the first request to lock database file is made.
30167 ** This matches the semantics of the traditional locking behavior, where
30168 ** opening a connection to a database file does not take a lock on it.
30169 ** The shared lock and an open file descriptor are maintained until
30170 ** the connection to the database is closed.
30171 **
30172 ** The proxy file and the lock file are never deleted so they only need
30173 ** to be created the first time they are used.
30174 **
30175 ** Configuration options
30176 ** ---------------------
30177 **
30178 **  SQLITE_PREFER_PROXY_LOCKING
30179 **
30180 **       Database files accessed on non-local file systems are
30181 **       automatically configured for proxy locking, lock files are
30182 **       named automatically using the same logic as
30183 **       PRAGMA lock_proxy_file=":auto:"
30184 **
30185 **  SQLITE_PROXY_DEBUG
30186 **
30187 **       Enables the logging of error messages during host id file
30188 **       retrieval and creation
30189 **
30190 **  LOCKPROXYDIR
30191 **
30192 **       Overrides the default directory used for lock proxy files that
30193 **       are named automatically via the ":auto:" setting
30194 **
30195 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30196 **
30197 **       Permissions to use when creating a directory for storing the
30198 **       lock proxy files, only used when LOCKPROXYDIR is not set.
30199 **
30200 **
30201 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30202 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30203 ** force proxy locking to be used for every database file opened, and 0
30204 ** will force automatic proxy locking to be disabled for all database
30205 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30206 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30207 */
30208 
30209 /*
30210 ** Proxy locking is only available on MacOSX
30211 */
30212 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30213 
30214 /*
30215 ** The proxyLockingContext has the path and file structures for the remote
30216 ** and local proxy files in it
30217 */
30218 typedef struct proxyLockingContext proxyLockingContext;
30219 struct proxyLockingContext {
30220   unixFile *conchFile;         /* Open conch file */
30221   char *conchFilePath;         /* Name of the conch file */
30222   unixFile *lockProxy;         /* Open proxy lock file */
30223   char *lockProxyPath;         /* Name of the proxy lock file */
30224   char *dbPath;                /* Name of the open file */
30225   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30226   void *oldLockingContext;     /* Original lockingcontext to restore on close */
30227   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30228 };
30229 
30230 /*
30231 ** The proxy lock file path for the database at dbPath is written into lPath,
30232 ** which must point to valid, writable memory large enough for a maxLen length
30233 ** file path.
30234 */
30235 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30236   int len;
30237   int dbLen;
30238   int i;
30239 
30240 #ifdef LOCKPROXYDIR
30241   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30242 #else
30243 # ifdef _CS_DARWIN_USER_TEMP_DIR
30244   {
30245     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30246       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30247                lPath, errno, getpid()));
30248       return SQLITE_IOERR_LOCK;
30249     }
30250     len = strlcat(lPath, "sqliteplocks", maxLen);
30251   }
30252 # else
30253   len = strlcpy(lPath, "/tmp/", maxLen);
30254 # endif
30255 #endif
30256 
30257   if( lPath[len-1]!='/' ){
30258     len = strlcat(lPath, "/", maxLen);
30259   }
30260 
30261   /* transform the db path to a unique cache name */
30262   dbLen = (int)strlen(dbPath);
30263   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30264     char c = dbPath[i];
30265     lPath[i+len] = (c=='/')?'_':c;
30266   }
30267   lPath[i+len]='\0';
30268   strlcat(lPath, ":auto:", maxLen);
30269   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30270   return SQLITE_OK;
30271 }
30272 
30273 /*
30274  ** Creates the lock file and any missing directories in lockPath
30275  */
30276 static int proxyCreateLockPath(const char *lockPath){
30277   int i, len;
30278   char buf[MAXPATHLEN];
30279   int start = 0;
30280 
30281   assert(lockPath!=NULL);
30282   /* try to create all the intermediate directories */
30283   len = (int)strlen(lockPath);
30284   buf[0] = lockPath[0];
30285   for( i=1; i<len; i++ ){
30286     if( lockPath[i] == '/' && (i - start > 0) ){
30287       /* only mkdir if leaf dir != "." or "/" or ".." */
30288       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30289          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30290         buf[i]='\0';
30291         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30292           int err=errno;
30293           if( err!=EEXIST ) {
30294             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30295                      "'%s' proxy lock path=%s pid=%d\n",
30296                      buf, strerror(err), lockPath, getpid()));
30297             return err;
30298           }
30299         }
30300       }
30301       start=i+1;
30302     }
30303     buf[i] = lockPath[i];
30304   }
30305   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30306   return 0;
30307 }
30308 
30309 /*
30310 ** Create a new VFS file descriptor (stored in memory obtained from
30311 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
30312 **
30313 ** The caller is responsible not only for closing the file descriptor
30314 ** but also for freeing the memory associated with the file descriptor.
30315 */
30316 static int proxyCreateUnixFile(
30317     const char *path,        /* path for the new unixFile */
30318     unixFile **ppFile,       /* unixFile created and returned by ref */
30319     int islockfile           /* if non zero missing dirs will be created */
30320 ) {
30321   int fd = -1;
30322   unixFile *pNew;
30323   int rc = SQLITE_OK;
30324   int openFlags = O_RDWR | O_CREAT;
30325   sqlite3_vfs dummyVfs;
30326   int terrno = 0;
30327   UnixUnusedFd *pUnused = NULL;
30328 
30329   /* 1. first try to open/create the file
30330   ** 2. if that fails, and this is a lock file (not-conch), try creating
30331   ** the parent directories and then try again.
30332   ** 3. if that fails, try to open the file read-only
30333   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30334   */
30335   pUnused = findReusableFd(path, openFlags);
30336   if( pUnused ){
30337     fd = pUnused->fd;
30338   }else{
30339     pUnused = sqlite3_malloc(sizeof(*pUnused));
30340     if( !pUnused ){
30341       return SQLITE_NOMEM;
30342     }
30343   }
30344   if( fd<0 ){
30345     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30346     terrno = errno;
30347     if( fd<0 && errno==ENOENT && islockfile ){
30348       if( proxyCreateLockPath(path) == SQLITE_OK ){
30349         fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30350       }
30351     }
30352   }
30353   if( fd<0 ){
30354     openFlags = O_RDONLY;
30355     fd = robust_open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
30356     terrno = errno;
30357   }
30358   if( fd<0 ){
30359     if( islockfile ){
30360       return SQLITE_BUSY;
30361     }
30362     switch (terrno) {
30363       case EACCES:
30364         return SQLITE_PERM;
30365       case EIO:
30366         return SQLITE_IOERR_LOCK; /* even though it is the conch */
30367       default:
30368         return SQLITE_CANTOPEN_BKPT;
30369     }
30370   }
30371 
30372   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30373   if( pNew==NULL ){
30374     rc = SQLITE_NOMEM;
30375     goto end_create_proxy;
30376   }
30377   memset(pNew, 0, sizeof(unixFile));
30378   pNew->openFlags = openFlags;
30379   memset(&dummyVfs, 0, sizeof(dummyVfs));
30380   dummyVfs.pAppData = (void*)&autolockIoFinder;
30381   dummyVfs.zName = "dummy";
30382   pUnused->fd = fd;
30383   pUnused->flags = openFlags;
30384   pNew->pUnused = pUnused;
30385 
30386   rc = fillInUnixFile(&dummyVfs, fd, 0, (sqlite3_file*)pNew, path, 0, 0, 0);
30387   if( rc==SQLITE_OK ){
30388     *ppFile = pNew;
30389     return SQLITE_OK;
30390   }
30391 end_create_proxy:
30392   robust_close(pNew, fd, __LINE__);
30393   sqlite3_free(pNew);
30394   sqlite3_free(pUnused);
30395   return rc;
30396 }
30397 
30398 #ifdef SQLITE_TEST
30399 /* simulate multiple hosts by creating unique hostid file paths */
30400 SQLITE_API int sqlite3_hostid_num = 0;
30401 #endif
30402 
30403 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
30404 
30405 /* Not always defined in the headers as it ought to be */
30406 extern int gethostuuid(uuid_t id, const struct timespec *wait);
30407 
30408 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30409 ** bytes of writable memory.
30410 */
30411 static int proxyGetHostID(unsigned char *pHostID, int *pError){
30412   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30413   memset(pHostID, 0, PROXY_HOSTIDLEN);
30414 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30415                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30416   {
30417     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30418     if( gethostuuid(pHostID, &timeout) ){
30419       int err = errno;
30420       if( pError ){
30421         *pError = err;
30422       }
30423       return SQLITE_IOERR;
30424     }
30425   }
30426 #else
30427   UNUSED_PARAMETER(pError);
30428 #endif
30429 #ifdef SQLITE_TEST
30430   /* simulate multiple hosts by creating unique hostid file paths */
30431   if( sqlite3_hostid_num != 0){
30432     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30433   }
30434 #endif
30435 
30436   return SQLITE_OK;
30437 }
30438 
30439 /* The conch file contains the header, host id and lock file path
30440  */
30441 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
30442 #define PROXY_HEADERLEN    1   /* conch file header length */
30443 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
30444 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
30445 
30446 /*
30447 ** Takes an open conch file, copies the contents to a new path and then moves
30448 ** it back.  The newly created file's file descriptor is assigned to the
30449 ** conch file structure and finally the original conch file descriptor is
30450 ** closed.  Returns zero if successful.
30451 */
30452 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
30453   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30454   unixFile *conchFile = pCtx->conchFile;
30455   char tPath[MAXPATHLEN];
30456   char buf[PROXY_MAXCONCHLEN];
30457   char *cPath = pCtx->conchFilePath;
30458   size_t readLen = 0;
30459   size_t pathLen = 0;
30460   char errmsg[64] = "";
30461   int fd = -1;
30462   int rc = -1;
30463   UNUSED_PARAMETER(myHostID);
30464 
30465   /* create a new path by replace the trailing '-conch' with '-break' */
30466   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
30467   if( pathLen>MAXPATHLEN || pathLen<6 ||
30468      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
30469     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
30470     goto end_breaklock;
30471   }
30472   /* read the conch content */
30473   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
30474   if( readLen<PROXY_PATHINDEX ){
30475     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
30476     goto end_breaklock;
30477   }
30478   /* write it out to the temporary break file */
30479   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL),
30480                    SQLITE_DEFAULT_FILE_PERMISSIONS);
30481   if( fd<0 ){
30482     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
30483     goto end_breaklock;
30484   }
30485   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
30486     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
30487     goto end_breaklock;
30488   }
30489   if( rename(tPath, cPath) ){
30490     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
30491     goto end_breaklock;
30492   }
30493   rc = 0;
30494   fprintf(stderr, "broke stale lock on %s\n", cPath);
30495   robust_close(pFile, conchFile->h, __LINE__);
30496   conchFile->h = fd;
30497   conchFile->openFlags = O_RDWR | O_CREAT;
30498 
30499 end_breaklock:
30500   if( rc ){
30501     if( fd>=0 ){
30502       osUnlink(tPath);
30503       robust_close(pFile, fd, __LINE__);
30504     }
30505     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
30506   }
30507   return rc;
30508 }
30509 
30510 /* Take the requested lock on the conch file and break a stale lock if the
30511 ** host id matches.
30512 */
30513 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
30514   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30515   unixFile *conchFile = pCtx->conchFile;
30516   int rc = SQLITE_OK;
30517   int nTries = 0;
30518   struct timespec conchModTime;
30519 
30520   memset(&conchModTime, 0, sizeof(conchModTime));
30521   do {
30522     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30523     nTries ++;
30524     if( rc==SQLITE_BUSY ){
30525       /* If the lock failed (busy):
30526        * 1st try: get the mod time of the conch, wait 0.5s and try again.
30527        * 2nd try: fail if the mod time changed or host id is different, wait
30528        *           10 sec and try again
30529        * 3rd try: break the lock unless the mod time has changed.
30530        */
30531       struct stat buf;
30532       if( osFstat(conchFile->h, &buf) ){
30533         pFile->lastErrno = errno;
30534         return SQLITE_IOERR_LOCK;
30535       }
30536 
30537       if( nTries==1 ){
30538         conchModTime = buf.st_mtimespec;
30539         usleep(500000); /* wait 0.5 sec and try the lock again*/
30540         continue;
30541       }
30542 
30543       assert( nTries>1 );
30544       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
30545          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
30546         return SQLITE_BUSY;
30547       }
30548 
30549       if( nTries==2 ){
30550         char tBuf[PROXY_MAXCONCHLEN];
30551         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
30552         if( len<0 ){
30553           pFile->lastErrno = errno;
30554           return SQLITE_IOERR_LOCK;
30555         }
30556         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
30557           /* don't break the lock if the host id doesn't match */
30558           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
30559             return SQLITE_BUSY;
30560           }
30561         }else{
30562           /* don't break the lock on short read or a version mismatch */
30563           return SQLITE_BUSY;
30564         }
30565         usleep(10000000); /* wait 10 sec and try the lock again */
30566         continue;
30567       }
30568 
30569       assert( nTries==3 );
30570       if( 0==proxyBreakConchLock(pFile, myHostID) ){
30571         rc = SQLITE_OK;
30572         if( lockType==EXCLUSIVE_LOCK ){
30573           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
30574         }
30575         if( !rc ){
30576           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
30577         }
30578       }
30579     }
30580   } while( rc==SQLITE_BUSY && nTries<3 );
30581 
30582   return rc;
30583 }
30584 
30585 /* Takes the conch by taking a shared lock and read the contents conch, if
30586 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
30587 ** lockPath means that the lockPath in the conch file will be used if the
30588 ** host IDs match, or a new lock path will be generated automatically
30589 ** and written to the conch file.
30590 */
30591 static int proxyTakeConch(unixFile *pFile){
30592   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30593 
30594   if( pCtx->conchHeld!=0 ){
30595     return SQLITE_OK;
30596   }else{
30597     unixFile *conchFile = pCtx->conchFile;
30598     uuid_t myHostID;
30599     int pError = 0;
30600     char readBuf[PROXY_MAXCONCHLEN];
30601     char lockPath[MAXPATHLEN];
30602     char *tempLockPath = NULL;
30603     int rc = SQLITE_OK;
30604     int createConch = 0;
30605     int hostIdMatch = 0;
30606     int readLen = 0;
30607     int tryOldLockPath = 0;
30608     int forceNewLockPath = 0;
30609 
30610     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
30611              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
30612 
30613     rc = proxyGetHostID(myHostID, &pError);
30614     if( (rc&0xff)==SQLITE_IOERR ){
30615       pFile->lastErrno = pError;
30616       goto end_takeconch;
30617     }
30618     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
30619     if( rc!=SQLITE_OK ){
30620       goto end_takeconch;
30621     }
30622     /* read the existing conch file */
30623     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
30624     if( readLen<0 ){
30625       /* I/O error: lastErrno set by seekAndRead */
30626       pFile->lastErrno = conchFile->lastErrno;
30627       rc = SQLITE_IOERR_READ;
30628       goto end_takeconch;
30629     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
30630              readBuf[0]!=(char)PROXY_CONCHVERSION ){
30631       /* a short read or version format mismatch means we need to create a new
30632       ** conch file.
30633       */
30634       createConch = 1;
30635     }
30636     /* if the host id matches and the lock path already exists in the conch
30637     ** we'll try to use the path there, if we can't open that path, we'll
30638     ** retry with a new auto-generated path
30639     */
30640     do { /* in case we need to try again for an :auto: named lock file */
30641 
30642       if( !createConch && !forceNewLockPath ){
30643         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
30644                                   PROXY_HOSTIDLEN);
30645         /* if the conch has data compare the contents */
30646         if( !pCtx->lockProxyPath ){
30647           /* for auto-named local lock file, just check the host ID and we'll
30648            ** use the local lock file path that's already in there
30649            */
30650           if( hostIdMatch ){
30651             size_t pathLen = (readLen - PROXY_PATHINDEX);
30652 
30653             if( pathLen>=MAXPATHLEN ){
30654               pathLen=MAXPATHLEN-1;
30655             }
30656             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
30657             lockPath[pathLen] = 0;
30658             tempLockPath = lockPath;
30659             tryOldLockPath = 1;
30660             /* create a copy of the lock path if the conch is taken */
30661             goto end_takeconch;
30662           }
30663         }else if( hostIdMatch
30664                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
30665                            readLen-PROXY_PATHINDEX)
30666         ){
30667           /* conch host and lock path match */
30668           goto end_takeconch;
30669         }
30670       }
30671 
30672       /* if the conch isn't writable and doesn't match, we can't take it */
30673       if( (conchFile->openFlags&O_RDWR) == 0 ){
30674         rc = SQLITE_BUSY;
30675         goto end_takeconch;
30676       }
30677 
30678       /* either the conch didn't match or we need to create a new one */
30679       if( !pCtx->lockProxyPath ){
30680         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
30681         tempLockPath = lockPath;
30682         /* create a copy of the lock path _only_ if the conch is taken */
30683       }
30684 
30685       /* update conch with host and path (this will fail if other process
30686       ** has a shared lock already), if the host id matches, use the big
30687       ** stick.
30688       */
30689       futimes(conchFile->h, NULL);
30690       if( hostIdMatch && !createConch ){
30691         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
30692           /* We are trying for an exclusive lock but another thread in this
30693            ** same process is still holding a shared lock. */
30694           rc = SQLITE_BUSY;
30695         } else {
30696           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
30697         }
30698       }else{
30699         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
30700       }
30701       if( rc==SQLITE_OK ){
30702         char writeBuffer[PROXY_MAXCONCHLEN];
30703         int writeSize = 0;
30704 
30705         writeBuffer[0] = (char)PROXY_CONCHVERSION;
30706         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
30707         if( pCtx->lockProxyPath!=NULL ){
30708           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
30709         }else{
30710           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
30711         }
30712         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
30713         robust_ftruncate(conchFile->h, writeSize);
30714         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
30715         fsync(conchFile->h);
30716         /* If we created a new conch file (not just updated the contents of a
30717          ** valid conch file), try to match the permissions of the database
30718          */
30719         if( rc==SQLITE_OK && createConch ){
30720           struct stat buf;
30721           int err = osFstat(pFile->h, &buf);
30722           if( err==0 ){
30723             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
30724                                         S_IROTH|S_IWOTH);
30725             /* try to match the database file R/W permissions, ignore failure */
30726 #ifndef SQLITE_PROXY_DEBUG
30727             osFchmod(conchFile->h, cmode);
30728 #else
30729             do{
30730               rc = osFchmod(conchFile->h, cmode);
30731             }while( rc==(-1) && errno==EINTR );
30732             if( rc!=0 ){
30733               int code = errno;
30734               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
30735                       cmode, code, strerror(code));
30736             } else {
30737               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
30738             }
30739           }else{
30740             int code = errno;
30741             fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
30742                     err, code, strerror(code));
30743 #endif
30744           }
30745         }
30746       }
30747       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
30748 
30749     end_takeconch:
30750       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
30751       if( rc==SQLITE_OK && pFile->openFlags ){
30752         int fd;
30753         if( pFile->h>=0 ){
30754           robust_close(pFile, pFile->h, __LINE__);
30755         }
30756         pFile->h = -1;
30757         fd = robust_open(pCtx->dbPath, pFile->openFlags,
30758                       SQLITE_DEFAULT_FILE_PERMISSIONS);
30759         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
30760         if( fd>=0 ){
30761           pFile->h = fd;
30762         }else{
30763           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
30764            during locking */
30765         }
30766       }
30767       if( rc==SQLITE_OK && !pCtx->lockProxy ){
30768         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
30769         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
30770         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
30771           /* we couldn't create the proxy lock file with the old lock file path
30772            ** so try again via auto-naming
30773            */
30774           forceNewLockPath = 1;
30775           tryOldLockPath = 0;
30776           continue; /* go back to the do {} while start point, try again */
30777         }
30778       }
30779       if( rc==SQLITE_OK ){
30780         /* Need to make a copy of path if we extracted the value
30781          ** from the conch file or the path was allocated on the stack
30782          */
30783         if( tempLockPath ){
30784           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
30785           if( !pCtx->lockProxyPath ){
30786             rc = SQLITE_NOMEM;
30787           }
30788         }
30789       }
30790       if( rc==SQLITE_OK ){
30791         pCtx->conchHeld = 1;
30792 
30793         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
30794           afpLockingContext *afpCtx;
30795           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
30796           afpCtx->dbPath = pCtx->lockProxyPath;
30797         }
30798       } else {
30799         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30800       }
30801       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
30802                rc==SQLITE_OK?"ok":"failed"));
30803       return rc;
30804     } while (1); /* in case we need to retry the :auto: lock file -
30805                  ** we should never get here except via the 'continue' call. */
30806   }
30807 }
30808 
30809 /*
30810 ** If pFile holds a lock on a conch file, then release that lock.
30811 */
30812 static int proxyReleaseConch(unixFile *pFile){
30813   int rc = SQLITE_OK;         /* Subroutine return code */
30814   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
30815   unixFile *conchFile;        /* Name of the conch file */
30816 
30817   pCtx = (proxyLockingContext *)pFile->lockingContext;
30818   conchFile = pCtx->conchFile;
30819   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
30820            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
30821            getpid()));
30822   if( pCtx->conchHeld>0 ){
30823     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
30824   }
30825   pCtx->conchHeld = 0;
30826   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
30827            (rc==SQLITE_OK ? "ok" : "failed")));
30828   return rc;
30829 }
30830 
30831 /*
30832 ** Given the name of a database file, compute the name of its conch file.
30833 ** Store the conch filename in memory obtained from sqlite3_malloc().
30834 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
30835 ** or SQLITE_NOMEM if unable to obtain memory.
30836 **
30837 ** The caller is responsible for ensuring that the allocated memory
30838 ** space is eventually freed.
30839 **
30840 ** *pConchPath is set to NULL if a memory allocation error occurs.
30841 */
30842 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30843   int i;                        /* Loop counter */
30844   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30845   char *conchPath;              /* buffer in which to construct conch name */
30846 
30847   /* Allocate space for the conch filename and initialize the name to
30848   ** the name of the original database file. */
30849   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30850   if( conchPath==0 ){
30851     return SQLITE_NOMEM;
30852   }
30853   memcpy(conchPath, dbPath, len+1);
30854 
30855   /* now insert a "." before the last / character */
30856   for( i=(len-1); i>=0; i-- ){
30857     if( conchPath[i]=='/' ){
30858       i++;
30859       break;
30860     }
30861   }
30862   conchPath[i]='.';
30863   while ( i<len ){
30864     conchPath[i+1]=dbPath[i];
30865     i++;
30866   }
30867 
30868   /* append the "-conch" suffix to the file */
30869   memcpy(&conchPath[i+1], "-conch", 7);
30870   assert( (int)strlen(conchPath) == len+7 );
30871 
30872   return SQLITE_OK;
30873 }
30874 
30875 
30876 /* Takes a fully configured proxy locking-style unix file and switches
30877 ** the local lock file path
30878 */
30879 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30880   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30881   char *oldPath = pCtx->lockProxyPath;
30882   int rc = SQLITE_OK;
30883 
30884   if( pFile->eFileLock!=NO_LOCK ){
30885     return SQLITE_BUSY;
30886   }
30887 
30888   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30889   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30890     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30891     return SQLITE_OK;
30892   }else{
30893     unixFile *lockProxy = pCtx->lockProxy;
30894     pCtx->lockProxy=NULL;
30895     pCtx->conchHeld = 0;
30896     if( lockProxy!=NULL ){
30897       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30898       if( rc ) return rc;
30899       sqlite3_free(lockProxy);
30900     }
30901     sqlite3_free(oldPath);
30902     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30903   }
30904 
30905   return rc;
30906 }
30907 
30908 /*
30909 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30910 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30911 **
30912 ** This routine find the filename associated with pFile and writes it
30913 ** int dbPath.
30914 */
30915 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30916 #if defined(__APPLE__)
30917   if( pFile->pMethod == &afpIoMethods ){
30918     /* afp style keeps a reference to the db path in the filePath field
30919     ** of the struct */
30920     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30921     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30922   } else
30923 #endif
30924   if( pFile->pMethod == &dotlockIoMethods ){
30925     /* dot lock style uses the locking context to store the dot lock
30926     ** file path */
30927     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30928     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30929   }else{
30930     /* all other styles use the locking context to store the db file path */
30931     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30932     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30933   }
30934   return SQLITE_OK;
30935 }
30936 
30937 /*
30938 ** Takes an already filled in unix file and alters it so all file locking
30939 ** will be performed on the local proxy lock file.  The following fields
30940 ** are preserved in the locking context so that they can be restored and
30941 ** the unix structure properly cleaned up at close time:
30942 **  ->lockingContext
30943 **  ->pMethod
30944 */
30945 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30946   proxyLockingContext *pCtx;
30947   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30948   char *lockPath=NULL;
30949   int rc = SQLITE_OK;
30950 
30951   if( pFile->eFileLock!=NO_LOCK ){
30952     return SQLITE_BUSY;
30953   }
30954   proxyGetDbPathForUnixFile(pFile, dbPath);
30955   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30956     lockPath=NULL;
30957   }else{
30958     lockPath=(char *)path;
30959   }
30960 
30961   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30962            (lockPath ? lockPath : ":auto:"), getpid()));
30963 
30964   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30965   if( pCtx==0 ){
30966     return SQLITE_NOMEM;
30967   }
30968   memset(pCtx, 0, sizeof(*pCtx));
30969 
30970   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30971   if( rc==SQLITE_OK ){
30972     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30973     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30974       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30975       ** (c) the file system is read-only, then enable no-locking access.
30976       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30977       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30978       */
30979       struct statfs fsInfo;
30980       struct stat conchInfo;
30981       int goLockless = 0;
30982 
30983       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30984         int err = errno;
30985         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30986           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30987         }
30988       }
30989       if( goLockless ){
30990         pCtx->conchHeld = -1; /* read only FS/ lockless */
30991         rc = SQLITE_OK;
30992       }
30993     }
30994   }
30995   if( rc==SQLITE_OK && lockPath ){
30996     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30997   }
30998 
30999   if( rc==SQLITE_OK ){
31000     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31001     if( pCtx->dbPath==NULL ){
31002       rc = SQLITE_NOMEM;
31003     }
31004   }
31005   if( rc==SQLITE_OK ){
31006     /* all memory is allocated, proxys are created and assigned,
31007     ** switch the locking context and pMethod then return.
31008     */
31009     pCtx->oldLockingContext = pFile->lockingContext;
31010     pFile->lockingContext = pCtx;
31011     pCtx->pOldMethod = pFile->pMethod;
31012     pFile->pMethod = &proxyIoMethods;
31013   }else{
31014     if( pCtx->conchFile ){
31015       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31016       sqlite3_free(pCtx->conchFile);
31017     }
31018     sqlite3DbFree(0, pCtx->lockProxyPath);
31019     sqlite3_free(pCtx->conchFilePath);
31020     sqlite3_free(pCtx);
31021   }
31022   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31023            (rc==SQLITE_OK ? "ok" : "failed")));
31024   return rc;
31025 }
31026 
31027 
31028 /*
31029 ** This routine handles sqlite3_file_control() calls that are specific
31030 ** to proxy locking.
31031 */
31032 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31033   switch( op ){
31034     case SQLITE_GET_LOCKPROXYFILE: {
31035       unixFile *pFile = (unixFile*)id;
31036       if( pFile->pMethod == &proxyIoMethods ){
31037         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31038         proxyTakeConch(pFile);
31039         if( pCtx->lockProxyPath ){
31040           *(const char **)pArg = pCtx->lockProxyPath;
31041         }else{
31042           *(const char **)pArg = ":auto: (not held)";
31043         }
31044       } else {
31045         *(const char **)pArg = NULL;
31046       }
31047       return SQLITE_OK;
31048     }
31049     case SQLITE_SET_LOCKPROXYFILE: {
31050       unixFile *pFile = (unixFile*)id;
31051       int rc = SQLITE_OK;
31052       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31053       if( pArg==NULL || (const char *)pArg==0 ){
31054         if( isProxyStyle ){
31055           /* turn off proxy locking - not supported */
31056           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31057         }else{
31058           /* turn off proxy locking - already off - NOOP */
31059           rc = SQLITE_OK;
31060         }
31061       }else{
31062         const char *proxyPath = (const char *)pArg;
31063         if( isProxyStyle ){
31064           proxyLockingContext *pCtx =
31065             (proxyLockingContext*)pFile->lockingContext;
31066           if( !strcmp(pArg, ":auto:")
31067            || (pCtx->lockProxyPath &&
31068                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31069           ){
31070             rc = SQLITE_OK;
31071           }else{
31072             rc = switchLockProxyPath(pFile, proxyPath);
31073           }
31074         }else{
31075           /* turn on proxy file locking */
31076           rc = proxyTransformUnixFile(pFile, proxyPath);
31077         }
31078       }
31079       return rc;
31080     }
31081     default: {
31082       assert( 0 );  /* The call assures that only valid opcodes are sent */
31083     }
31084   }
31085   /*NOTREACHED*/
31086   return SQLITE_ERROR;
31087 }
31088 
31089 /*
31090 ** Within this division (the proxying locking implementation) the procedures
31091 ** above this point are all utilities.  The lock-related methods of the
31092 ** proxy-locking sqlite3_io_method object follow.
31093 */
31094 
31095 
31096 /*
31097 ** This routine checks if there is a RESERVED lock held on the specified
31098 ** file by this or any other process. If such a lock is held, set *pResOut
31099 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
31100 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31101 */
31102 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31103   unixFile *pFile = (unixFile*)id;
31104   int rc = proxyTakeConch(pFile);
31105   if( rc==SQLITE_OK ){
31106     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31107     if( pCtx->conchHeld>0 ){
31108       unixFile *proxy = pCtx->lockProxy;
31109       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31110     }else{ /* conchHeld < 0 is lockless */
31111       pResOut=0;
31112     }
31113   }
31114   return rc;
31115 }
31116 
31117 /*
31118 ** Lock the file with the lock specified by parameter eFileLock - one
31119 ** of the following:
31120 **
31121 **     (1) SHARED_LOCK
31122 **     (2) RESERVED_LOCK
31123 **     (3) PENDING_LOCK
31124 **     (4) EXCLUSIVE_LOCK
31125 **
31126 ** Sometimes when requesting one lock state, additional lock states
31127 ** are inserted in between.  The locking might fail on one of the later
31128 ** transitions leaving the lock state different from what it started but
31129 ** still short of its goal.  The following chart shows the allowed
31130 ** transitions and the inserted intermediate states:
31131 **
31132 **    UNLOCKED -> SHARED
31133 **    SHARED -> RESERVED
31134 **    SHARED -> (PENDING) -> EXCLUSIVE
31135 **    RESERVED -> (PENDING) -> EXCLUSIVE
31136 **    PENDING -> EXCLUSIVE
31137 **
31138 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31139 ** routine to lower a locking level.
31140 */
31141 static int proxyLock(sqlite3_file *id, int eFileLock) {
31142   unixFile *pFile = (unixFile*)id;
31143   int rc = proxyTakeConch(pFile);
31144   if( rc==SQLITE_OK ){
31145     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31146     if( pCtx->conchHeld>0 ){
31147       unixFile *proxy = pCtx->lockProxy;
31148       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31149       pFile->eFileLock = proxy->eFileLock;
31150     }else{
31151       /* conchHeld < 0 is lockless */
31152     }
31153   }
31154   return rc;
31155 }
31156 
31157 
31158 /*
31159 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31160 ** must be either NO_LOCK or SHARED_LOCK.
31161 **
31162 ** If the locking level of the file descriptor is already at or below
31163 ** the requested locking level, this routine is a no-op.
31164 */
31165 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31166   unixFile *pFile = (unixFile*)id;
31167   int rc = proxyTakeConch(pFile);
31168   if( rc==SQLITE_OK ){
31169     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31170     if( pCtx->conchHeld>0 ){
31171       unixFile *proxy = pCtx->lockProxy;
31172       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31173       pFile->eFileLock = proxy->eFileLock;
31174     }else{
31175       /* conchHeld < 0 is lockless */
31176     }
31177   }
31178   return rc;
31179 }
31180 
31181 /*
31182 ** Close a file that uses proxy locks.
31183 */
31184 static int proxyClose(sqlite3_file *id) {
31185   if( id ){
31186     unixFile *pFile = (unixFile*)id;
31187     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31188     unixFile *lockProxy = pCtx->lockProxy;
31189     unixFile *conchFile = pCtx->conchFile;
31190     int rc = SQLITE_OK;
31191 
31192     if( lockProxy ){
31193       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31194       if( rc ) return rc;
31195       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31196       if( rc ) return rc;
31197       sqlite3_free(lockProxy);
31198       pCtx->lockProxy = 0;
31199     }
31200     if( conchFile ){
31201       if( pCtx->conchHeld ){
31202         rc = proxyReleaseConch(pFile);
31203         if( rc ) return rc;
31204       }
31205       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31206       if( rc ) return rc;
31207       sqlite3_free(conchFile);
31208     }
31209     sqlite3DbFree(0, pCtx->lockProxyPath);
31210     sqlite3_free(pCtx->conchFilePath);
31211     sqlite3DbFree(0, pCtx->dbPath);
31212     /* restore the original locking context and pMethod then close it */
31213     pFile->lockingContext = pCtx->oldLockingContext;
31214     pFile->pMethod = pCtx->pOldMethod;
31215     sqlite3_free(pCtx);
31216     return pFile->pMethod->xClose(id);
31217   }
31218   return SQLITE_OK;
31219 }
31220 
31221 
31222 
31223 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31224 /*
31225 ** The proxy locking style is intended for use with AFP filesystems.
31226 ** And since AFP is only supported on MacOSX, the proxy locking is also
31227 ** restricted to MacOSX.
31228 **
31229 **
31230 ******************* End of the proxy lock implementation **********************
31231 ******************************************************************************/
31232 
31233 /*
31234 ** Initialize the operating system interface.
31235 **
31236 ** This routine registers all VFS implementations for unix-like operating
31237 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
31238 ** should be the only routines in this file that are visible from other
31239 ** files.
31240 **
31241 ** This routine is called once during SQLite initialization and by a
31242 ** single thread.  The memory allocation and mutex subsystems have not
31243 ** necessarily been initialized when this routine is called, and so they
31244 ** should not be used.
31245 */
31246 SQLITE_API int sqlite3_os_init(void){
31247   /*
31248   ** The following macro defines an initializer for an sqlite3_vfs object.
31249   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31250   ** to the "finder" function.  (pAppData is a pointer to a pointer because
31251   ** silly C90 rules prohibit a void* from being cast to a function pointer
31252   ** and so we have to go through the intermediate pointer to avoid problems
31253   ** when compiling with -pedantic-errors on GCC.)
31254   **
31255   ** The FINDER parameter to this macro is the name of the pointer to the
31256   ** finder-function.  The finder-function returns a pointer to the
31257   ** sqlite_io_methods object that implements the desired locking
31258   ** behaviors.  See the division above that contains the IOMETHODS
31259   ** macro for addition information on finder-functions.
31260   **
31261   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31262   ** object.  But the "autolockIoFinder" available on MacOSX does a little
31263   ** more than that; it looks at the filesystem type that hosts the
31264   ** database file and tries to choose an locking method appropriate for
31265   ** that filesystem time.
31266   */
31267   #define UNIXVFS(VFSNAME, FINDER) {                        \
31268     3,                    /* iVersion */                    \
31269     sizeof(unixFile),     /* szOsFile */                    \
31270     MAX_PATHNAME,         /* mxPathname */                  \
31271     0,                    /* pNext */                       \
31272     VFSNAME,              /* zName */                       \
31273     (void*)&FINDER,       /* pAppData */                    \
31274     unixOpen,             /* xOpen */                       \
31275     unixDelete,           /* xDelete */                     \
31276     unixAccess,           /* xAccess */                     \
31277     unixFullPathname,     /* xFullPathname */               \
31278     unixDlOpen,           /* xDlOpen */                     \
31279     unixDlError,          /* xDlError */                    \
31280     unixDlSym,            /* xDlSym */                      \
31281     unixDlClose,          /* xDlClose */                    \
31282     unixRandomness,       /* xRandomness */                 \
31283     unixSleep,            /* xSleep */                      \
31284     unixCurrentTime,      /* xCurrentTime */                \
31285     unixGetLastError,     /* xGetLastError */               \
31286     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31287     unixSetSystemCall,    /* xSetSystemCall */              \
31288     unixGetSystemCall,    /* xGetSystemCall */              \
31289     unixNextSystemCall,   /* xNextSystemCall */             \
31290   }
31291 
31292   /*
31293   ** All default VFSes for unix are contained in the following array.
31294   **
31295   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31296   ** by the SQLite core when the VFS is registered.  So the following
31297   ** array cannot be const.
31298   */
31299   static sqlite3_vfs aVfs[] = {
31300 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31301     UNIXVFS("unix",          autolockIoFinder ),
31302 #else
31303     UNIXVFS("unix",          posixIoFinder ),
31304 #endif
31305     UNIXVFS("unix-none",     nolockIoFinder ),
31306     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31307     UNIXVFS("unix-excl",     posixIoFinder ),
31308 #if OS_VXWORKS
31309     UNIXVFS("unix-namedsem", semIoFinder ),
31310 #endif
31311 #if SQLITE_ENABLE_LOCKING_STYLE
31312     UNIXVFS("unix-posix",    posixIoFinder ),
31313 #if !OS_VXWORKS
31314     UNIXVFS("unix-flock",    flockIoFinder ),
31315 #endif
31316 #endif
31317 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31318     UNIXVFS("unix-afp",      afpIoFinder ),
31319     UNIXVFS("unix-nfs",      nfsIoFinder ),
31320     UNIXVFS("unix-proxy",    proxyIoFinder ),
31321 #endif
31322   };
31323   unsigned int i;          /* Loop counter */
31324 
31325   /* Double-check that the aSyscall[] array has been constructed
31326   ** correctly.  See ticket [bb3a86e890c8e96ab] */
31327   assert( ArraySize(aSyscall)==18 );
31328 
31329   /* Register all VFSes defined in the aVfs[] array */
31330   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31331     sqlite3_vfs_register(&aVfs[i], i==0);
31332   }
31333   return SQLITE_OK;
31334 }
31335 
31336 /*
31337 ** Shutdown the operating system interface.
31338 **
31339 ** Some operating systems might need to do some cleanup in this routine,
31340 ** to release dynamically allocated objects.  But not on unix.
31341 ** This routine is a no-op for unix.
31342 */
31343 SQLITE_API int sqlite3_os_end(void){
31344   return SQLITE_OK;
31345 }
31346 
31347 #endif /* SQLITE_OS_UNIX */
31348 
31349 /************** End of os_unix.c *********************************************/
31350 /************** Begin file os_win.c ******************************************/
31351 /*
31352 ** 2004 May 22
31353 **
31354 ** The author disclaims copyright to this source code.  In place of
31355 ** a legal notice, here is a blessing:
31356 **
31357 **    May you do good and not evil.
31358 **    May you find forgiveness for yourself and forgive others.
31359 **    May you share freely, never taking more than you give.
31360 **
31361 ******************************************************************************
31362 **
31363 ** This file contains code that is specific to windows.
31364 */
31365 #if SQLITE_OS_WIN               /* This file is used for windows only */
31366 
31367 
31368 /*
31369 ** A Note About Memory Allocation:
31370 **
31371 ** This driver uses malloc()/free() directly rather than going through
31372 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
31373 ** are designed for use on embedded systems where memory is scarce and
31374 ** malloc failures happen frequently.  Win32 does not typically run on
31375 ** embedded systems, and when it does the developers normally have bigger
31376 ** problems to worry about than running out of memory.  So there is not
31377 ** a compelling need to use the wrappers.
31378 **
31379 ** But there is a good reason to not use the wrappers.  If we use the
31380 ** wrappers then we will get simulated malloc() failures within this
31381 ** driver.  And that causes all kinds of problems for our tests.  We
31382 ** could enhance SQLite to deal with simulated malloc failures within
31383 ** the OS driver, but the code to deal with those failure would not
31384 ** be exercised on Linux (which does not need to malloc() in the driver)
31385 ** and so we would have difficulty writing coverage tests for that
31386 ** code.  Better to leave the code out, we think.
31387 **
31388 ** The point of this discussion is as follows:  When creating a new
31389 ** OS layer for an embedded system, if you use this file as an example,
31390 ** avoid the use of malloc()/free().  Those routines work ok on windows
31391 ** desktops but not so well in embedded systems.
31392 */
31393 
31394 #include <winbase.h>
31395 
31396 #ifdef __CYGWIN__
31397 # include <sys/cygwin.h>
31398 #endif
31399 
31400 /*
31401 ** Macros used to determine whether or not to use threads.
31402 */
31403 #if defined(THREADSAFE) && THREADSAFE
31404 # define SQLITE_W32_THREADS 1
31405 #endif
31406 
31407 /*
31408 ** Include code that is common to all os_*.c files
31409 */
31410 /************** Include os_common.h in the middle of os_win.c ****************/
31411 /************** Begin file os_common.h ***************************************/
31412 /*
31413 ** 2004 May 22
31414 **
31415 ** The author disclaims copyright to this source code.  In place of
31416 ** a legal notice, here is a blessing:
31417 **
31418 **    May you do good and not evil.
31419 **    May you find forgiveness for yourself and forgive others.
31420 **    May you share freely, never taking more than you give.
31421 **
31422 ******************************************************************************
31423 **
31424 ** This file contains macros and a little bit of code that is common to
31425 ** all of the platform-specific files (os_*.c) and is #included into those
31426 ** files.
31427 **
31428 ** This file should be #included by the os_*.c files only.  It is not a
31429 ** general purpose header file.
31430 */
31431 #ifndef _OS_COMMON_H_
31432 #define _OS_COMMON_H_
31433 
31434 /*
31435 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31436 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31437 ** switch.  The following code should catch this problem at compile-time.
31438 */
31439 #ifdef MEMORY_DEBUG
31440 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31441 #endif
31442 
31443 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31444 # ifndef SQLITE_DEBUG_OS_TRACE
31445 #   define SQLITE_DEBUG_OS_TRACE 0
31446 # endif
31447   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31448 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31449 #else
31450 # define OSTRACE(X)
31451 #endif
31452 
31453 /*
31454 ** Macros for performance tracing.  Normally turned off.  Only works
31455 ** on i486 hardware.
31456 */
31457 #ifdef SQLITE_PERFORMANCE_TRACE
31458 
31459 /*
31460 ** hwtime.h contains inline assembler code for implementing
31461 ** high-performance timing routines.
31462 */
31463 /************** Include hwtime.h in the middle of os_common.h ****************/
31464 /************** Begin file hwtime.h ******************************************/
31465 /*
31466 ** 2008 May 27
31467 **
31468 ** The author disclaims copyright to this source code.  In place of
31469 ** a legal notice, here is a blessing:
31470 **
31471 **    May you do good and not evil.
31472 **    May you find forgiveness for yourself and forgive others.
31473 **    May you share freely, never taking more than you give.
31474 **
31475 ******************************************************************************
31476 **
31477 ** This file contains inline asm code for retrieving "high-performance"
31478 ** counters for x86 class CPUs.
31479 */
31480 #ifndef _HWTIME_H_
31481 #define _HWTIME_H_
31482 
31483 /*
31484 ** The following routine only works on pentium-class (or newer) processors.
31485 ** It uses the RDTSC opcode to read the cycle count value out of the
31486 ** processor and returns that value.  This can be used for high-res
31487 ** profiling.
31488 */
31489 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
31490       (defined(i386) || defined(__i386__) || defined(_M_IX86))
31491 
31492   #if defined(__GNUC__)
31493 
31494   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31495      unsigned int lo, hi;
31496      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
31497      return (sqlite_uint64)hi << 32 | lo;
31498   }
31499 
31500   #elif defined(_MSC_VER)
31501 
31502   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
31503      __asm {
31504         rdtsc
31505         ret       ; return value at EDX:EAX
31506      }
31507   }
31508 
31509   #endif
31510 
31511 #elif (defined(__GNUC__) && defined(__x86_64__))
31512 
31513   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31514       unsigned long val;
31515       __asm__ __volatile__ ("rdtsc" : "=A" (val));
31516       return val;
31517   }
31518 
31519 #elif (defined(__GNUC__) && defined(__ppc__))
31520 
31521   __inline__ sqlite_uint64 sqlite3Hwtime(void){
31522       unsigned long long retval;
31523       unsigned long junk;
31524       __asm__ __volatile__ ("\n\
31525           1:      mftbu   %1\n\
31526                   mftb    %L0\n\
31527                   mftbu   %0\n\
31528                   cmpw    %0,%1\n\
31529                   bne     1b"
31530                   : "=r" (retval), "=r" (junk));
31531       return retval;
31532   }
31533 
31534 #else
31535 
31536   #error Need implementation of sqlite3Hwtime() for your platform.
31537 
31538   /*
31539   ** To compile without implementing sqlite3Hwtime() for your platform,
31540   ** you can remove the above #error and use the following
31541   ** stub function.  You will lose timing support for many
31542   ** of the debugging and testing utilities, but it should at
31543   ** least compile and run.
31544   */
31545 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
31546 
31547 #endif
31548 
31549 #endif /* !defined(_HWTIME_H_) */
31550 
31551 /************** End of hwtime.h **********************************************/
31552 /************** Continuing where we left off in os_common.h ******************/
31553 
31554 static sqlite_uint64 g_start;
31555 static sqlite_uint64 g_elapsed;
31556 #define TIMER_START       g_start=sqlite3Hwtime()
31557 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
31558 #define TIMER_ELAPSED     g_elapsed
31559 #else
31560 #define TIMER_START
31561 #define TIMER_END
31562 #define TIMER_ELAPSED     ((sqlite_uint64)0)
31563 #endif
31564 
31565 /*
31566 ** If we compile with the SQLITE_TEST macro set, then the following block
31567 ** of code will give us the ability to simulate a disk I/O error.  This
31568 ** is used for testing the I/O recovery logic.
31569 */
31570 #ifdef SQLITE_TEST
31571 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
31572 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
31573 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
31574 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
31575 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
31576 SQLITE_API int sqlite3_diskfull_pending = 0;
31577 SQLITE_API int sqlite3_diskfull = 0;
31578 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
31579 #define SimulateIOError(CODE)  \
31580   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
31581        || sqlite3_io_error_pending-- == 1 )  \
31582               { local_ioerr(); CODE; }
31583 static void local_ioerr(){
31584   IOTRACE(("IOERR\n"));
31585   sqlite3_io_error_hit++;
31586   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
31587 }
31588 #define SimulateDiskfullError(CODE) \
31589    if( sqlite3_diskfull_pending ){ \
31590      if( sqlite3_diskfull_pending == 1 ){ \
31591        local_ioerr(); \
31592        sqlite3_diskfull = 1; \
31593        sqlite3_io_error_hit = 1; \
31594        CODE; \
31595      }else{ \
31596        sqlite3_diskfull_pending--; \
31597      } \
31598    }
31599 #else
31600 #define SimulateIOErrorBenign(X)
31601 #define SimulateIOError(A)
31602 #define SimulateDiskfullError(A)
31603 #endif
31604 
31605 /*
31606 ** When testing, keep a count of the number of open files.
31607 */
31608 #ifdef SQLITE_TEST
31609 SQLITE_API int sqlite3_open_file_count = 0;
31610 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
31611 #else
31612 #define OpenCounter(X)
31613 #endif
31614 
31615 #endif /* !defined(_OS_COMMON_H_) */
31616 
31617 /************** End of os_common.h *******************************************/
31618 /************** Continuing where we left off in os_win.c *********************/
31619 
31620 /*
31621 ** Some microsoft compilers lack this definition.
31622 */
31623 #ifndef INVALID_FILE_ATTRIBUTES
31624 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
31625 #endif
31626 
31627 /*
31628 ** Determine if we are dealing with WindowsCE - which has a much
31629 ** reduced API.
31630 */
31631 #if SQLITE_OS_WINCE
31632 # define AreFileApisANSI() 1
31633 # define FormatMessageW(a,b,c,d,e,f,g) 0
31634 #endif
31635 
31636 /* Forward references */
31637 typedef struct winShm winShm;           /* A connection to shared-memory */
31638 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
31639 
31640 /*
31641 ** WinCE lacks native support for file locking so we have to fake it
31642 ** with some code of our own.
31643 */
31644 #if SQLITE_OS_WINCE
31645 typedef struct winceLock {
31646   int nReaders;       /* Number of reader locks obtained */
31647   BOOL bPending;      /* Indicates a pending lock has been obtained */
31648   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
31649   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
31650 } winceLock;
31651 #endif
31652 
31653 /*
31654 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
31655 ** portability layer.
31656 */
31657 typedef struct winFile winFile;
31658 struct winFile {
31659   const sqlite3_io_methods *pMethod; /*** Must be first ***/
31660   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
31661   HANDLE h;               /* Handle for accessing the file */
31662   u8 locktype;            /* Type of lock currently held on this file */
31663   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
31664   u8 bPersistWal;         /* True to persist WAL files */
31665   DWORD lastErrno;        /* The Windows errno from the last I/O error */
31666   DWORD sectorSize;       /* Sector size of the device file is on */
31667   winShm *pShm;           /* Instance of shared memory on this file */
31668   const char *zPath;      /* Full pathname of this file */
31669   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
31670 #if SQLITE_OS_WINCE
31671   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
31672   HANDLE hMutex;          /* Mutex used to control access to shared lock */
31673   HANDLE hShared;         /* Shared memory segment used for locking */
31674   winceLock local;        /* Locks obtained by this instance of winFile */
31675   winceLock *shared;      /* Global shared lock memory for the file  */
31676 #endif
31677 };
31678 
31679 /*
31680  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
31681  * various Win32 API heap functions instead of our own.
31682  */
31683 #ifdef SQLITE_WIN32_MALLOC
31684 /*
31685  * The initial size of the Win32-specific heap.  This value may be zero.
31686  */
31687 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
31688 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
31689                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
31690 #endif
31691 
31692 /*
31693  * The maximum size of the Win32-specific heap.  This value may be zero.
31694  */
31695 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
31696 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
31697 #endif
31698 
31699 /*
31700  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
31701  * zero for the default behavior.
31702  */
31703 #ifndef SQLITE_WIN32_HEAP_FLAGS
31704 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
31705 #endif
31706 
31707 /*
31708 ** The winMemData structure stores information required by the Win32-specific
31709 ** sqlite3_mem_methods implementation.
31710 */
31711 typedef struct winMemData winMemData;
31712 struct winMemData {
31713 #ifndef NDEBUG
31714   u32 magic;    /* Magic number to detect structure corruption. */
31715 #endif
31716   HANDLE hHeap; /* The handle to our heap. */
31717   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
31718 };
31719 
31720 #ifndef NDEBUG
31721 #define WINMEM_MAGIC     0x42b2830b
31722 #endif
31723 
31724 static struct winMemData win_mem_data = {
31725 #ifndef NDEBUG
31726   WINMEM_MAGIC,
31727 #endif
31728   NULL, FALSE
31729 };
31730 
31731 #ifndef NDEBUG
31732 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
31733 #else
31734 #define winMemAssertMagic()
31735 #endif
31736 
31737 #define winMemGetHeap() win_mem_data.hHeap
31738 
31739 static void *winMemMalloc(int nBytes);
31740 static void winMemFree(void *pPrior);
31741 static void *winMemRealloc(void *pPrior, int nBytes);
31742 static int winMemSize(void *p);
31743 static int winMemRoundup(int n);
31744 static int winMemInit(void *pAppData);
31745 static void winMemShutdown(void *pAppData);
31746 
31747 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
31748 #endif /* SQLITE_WIN32_MALLOC */
31749 
31750 /*
31751 ** Forward prototypes.
31752 */
31753 static int getSectorSize(
31754     sqlite3_vfs *pVfs,
31755     const char *zRelative     /* UTF-8 file name */
31756 );
31757 
31758 /*
31759 ** The following variable is (normally) set once and never changes
31760 ** thereafter.  It records whether the operating system is Win95
31761 ** or WinNT.
31762 **
31763 ** 0:   Operating system unknown.
31764 ** 1:   Operating system is Win95.
31765 ** 2:   Operating system is WinNT.
31766 **
31767 ** In order to facilitate testing on a WinNT system, the test fixture
31768 ** can manually set this value to 1 to emulate Win98 behavior.
31769 */
31770 #ifdef SQLITE_TEST
31771 SQLITE_API int sqlite3_os_type = 0;
31772 #else
31773 static int sqlite3_os_type = 0;
31774 #endif
31775 
31776 /*
31777 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31778 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31779 **
31780 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31781 ** the LockFileEx() API.  But we can still statically link against that
31782 ** API as long as we don't call it when running Win95/98/ME.  A call to
31783 ** this routine is used to determine if the host is Win95/98/ME or
31784 ** WinNT/2K/XP so that we will know whether or not we can safely call
31785 ** the LockFileEx() API.
31786 */
31787 #if SQLITE_OS_WINCE
31788 # define isNT()  (1)
31789 #else
31790   static int isNT(void){
31791     if( sqlite3_os_type==0 ){
31792       OSVERSIONINFO sInfo;
31793       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31794       GetVersionEx(&sInfo);
31795       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31796     }
31797     return sqlite3_os_type==2;
31798   }
31799 #endif /* SQLITE_OS_WINCE */
31800 
31801 #ifdef SQLITE_WIN32_MALLOC
31802 /*
31803 ** Allocate nBytes of memory.
31804 */
31805 static void *winMemMalloc(int nBytes){
31806   HANDLE hHeap;
31807   void *p;
31808 
31809   winMemAssertMagic();
31810   hHeap = winMemGetHeap();
31811   assert( hHeap!=0 );
31812   assert( hHeap!=INVALID_HANDLE_VALUE );
31813 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31814   assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31815 #endif
31816   assert( nBytes>=0 );
31817   p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31818   if( !p ){
31819     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31820         nBytes, GetLastError(), (void*)hHeap);
31821   }
31822   return p;
31823 }
31824 
31825 /*
31826 ** Free memory.
31827 */
31828 static void winMemFree(void *pPrior){
31829   HANDLE hHeap;
31830 
31831   winMemAssertMagic();
31832   hHeap = winMemGetHeap();
31833   assert( hHeap!=0 );
31834   assert( hHeap!=INVALID_HANDLE_VALUE );
31835 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31836   assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31837 #endif
31838   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31839   if( !HeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31840     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31841         pPrior, GetLastError(), (void*)hHeap);
31842   }
31843 }
31844 
31845 /*
31846 ** Change the size of an existing memory allocation
31847 */
31848 static void *winMemRealloc(void *pPrior, int nBytes){
31849   HANDLE hHeap;
31850   void *p;
31851 
31852   winMemAssertMagic();
31853   hHeap = winMemGetHeap();
31854   assert( hHeap!=0 );
31855   assert( hHeap!=INVALID_HANDLE_VALUE );
31856 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31857   assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31858 #endif
31859   assert( nBytes>=0 );
31860   if( !pPrior ){
31861     p = HeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31862   }else{
31863     p = HeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31864   }
31865   if( !p ){
31866     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31867         pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, GetLastError(),
31868         (void*)hHeap);
31869   }
31870   return p;
31871 }
31872 
31873 /*
31874 ** Return the size of an outstanding allocation, in bytes.
31875 */
31876 static int winMemSize(void *p){
31877   HANDLE hHeap;
31878   SIZE_T n;
31879 
31880   winMemAssertMagic();
31881   hHeap = winMemGetHeap();
31882   assert( hHeap!=0 );
31883   assert( hHeap!=INVALID_HANDLE_VALUE );
31884 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31885   assert ( HeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31886 #endif
31887   if( !p ) return 0;
31888   n = HeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31889   if( n==(SIZE_T)-1 ){
31890     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31891         p, GetLastError(), (void*)hHeap);
31892     return 0;
31893   }
31894   return (int)n;
31895 }
31896 
31897 /*
31898 ** Round up a request size to the next valid allocation size.
31899 */
31900 static int winMemRoundup(int n){
31901   return n;
31902 }
31903 
31904 /*
31905 ** Initialize this module.
31906 */
31907 static int winMemInit(void *pAppData){
31908   winMemData *pWinMemData = (winMemData *)pAppData;
31909 
31910   if( !pWinMemData ) return SQLITE_ERROR;
31911   assert( pWinMemData->magic==WINMEM_MAGIC );
31912   if( !pWinMemData->hHeap ){
31913     pWinMemData->hHeap = HeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31914                                     SQLITE_WIN32_HEAP_INIT_SIZE,
31915                                     SQLITE_WIN32_HEAP_MAX_SIZE);
31916     if( !pWinMemData->hHeap ){
31917       sqlite3_log(SQLITE_NOMEM,
31918           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31919           GetLastError(), SQLITE_WIN32_HEAP_FLAGS, SQLITE_WIN32_HEAP_INIT_SIZE,
31920           SQLITE_WIN32_HEAP_MAX_SIZE);
31921       return SQLITE_NOMEM;
31922     }
31923     pWinMemData->bOwned = TRUE;
31924   }
31925   assert( pWinMemData->hHeap!=0 );
31926   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31927 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31928   assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31929 #endif
31930   return SQLITE_OK;
31931 }
31932 
31933 /*
31934 ** Deinitialize this module.
31935 */
31936 static void winMemShutdown(void *pAppData){
31937   winMemData *pWinMemData = (winMemData *)pAppData;
31938 
31939   if( !pWinMemData ) return;
31940   if( pWinMemData->hHeap ){
31941     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31942 #ifdef SQLITE_WIN32_MALLOC_VALIDATE
31943     assert( HeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31944 #endif
31945     if( pWinMemData->bOwned ){
31946       if( !HeapDestroy(pWinMemData->hHeap) ){
31947         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31948             GetLastError(), (void*)pWinMemData->hHeap);
31949       }
31950       pWinMemData->bOwned = FALSE;
31951     }
31952     pWinMemData->hHeap = NULL;
31953   }
31954 }
31955 
31956 /*
31957 ** Populate the low-level memory allocation function pointers in
31958 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31959 ** arguments specify the block of memory to manage.
31960 **
31961 ** This routine is only called by sqlite3_config(), and therefore
31962 ** is not required to be threadsafe (it is not).
31963 */
31964 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31965   static const sqlite3_mem_methods winMemMethods = {
31966     winMemMalloc,
31967     winMemFree,
31968     winMemRealloc,
31969     winMemSize,
31970     winMemRoundup,
31971     winMemInit,
31972     winMemShutdown,
31973     &win_mem_data
31974   };
31975   return &winMemMethods;
31976 }
31977 
31978 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31979   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31980 }
31981 #endif /* SQLITE_WIN32_MALLOC */
31982 
31983 /*
31984 ** Convert a UTF-8 string to microsoft unicode (UTF-16?).
31985 **
31986 ** Space to hold the returned string is obtained from malloc.
31987 */
31988 static WCHAR *utf8ToUnicode(const char *zFilename){
31989   int nChar;
31990   WCHAR *zWideFilename;
31991 
31992   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
31993   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
31994   if( zWideFilename==0 ){
31995     return 0;
31996   }
31997   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
31998   if( nChar==0 ){
31999     free(zWideFilename);
32000     zWideFilename = 0;
32001   }
32002   return zWideFilename;
32003 }
32004 
32005 /*
32006 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
32007 ** obtained from malloc().
32008 */
32009 static char *unicodeToUtf8(const WCHAR *zWideFilename){
32010   int nByte;
32011   char *zFilename;
32012 
32013   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32014   zFilename = malloc( nByte );
32015   if( zFilename==0 ){
32016     return 0;
32017   }
32018   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32019                               0, 0);
32020   if( nByte == 0 ){
32021     free(zFilename);
32022     zFilename = 0;
32023   }
32024   return zFilename;
32025 }
32026 
32027 /*
32028 ** Convert an ansi string to microsoft unicode, based on the
32029 ** current codepage settings for file apis.
32030 **
32031 ** Space to hold the returned string is obtained
32032 ** from malloc.
32033 */
32034 static WCHAR *mbcsToUnicode(const char *zFilename){
32035   int nByte;
32036   WCHAR *zMbcsFilename;
32037   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
32038 
32039   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
32040   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
32041   if( zMbcsFilename==0 ){
32042     return 0;
32043   }
32044   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
32045   if( nByte==0 ){
32046     free(zMbcsFilename);
32047     zMbcsFilename = 0;
32048   }
32049   return zMbcsFilename;
32050 }
32051 
32052 /*
32053 ** Convert microsoft unicode to multibyte character string, based on the
32054 ** user's Ansi codepage.
32055 **
32056 ** Space to hold the returned string is obtained from
32057 ** malloc().
32058 */
32059 static char *unicodeToMbcs(const WCHAR *zWideFilename){
32060   int nByte;
32061   char *zFilename;
32062   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
32063 
32064   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32065   zFilename = malloc( nByte );
32066   if( zFilename==0 ){
32067     return 0;
32068   }
32069   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
32070                               0, 0);
32071   if( nByte == 0 ){
32072     free(zFilename);
32073     zFilename = 0;
32074   }
32075   return zFilename;
32076 }
32077 
32078 /*
32079 ** Convert multibyte character string to UTF-8.  Space to hold the
32080 ** returned string is obtained from malloc().
32081 */
32082 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32083   char *zFilenameUtf8;
32084   WCHAR *zTmpWide;
32085 
32086   zTmpWide = mbcsToUnicode(zFilename);
32087   if( zTmpWide==0 ){
32088     return 0;
32089   }
32090   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
32091   free(zTmpWide);
32092   return zFilenameUtf8;
32093 }
32094 
32095 /*
32096 ** Convert UTF-8 to multibyte character string.  Space to hold the
32097 ** returned string is obtained from malloc().
32098 */
32099 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32100   char *zFilenameMbcs;
32101   WCHAR *zTmpWide;
32102 
32103   zTmpWide = utf8ToUnicode(zFilename);
32104   if( zTmpWide==0 ){
32105     return 0;
32106   }
32107   zFilenameMbcs = unicodeToMbcs(zTmpWide);
32108   free(zTmpWide);
32109   return zFilenameMbcs;
32110 }
32111 
32112 
32113 /*
32114 ** The return value of getLastErrorMsg
32115 ** is zero if the error message fits in the buffer, or non-zero
32116 ** otherwise (if the message was truncated).
32117 */
32118 static int getLastErrorMsg(int nBuf, char *zBuf){
32119   /* FormatMessage returns 0 on failure.  Otherwise it
32120   ** returns the number of TCHARs written to the output
32121   ** buffer, excluding the terminating null char.
32122   */
32123   DWORD error = GetLastError();
32124   DWORD dwLen = 0;
32125   char *zOut = 0;
32126 
32127   if( isNT() ){
32128     WCHAR *zTempWide = NULL;
32129     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
32130                            NULL,
32131                            error,
32132                            0,
32133                            (LPWSTR) &zTempWide,
32134                            0,
32135                            0);
32136     if( dwLen > 0 ){
32137       /* allocate a buffer and convert to UTF8 */
32138       zOut = unicodeToUtf8(zTempWide);
32139       /* free the system buffer allocated by FormatMessage */
32140       LocalFree(zTempWide);
32141     }
32142 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32143 ** Since the ASCII version of these Windows API do not exist for WINCE,
32144 ** it's important to not reference them for WINCE builds.
32145 */
32146 #if SQLITE_OS_WINCE==0
32147   }else{
32148     char *zTemp = NULL;
32149     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
32150                            NULL,
32151                            error,
32152                            0,
32153                            (LPSTR) &zTemp,
32154                            0,
32155                            0);
32156     if( dwLen > 0 ){
32157       /* allocate a buffer and convert to UTF8 */
32158       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32159       /* free the system buffer allocated by FormatMessage */
32160       LocalFree(zTemp);
32161     }
32162 #endif
32163   }
32164   if( 0 == dwLen ){
32165     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
32166   }else{
32167     /* copy a maximum of nBuf chars to output buffer */
32168     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32169     /* free the UTF8 buffer */
32170     free(zOut);
32171   }
32172   return 0;
32173 }
32174 
32175 /*
32176 **
32177 ** This function - winLogErrorAtLine() - is only ever called via the macro
32178 ** winLogError().
32179 **
32180 ** This routine is invoked after an error occurs in an OS function.
32181 ** It logs a message using sqlite3_log() containing the current value of
32182 ** error code and, if possible, the human-readable equivalent from
32183 ** FormatMessage.
32184 **
32185 ** The first argument passed to the macro should be the error code that
32186 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
32187 ** The two subsequent arguments should be the name of the OS function that
32188 ** failed and the the associated file-system path, if any.
32189 */
32190 #define winLogError(a,b,c)     winLogErrorAtLine(a,b,c,__LINE__)
32191 static int winLogErrorAtLine(
32192   int errcode,                    /* SQLite error code */
32193   const char *zFunc,              /* Name of OS function that failed */
32194   const char *zPath,              /* File path associated with error */
32195   int iLine                       /* Source line number where error occurred */
32196 ){
32197   char zMsg[500];                 /* Human readable error text */
32198   int i;                          /* Loop counter */
32199   DWORD iErrno = GetLastError();  /* Error code */
32200 
32201   zMsg[0] = 0;
32202   getLastErrorMsg(sizeof(zMsg), zMsg);
32203   assert( errcode!=SQLITE_OK );
32204   if( zPath==0 ) zPath = "";
32205   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32206   zMsg[i] = 0;
32207   sqlite3_log(errcode,
32208       "os_win.c:%d: (%d) %s(%s) - %s",
32209       iLine, iErrno, zFunc, zPath, zMsg
32210   );
32211 
32212   return errcode;
32213 }
32214 
32215 /*
32216 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32217 ** will be retried following a locking error - probably caused by
32218 ** antivirus software.  Also the initial delay before the first retry.
32219 ** The delay increases linearly with each retry.
32220 */
32221 #ifndef SQLITE_WIN32_IOERR_RETRY
32222 # define SQLITE_WIN32_IOERR_RETRY 10
32223 #endif
32224 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32225 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32226 #endif
32227 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32228 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32229 
32230 /*
32231 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
32232 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
32233 ** to give up with an error.
32234 */
32235 static int retryIoerr(int *pnRetry){
32236   DWORD e;
32237   if( *pnRetry>=win32IoerrRetry ){
32238     return 0;
32239   }
32240   e = GetLastError();
32241   if( e==ERROR_ACCESS_DENIED ||
32242       e==ERROR_LOCK_VIOLATION ||
32243       e==ERROR_SHARING_VIOLATION ){
32244     Sleep(win32IoerrRetryDelay*(1+*pnRetry));
32245     ++*pnRetry;
32246     return 1;
32247   }
32248   return 0;
32249 }
32250 
32251 /*
32252 ** Log a I/O error retry episode.
32253 */
32254 static void logIoerr(int nRetry){
32255   if( nRetry ){
32256     sqlite3_log(SQLITE_IOERR,
32257       "delayed %dms for lock/sharing conflict",
32258       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
32259     );
32260   }
32261 }
32262 
32263 #if SQLITE_OS_WINCE
32264 /*************************************************************************
32265 ** This section contains code for WinCE only.
32266 */
32267 /*
32268 ** WindowsCE does not have a localtime() function.  So create a
32269 ** substitute.
32270 */
32271 /* #include <time.h> */
32272 struct tm *__cdecl localtime(const time_t *t)
32273 {
32274   static struct tm y;
32275   FILETIME uTm, lTm;
32276   SYSTEMTIME pTm;
32277   sqlite3_int64 t64;
32278   t64 = *t;
32279   t64 = (t64 + 11644473600)*10000000;
32280   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32281   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32282   FileTimeToLocalFileTime(&uTm,&lTm);
32283   FileTimeToSystemTime(&lTm,&pTm);
32284   y.tm_year = pTm.wYear - 1900;
32285   y.tm_mon = pTm.wMonth - 1;
32286   y.tm_wday = pTm.wDayOfWeek;
32287   y.tm_mday = pTm.wDay;
32288   y.tm_hour = pTm.wHour;
32289   y.tm_min = pTm.wMinute;
32290   y.tm_sec = pTm.wSecond;
32291   return &y;
32292 }
32293 
32294 /* This will never be called, but defined to make the code compile */
32295 #define GetTempPathA(a,b)
32296 
32297 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
32298 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
32299 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
32300 
32301 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32302 
32303 /*
32304 ** Acquire a lock on the handle h
32305 */
32306 static void winceMutexAcquire(HANDLE h){
32307    DWORD dwErr;
32308    do {
32309      dwErr = WaitForSingleObject(h, INFINITE);
32310    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32311 }
32312 /*
32313 ** Release a lock acquired by winceMutexAcquire()
32314 */
32315 #define winceMutexRelease(h) ReleaseMutex(h)
32316 
32317 /*
32318 ** Create the mutex and shared memory used for locking in the file
32319 ** descriptor pFile
32320 */
32321 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
32322   WCHAR *zTok;
32323   WCHAR *zName = utf8ToUnicode(zFilename);
32324   BOOL bInit = TRUE;
32325 
32326   /* Initialize the local lockdata */
32327   ZeroMemory(&pFile->local, sizeof(pFile->local));
32328 
32329   /* Replace the backslashes from the filename and lowercase it
32330   ** to derive a mutex name. */
32331   zTok = CharLowerW(zName);
32332   for (;*zTok;zTok++){
32333     if (*zTok == '\\') *zTok = '_';
32334   }
32335 
32336   /* Create/open the named mutex */
32337   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
32338   if (!pFile->hMutex){
32339     pFile->lastErrno = GetLastError();
32340     winLogError(SQLITE_ERROR, "winceCreateLock1", zFilename);
32341     free(zName);
32342     return FALSE;
32343   }
32344 
32345   /* Acquire the mutex before continuing */
32346   winceMutexAcquire(pFile->hMutex);
32347 
32348   /* Since the names of named mutexes, semaphores, file mappings etc are
32349   ** case-sensitive, take advantage of that by uppercasing the mutex name
32350   ** and using that as the shared filemapping name.
32351   */
32352   CharUpperW(zName);
32353   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32354                                        PAGE_READWRITE, 0, sizeof(winceLock),
32355                                        zName);
32356 
32357   /* Set a flag that indicates we're the first to create the memory so it
32358   ** must be zero-initialized */
32359   if (GetLastError() == ERROR_ALREADY_EXISTS){
32360     bInit = FALSE;
32361   }
32362 
32363   free(zName);
32364 
32365   /* If we succeeded in making the shared memory handle, map it. */
32366   if (pFile->hShared){
32367     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
32368              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32369     /* If mapping failed, close the shared memory handle and erase it */
32370     if (!pFile->shared){
32371       pFile->lastErrno = GetLastError();
32372       winLogError(SQLITE_ERROR, "winceCreateLock2", zFilename);
32373       CloseHandle(pFile->hShared);
32374       pFile->hShared = NULL;
32375     }
32376   }
32377 
32378   /* If shared memory could not be created, then close the mutex and fail */
32379   if (pFile->hShared == NULL){
32380     winceMutexRelease(pFile->hMutex);
32381     CloseHandle(pFile->hMutex);
32382     pFile->hMutex = NULL;
32383     return FALSE;
32384   }
32385 
32386   /* Initialize the shared memory if we're supposed to */
32387   if (bInit) {
32388     ZeroMemory(pFile->shared, sizeof(winceLock));
32389   }
32390 
32391   winceMutexRelease(pFile->hMutex);
32392   return TRUE;
32393 }
32394 
32395 /*
32396 ** Destroy the part of winFile that deals with wince locks
32397 */
32398 static void winceDestroyLock(winFile *pFile){
32399   if (pFile->hMutex){
32400     /* Acquire the mutex */
32401     winceMutexAcquire(pFile->hMutex);
32402 
32403     /* The following blocks should probably assert in debug mode, but they
32404        are to cleanup in case any locks remained open */
32405     if (pFile->local.nReaders){
32406       pFile->shared->nReaders --;
32407     }
32408     if (pFile->local.bReserved){
32409       pFile->shared->bReserved = FALSE;
32410     }
32411     if (pFile->local.bPending){
32412       pFile->shared->bPending = FALSE;
32413     }
32414     if (pFile->local.bExclusive){
32415       pFile->shared->bExclusive = FALSE;
32416     }
32417 
32418     /* De-reference and close our copy of the shared memory handle */
32419     UnmapViewOfFile(pFile->shared);
32420     CloseHandle(pFile->hShared);
32421 
32422     /* Done with the mutex */
32423     winceMutexRelease(pFile->hMutex);
32424     CloseHandle(pFile->hMutex);
32425     pFile->hMutex = NULL;
32426   }
32427 }
32428 
32429 /*
32430 ** An implementation of the LockFile() API of windows for wince
32431 */
32432 static BOOL winceLockFile(
32433   HANDLE *phFile,
32434   DWORD dwFileOffsetLow,
32435   DWORD dwFileOffsetHigh,
32436   DWORD nNumberOfBytesToLockLow,
32437   DWORD nNumberOfBytesToLockHigh
32438 ){
32439   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32440   BOOL bReturn = FALSE;
32441 
32442   UNUSED_PARAMETER(dwFileOffsetHigh);
32443   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32444 
32445   if (!pFile->hMutex) return TRUE;
32446   winceMutexAcquire(pFile->hMutex);
32447 
32448   /* Wanting an exclusive lock? */
32449   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32450        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32451     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32452        pFile->shared->bExclusive = TRUE;
32453        pFile->local.bExclusive = TRUE;
32454        bReturn = TRUE;
32455     }
32456   }
32457 
32458   /* Want a read-only lock? */
32459   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32460            nNumberOfBytesToLockLow == 1){
32461     if (pFile->shared->bExclusive == 0){
32462       pFile->local.nReaders ++;
32463       if (pFile->local.nReaders == 1){
32464         pFile->shared->nReaders ++;
32465       }
32466       bReturn = TRUE;
32467     }
32468   }
32469 
32470   /* Want a pending lock? */
32471   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
32472     /* If no pending lock has been acquired, then acquire it */
32473     if (pFile->shared->bPending == 0) {
32474       pFile->shared->bPending = TRUE;
32475       pFile->local.bPending = TRUE;
32476       bReturn = TRUE;
32477     }
32478   }
32479 
32480   /* Want a reserved lock? */
32481   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
32482     if (pFile->shared->bReserved == 0) {
32483       pFile->shared->bReserved = TRUE;
32484       pFile->local.bReserved = TRUE;
32485       bReturn = TRUE;
32486     }
32487   }
32488 
32489   winceMutexRelease(pFile->hMutex);
32490   return bReturn;
32491 }
32492 
32493 /*
32494 ** An implementation of the UnlockFile API of windows for wince
32495 */
32496 static BOOL winceUnlockFile(
32497   HANDLE *phFile,
32498   DWORD dwFileOffsetLow,
32499   DWORD dwFileOffsetHigh,
32500   DWORD nNumberOfBytesToUnlockLow,
32501   DWORD nNumberOfBytesToUnlockHigh
32502 ){
32503   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32504   BOOL bReturn = FALSE;
32505 
32506   UNUSED_PARAMETER(dwFileOffsetHigh);
32507   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32508 
32509   if (!pFile->hMutex) return TRUE;
32510   winceMutexAcquire(pFile->hMutex);
32511 
32512   /* Releasing a reader lock or an exclusive lock */
32513   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32514     /* Did we have an exclusive lock? */
32515     if (pFile->local.bExclusive){
32516       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32517       pFile->local.bExclusive = FALSE;
32518       pFile->shared->bExclusive = FALSE;
32519       bReturn = TRUE;
32520     }
32521 
32522     /* Did we just have a reader lock? */
32523     else if (pFile->local.nReaders){
32524       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
32525       pFile->local.nReaders --;
32526       if (pFile->local.nReaders == 0)
32527       {
32528         pFile->shared->nReaders --;
32529       }
32530       bReturn = TRUE;
32531     }
32532   }
32533 
32534   /* Releasing a pending lock */
32535   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
32536     if (pFile->local.bPending){
32537       pFile->local.bPending = FALSE;
32538       pFile->shared->bPending = FALSE;
32539       bReturn = TRUE;
32540     }
32541   }
32542   /* Releasing a reserved lock */
32543   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
32544     if (pFile->local.bReserved) {
32545       pFile->local.bReserved = FALSE;
32546       pFile->shared->bReserved = FALSE;
32547       bReturn = TRUE;
32548     }
32549   }
32550 
32551   winceMutexRelease(pFile->hMutex);
32552   return bReturn;
32553 }
32554 
32555 /*
32556 ** An implementation of the LockFileEx() API of windows for wince
32557 */
32558 static BOOL winceLockFileEx(
32559   HANDLE *phFile,
32560   DWORD dwFlags,
32561   DWORD dwReserved,
32562   DWORD nNumberOfBytesToLockLow,
32563   DWORD nNumberOfBytesToLockHigh,
32564   LPOVERLAPPED lpOverlapped
32565 ){
32566   UNUSED_PARAMETER(dwReserved);
32567   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32568 
32569   /* If the caller wants a shared read lock, forward this call
32570   ** to winceLockFile */
32571   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
32572       dwFlags == 1 &&
32573       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32574     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
32575   }
32576   return FALSE;
32577 }
32578 /*
32579 ** End of the special code for wince
32580 *****************************************************************************/
32581 #endif /* SQLITE_OS_WINCE */
32582 
32583 /*****************************************************************************
32584 ** The next group of routines implement the I/O methods specified
32585 ** by the sqlite3_io_methods object.
32586 ******************************************************************************/
32587 
32588 /*
32589 ** Some microsoft compilers lack this definition.
32590 */
32591 #ifndef INVALID_SET_FILE_POINTER
32592 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32593 #endif
32594 
32595 /*
32596 ** Move the current position of the file handle passed as the first
32597 ** argument to offset iOffset within the file. If successful, return 0.
32598 ** Otherwise, set pFile->lastErrno and return non-zero.
32599 */
32600 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32601   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32602   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32603   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32604 
32605   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32606   lowerBits = (LONG)(iOffset & 0xffffffff);
32607 
32608   /* API oddity: If successful, SetFilePointer() returns a dword
32609   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32610   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
32611   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
32612   ** whether an error has actually occured, it is also necessary to call
32613   ** GetLastError().
32614   */
32615   dwRet = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32616   if( (dwRet==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR) ){
32617     pFile->lastErrno = GetLastError();
32618     winLogError(SQLITE_IOERR_SEEK, "seekWinFile", pFile->zPath);
32619     return 1;
32620   }
32621 
32622   return 0;
32623 }
32624 
32625 /*
32626 ** Close a file.
32627 **
32628 ** It is reported that an attempt to close a handle might sometimes
32629 ** fail.  This is a very unreasonable result, but windows is notorious
32630 ** for being unreasonable so I do not doubt that it might happen.  If
32631 ** the close fails, we pause for 100 milliseconds and try again.  As
32632 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32633 ** giving up and returning an error.
32634 */
32635 #define MX_CLOSE_ATTEMPT 3
32636 static int winClose(sqlite3_file *id){
32637   int rc, cnt = 0;
32638   winFile *pFile = (winFile*)id;
32639 
32640   assert( id!=0 );
32641   assert( pFile->pShm==0 );
32642   OSTRACE(("CLOSE %d\n", pFile->h));
32643   do{
32644     rc = CloseHandle(pFile->h);
32645     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32646   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
32647 #if SQLITE_OS_WINCE
32648 #define WINCE_DELETION_ATTEMPTS 3
32649   winceDestroyLock(pFile);
32650   if( pFile->zDeleteOnClose ){
32651     int cnt = 0;
32652     while(
32653            DeleteFileW(pFile->zDeleteOnClose)==0
32654         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
32655         && cnt++ < WINCE_DELETION_ATTEMPTS
32656     ){
32657        Sleep(100);  /* Wait a little before trying again */
32658     }
32659     free(pFile->zDeleteOnClose);
32660   }
32661 #endif
32662   OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
32663   OpenCounter(-1);
32664   return rc ? SQLITE_OK
32665             : winLogError(SQLITE_IOERR_CLOSE, "winClose", pFile->zPath);
32666 }
32667 
32668 /*
32669 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32670 ** bytes were read successfully and SQLITE_IOERR if anything goes
32671 ** wrong.
32672 */
32673 static int winRead(
32674   sqlite3_file *id,          /* File to read from */
32675   void *pBuf,                /* Write content into this buffer */
32676   int amt,                   /* Number of bytes to read */
32677   sqlite3_int64 offset       /* Begin reading at this offset */
32678 ){
32679   winFile *pFile = (winFile*)id;  /* file handle */
32680   DWORD nRead;                    /* Number of bytes actually read from file */
32681   int nRetry = 0;                 /* Number of retrys */
32682 
32683   assert( id!=0 );
32684   SimulateIOError(return SQLITE_IOERR_READ);
32685   OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
32686 
32687   if( seekWinFile(pFile, offset) ){
32688     return SQLITE_FULL;
32689   }
32690   while( !ReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32691     if( retryIoerr(&nRetry) ) continue;
32692     pFile->lastErrno = GetLastError();
32693     return winLogError(SQLITE_IOERR_READ, "winRead", pFile->zPath);
32694   }
32695   logIoerr(nRetry);
32696   if( nRead<(DWORD)amt ){
32697     /* Unread parts of the buffer must be zero-filled */
32698     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32699     return SQLITE_IOERR_SHORT_READ;
32700   }
32701 
32702   return SQLITE_OK;
32703 }
32704 
32705 /*
32706 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32707 ** or some other error code on failure.
32708 */
32709 static int winWrite(
32710   sqlite3_file *id,               /* File to write into */
32711   const void *pBuf,               /* The bytes to be written */
32712   int amt,                        /* Number of bytes to write */
32713   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32714 ){
32715   int rc;                         /* True if error has occured, else false */
32716   winFile *pFile = (winFile*)id;  /* File handle */
32717   int nRetry = 0;                 /* Number of retries */
32718 
32719   assert( amt>0 );
32720   assert( pFile );
32721   SimulateIOError(return SQLITE_IOERR_WRITE);
32722   SimulateDiskfullError(return SQLITE_FULL);
32723 
32724   OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
32725 
32726   rc = seekWinFile(pFile, offset);
32727   if( rc==0 ){
32728     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32729     int nRem = amt;               /* Number of bytes yet to be written */
32730     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32731 
32732     while( nRem>0 ){
32733       if( !WriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32734         if( retryIoerr(&nRetry) ) continue;
32735         break;
32736       }
32737       if( nWrite<=0 ) break;
32738       aRem += nWrite;
32739       nRem -= nWrite;
32740     }
32741     if( nRem>0 ){
32742       pFile->lastErrno = GetLastError();
32743       rc = 1;
32744     }
32745   }
32746 
32747   if( rc ){
32748     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
32749        || ( pFile->lastErrno==ERROR_DISK_FULL )){
32750       return SQLITE_FULL;
32751     }
32752     return winLogError(SQLITE_IOERR_WRITE, "winWrite", pFile->zPath);
32753   }else{
32754     logIoerr(nRetry);
32755   }
32756   return SQLITE_OK;
32757 }
32758 
32759 /*
32760 ** Truncate an open file to a specified size
32761 */
32762 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
32763   winFile *pFile = (winFile*)id;  /* File handle object */
32764   int rc = SQLITE_OK;             /* Return code for this function */
32765 
32766   assert( pFile );
32767 
32768   OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
32769   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
32770 
32771   /* If the user has configured a chunk-size for this file, truncate the
32772   ** file so that it consists of an integer number of chunks (i.e. the
32773   ** actual file size after the operation may be larger than the requested
32774   ** size).
32775   */
32776   if( pFile->szChunk>0 ){
32777     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32778   }
32779 
32780   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
32781   if( seekWinFile(pFile, nByte) ){
32782     rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate1", pFile->zPath);
32783   }else if( 0==SetEndOfFile(pFile->h) ){
32784     pFile->lastErrno = GetLastError();
32785     rc = winLogError(SQLITE_IOERR_TRUNCATE, "winTruncate2", pFile->zPath);
32786   }
32787 
32788   OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
32789   return rc;
32790 }
32791 
32792 #ifdef SQLITE_TEST
32793 /*
32794 ** Count the number of fullsyncs and normal syncs.  This is used to test
32795 ** that syncs and fullsyncs are occuring at the right times.
32796 */
32797 SQLITE_API int sqlite3_sync_count = 0;
32798 SQLITE_API int sqlite3_fullsync_count = 0;
32799 #endif
32800 
32801 /*
32802 ** Make sure all writes to a particular file are committed to disk.
32803 */
32804 static int winSync(sqlite3_file *id, int flags){
32805 #ifndef SQLITE_NO_SYNC
32806   /*
32807   ** Used only when SQLITE_NO_SYNC is not defined.
32808    */
32809   BOOL rc;
32810 #endif
32811 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
32812     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
32813   /*
32814   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
32815   ** OSTRACE() macros.
32816    */
32817   winFile *pFile = (winFile*)id;
32818 #else
32819   UNUSED_PARAMETER(id);
32820 #endif
32821 
32822   assert( pFile );
32823   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32824   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32825       || (flags&0x0F)==SQLITE_SYNC_FULL
32826   );
32827 
32828   OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
32829 
32830   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32831   ** line is to test that doing so does not cause any problems.
32832   */
32833   SimulateDiskfullError( return SQLITE_FULL );
32834 
32835 #ifndef SQLITE_TEST
32836   UNUSED_PARAMETER(flags);
32837 #else
32838   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
32839     sqlite3_fullsync_count++;
32840   }
32841   sqlite3_sync_count++;
32842 #endif
32843 
32844   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32845   ** no-op
32846   */
32847 #ifdef SQLITE_NO_SYNC
32848   return SQLITE_OK;
32849 #else
32850   rc = FlushFileBuffers(pFile->h);
32851   SimulateIOError( rc=FALSE );
32852   if( rc ){
32853     return SQLITE_OK;
32854   }else{
32855     pFile->lastErrno = GetLastError();
32856     return winLogError(SQLITE_IOERR_FSYNC, "winSync", pFile->zPath);
32857   }
32858 #endif
32859 }
32860 
32861 /*
32862 ** Determine the current size of a file in bytes
32863 */
32864 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
32865   DWORD upperBits;
32866   DWORD lowerBits;
32867   winFile *pFile = (winFile*)id;
32868   DWORD error;
32869 
32870   assert( id!=0 );
32871   SimulateIOError(return SQLITE_IOERR_FSTAT);
32872   lowerBits = GetFileSize(pFile->h, &upperBits);
32873   if(   (lowerBits == INVALID_FILE_SIZE)
32874      && ((error = GetLastError()) != NO_ERROR) )
32875   {
32876     pFile->lastErrno = error;
32877     return winLogError(SQLITE_IOERR_FSTAT, "winFileSize", pFile->zPath);
32878   }
32879   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
32880   return SQLITE_OK;
32881 }
32882 
32883 /*
32884 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
32885 */
32886 #ifndef LOCKFILE_FAIL_IMMEDIATELY
32887 # define LOCKFILE_FAIL_IMMEDIATELY 1
32888 #endif
32889 
32890 /*
32891 ** Acquire a reader lock.
32892 ** Different API routines are called depending on whether or not this
32893 ** is Win95 or WinNT.
32894 */
32895 static int getReadLock(winFile *pFile){
32896   int res;
32897   if( isNT() ){
32898     OVERLAPPED ovlp;
32899     ovlp.Offset = SHARED_FIRST;
32900     ovlp.OffsetHigh = 0;
32901     ovlp.hEvent = 0;
32902     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
32903                      0, SHARED_SIZE, 0, &ovlp);
32904 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32905 */
32906 #if SQLITE_OS_WINCE==0
32907   }else{
32908     int lk;
32909     sqlite3_randomness(sizeof(lk), &lk);
32910     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
32911     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
32912 #endif
32913   }
32914   if( res == 0 ){
32915     pFile->lastErrno = GetLastError();
32916     /* No need to log a failure to lock */
32917   }
32918   return res;
32919 }
32920 
32921 /*
32922 ** Undo a readlock
32923 */
32924 static int unlockReadLock(winFile *pFile){
32925   int res;
32926   if( isNT() ){
32927     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
32928 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
32929 */
32930 #if SQLITE_OS_WINCE==0
32931   }else{
32932     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
32933 #endif
32934   }
32935   if( res==0 && GetLastError()!=ERROR_NOT_LOCKED ){
32936     pFile->lastErrno = GetLastError();
32937     winLogError(SQLITE_IOERR_UNLOCK, "unlockReadLock", pFile->zPath);
32938   }
32939   return res;
32940 }
32941 
32942 /*
32943 ** Lock the file with the lock specified by parameter locktype - one
32944 ** of the following:
32945 **
32946 **     (1) SHARED_LOCK
32947 **     (2) RESERVED_LOCK
32948 **     (3) PENDING_LOCK
32949 **     (4) EXCLUSIVE_LOCK
32950 **
32951 ** Sometimes when requesting one lock state, additional lock states
32952 ** are inserted in between.  The locking might fail on one of the later
32953 ** transitions leaving the lock state different from what it started but
32954 ** still short of its goal.  The following chart shows the allowed
32955 ** transitions and the inserted intermediate states:
32956 **
32957 **    UNLOCKED -> SHARED
32958 **    SHARED -> RESERVED
32959 **    SHARED -> (PENDING) -> EXCLUSIVE
32960 **    RESERVED -> (PENDING) -> EXCLUSIVE
32961 **    PENDING -> EXCLUSIVE
32962 **
32963 ** This routine will only increase a lock.  The winUnlock() routine
32964 ** erases all locks at once and returns us immediately to locking level 0.
32965 ** It is not possible to lower the locking level one step at a time.  You
32966 ** must go straight to locking level 0.
32967 */
32968 static int winLock(sqlite3_file *id, int locktype){
32969   int rc = SQLITE_OK;    /* Return code from subroutines */
32970   int res = 1;           /* Result of a windows lock call */
32971   int newLocktype;       /* Set pFile->locktype to this value before exiting */
32972   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
32973   winFile *pFile = (winFile*)id;
32974   DWORD error = NO_ERROR;
32975 
32976   assert( id!=0 );
32977   OSTRACE(("LOCK %d %d was %d(%d)\n",
32978            pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
32979 
32980   /* If there is already a lock of this type or more restrictive on the
32981   ** OsFile, do nothing. Don't use the end_lock: exit path, as
32982   ** sqlite3OsEnterMutex() hasn't been called yet.
32983   */
32984   if( pFile->locktype>=locktype ){
32985     return SQLITE_OK;
32986   }
32987 
32988   /* Make sure the locking sequence is correct
32989   */
32990   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
32991   assert( locktype!=PENDING_LOCK );
32992   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
32993 
32994   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
32995   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
32996   ** the PENDING_LOCK byte is temporary.
32997   */
32998   newLocktype = pFile->locktype;
32999   if(   (pFile->locktype==NO_LOCK)
33000      || (   (locktype==EXCLUSIVE_LOCK)
33001          && (pFile->locktype==RESERVED_LOCK))
33002   ){
33003     int cnt = 3;
33004     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
33005       /* Try 3 times to get the pending lock.  The pending lock might be
33006       ** held by another reader process who will release it momentarily.
33007       */
33008       OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
33009       Sleep(1);
33010     }
33011     gotPendingLock = res;
33012     if( !res ){
33013       error = GetLastError();
33014     }
33015   }
33016 
33017   /* Acquire a shared lock
33018   */
33019   if( locktype==SHARED_LOCK && res ){
33020     assert( pFile->locktype==NO_LOCK );
33021     res = getReadLock(pFile);
33022     if( res ){
33023       newLocktype = SHARED_LOCK;
33024     }else{
33025       error = GetLastError();
33026     }
33027   }
33028 
33029   /* Acquire a RESERVED lock
33030   */
33031   if( locktype==RESERVED_LOCK && res ){
33032     assert( pFile->locktype==SHARED_LOCK );
33033     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33034     if( res ){
33035       newLocktype = RESERVED_LOCK;
33036     }else{
33037       error = GetLastError();
33038     }
33039   }
33040 
33041   /* Acquire a PENDING lock
33042   */
33043   if( locktype==EXCLUSIVE_LOCK && res ){
33044     newLocktype = PENDING_LOCK;
33045     gotPendingLock = 0;
33046   }
33047 
33048   /* Acquire an EXCLUSIVE lock
33049   */
33050   if( locktype==EXCLUSIVE_LOCK && res ){
33051     assert( pFile->locktype>=SHARED_LOCK );
33052     res = unlockReadLock(pFile);
33053     OSTRACE(("unreadlock = %d\n", res));
33054     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33055     if( res ){
33056       newLocktype = EXCLUSIVE_LOCK;
33057     }else{
33058       error = GetLastError();
33059       OSTRACE(("error-code = %d\n", error));
33060       getReadLock(pFile);
33061     }
33062   }
33063 
33064   /* If we are holding a PENDING lock that ought to be released, then
33065   ** release it now.
33066   */
33067   if( gotPendingLock && locktype==SHARED_LOCK ){
33068     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
33069   }
33070 
33071   /* Update the state of the lock has held in the file descriptor then
33072   ** return the appropriate result code.
33073   */
33074   if( res ){
33075     rc = SQLITE_OK;
33076   }else{
33077     OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
33078            locktype, newLocktype));
33079     pFile->lastErrno = error;
33080     rc = SQLITE_BUSY;
33081   }
33082   pFile->locktype = (u8)newLocktype;
33083   return rc;
33084 }
33085 
33086 /*
33087 ** This routine checks if there is a RESERVED lock held on the specified
33088 ** file by this or any other process. If such a lock is held, return
33089 ** non-zero, otherwise zero.
33090 */
33091 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33092   int rc;
33093   winFile *pFile = (winFile*)id;
33094 
33095   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33096 
33097   assert( id!=0 );
33098   if( pFile->locktype>=RESERVED_LOCK ){
33099     rc = 1;
33100     OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
33101   }else{
33102     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33103     if( rc ){
33104       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33105     }
33106     rc = !rc;
33107     OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
33108   }
33109   *pResOut = rc;
33110   return SQLITE_OK;
33111 }
33112 
33113 /*
33114 ** Lower the locking level on file descriptor id to locktype.  locktype
33115 ** must be either NO_LOCK or SHARED_LOCK.
33116 **
33117 ** If the locking level of the file descriptor is already at or below
33118 ** the requested locking level, this routine is a no-op.
33119 **
33120 ** It is not possible for this routine to fail if the second argument
33121 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
33122 ** might return SQLITE_IOERR;
33123 */
33124 static int winUnlock(sqlite3_file *id, int locktype){
33125   int type;
33126   winFile *pFile = (winFile*)id;
33127   int rc = SQLITE_OK;
33128   assert( pFile!=0 );
33129   assert( locktype<=SHARED_LOCK );
33130   OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
33131           pFile->locktype, pFile->sharedLockByte));
33132   type = pFile->locktype;
33133   if( type>=EXCLUSIVE_LOCK ){
33134     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33135     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
33136       /* This should never happen.  We should always be able to
33137       ** reacquire the read lock */
33138       rc = winLogError(SQLITE_IOERR_UNLOCK, "winUnlock", pFile->zPath);
33139     }
33140   }
33141   if( type>=RESERVED_LOCK ){
33142     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
33143   }
33144   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
33145     unlockReadLock(pFile);
33146   }
33147   if( type>=PENDING_LOCK ){
33148     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
33149   }
33150   pFile->locktype = (u8)locktype;
33151   return rc;
33152 }
33153 
33154 /*
33155 ** Control and query of the open file handle.
33156 */
33157 static int winFileControl(sqlite3_file *id, int op, void *pArg){
33158   winFile *pFile = (winFile*)id;
33159   switch( op ){
33160     case SQLITE_FCNTL_LOCKSTATE: {
33161       *(int*)pArg = pFile->locktype;
33162       return SQLITE_OK;
33163     }
33164     case SQLITE_LAST_ERRNO: {
33165       *(int*)pArg = (int)pFile->lastErrno;
33166       return SQLITE_OK;
33167     }
33168     case SQLITE_FCNTL_CHUNK_SIZE: {
33169       pFile->szChunk = *(int *)pArg;
33170       return SQLITE_OK;
33171     }
33172     case SQLITE_FCNTL_SIZE_HINT: {
33173       if( pFile->szChunk>0 ){
33174         sqlite3_int64 oldSz;
33175         int rc = winFileSize(id, &oldSz);
33176         if( rc==SQLITE_OK ){
33177           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
33178           if( newSz>oldSz ){
33179             SimulateIOErrorBenign(1);
33180             rc = winTruncate(id, newSz);
33181             SimulateIOErrorBenign(0);
33182           }
33183         }
33184         return rc;
33185       }
33186       return SQLITE_OK;
33187     }
33188     case SQLITE_FCNTL_PERSIST_WAL: {
33189       int bPersist = *(int*)pArg;
33190       if( bPersist<0 ){
33191         *(int*)pArg = pFile->bPersistWal;
33192       }else{
33193         pFile->bPersistWal = bPersist!=0;
33194       }
33195       return SQLITE_OK;
33196     }
33197     case SQLITE_FCNTL_SYNC_OMITTED: {
33198       return SQLITE_OK;
33199     }
33200     case SQLITE_FCNTL_WIN32_AV_RETRY: {
33201       int *a = (int*)pArg;
33202       if( a[0]>0 ){
33203         win32IoerrRetry = a[0];
33204       }else{
33205         a[0] = win32IoerrRetry;
33206       }
33207       if( a[1]>0 ){
33208         win32IoerrRetryDelay = a[1];
33209       }else{
33210         a[1] = win32IoerrRetryDelay;
33211       }
33212       return SQLITE_OK;
33213     }
33214   }
33215   return SQLITE_NOTFOUND;
33216 }
33217 
33218 /*
33219 ** Return the sector size in bytes of the underlying block device for
33220 ** the specified file. This is almost always 512 bytes, but may be
33221 ** larger for some devices.
33222 **
33223 ** SQLite code assumes this function cannot fail. It also assumes that
33224 ** if two files are created in the same file-system directory (i.e.
33225 ** a database and its journal file) that the sector size will be the
33226 ** same for both.
33227 */
33228 static int winSectorSize(sqlite3_file *id){
33229   assert( id!=0 );
33230   return (int)(((winFile*)id)->sectorSize);
33231 }
33232 
33233 /*
33234 ** Return a vector of device characteristics.
33235 */
33236 static int winDeviceCharacteristics(sqlite3_file *id){
33237   UNUSED_PARAMETER(id);
33238   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
33239 }
33240 
33241 #ifndef SQLITE_OMIT_WAL
33242 
33243 /*
33244 ** Windows will only let you create file view mappings
33245 ** on allocation size granularity boundaries.
33246 ** During sqlite3_os_init() we do a GetSystemInfo()
33247 ** to get the granularity size.
33248 */
33249 SYSTEM_INFO winSysInfo;
33250 
33251 /*
33252 ** Helper functions to obtain and relinquish the global mutex. The
33253 ** global mutex is used to protect the winLockInfo objects used by
33254 ** this file, all of which may be shared by multiple threads.
33255 **
33256 ** Function winShmMutexHeld() is used to assert() that the global mutex
33257 ** is held when required. This function is only used as part of assert()
33258 ** statements. e.g.
33259 **
33260 **   winShmEnterMutex()
33261 **     assert( winShmMutexHeld() );
33262 **   winShmLeaveMutex()
33263 */
33264 static void winShmEnterMutex(void){
33265   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33266 }
33267 static void winShmLeaveMutex(void){
33268   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33269 }
33270 #ifdef SQLITE_DEBUG
33271 static int winShmMutexHeld(void) {
33272   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33273 }
33274 #endif
33275 
33276 /*
33277 ** Object used to represent a single file opened and mmapped to provide
33278 ** shared memory.  When multiple threads all reference the same
33279 ** log-summary, each thread has its own winFile object, but they all
33280 ** point to a single instance of this object.  In other words, each
33281 ** log-summary is opened only once per process.
33282 **
33283 ** winShmMutexHeld() must be true when creating or destroying
33284 ** this object or while reading or writing the following fields:
33285 **
33286 **      nRef
33287 **      pNext
33288 **
33289 ** The following fields are read-only after the object is created:
33290 **
33291 **      fid
33292 **      zFilename
33293 **
33294 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33295 ** winShmMutexHeld() is true when reading or writing any other field
33296 ** in this structure.
33297 **
33298 */
33299 struct winShmNode {
33300   sqlite3_mutex *mutex;      /* Mutex to access this object */
33301   char *zFilename;           /* Name of the file */
33302   winFile hFile;             /* File handle from winOpen */
33303 
33304   int szRegion;              /* Size of shared-memory regions */
33305   int nRegion;               /* Size of array apRegion */
33306   struct ShmRegion {
33307     HANDLE hMap;             /* File handle from CreateFileMapping */
33308     void *pMap;
33309   } *aRegion;
33310   DWORD lastErrno;           /* The Windows errno from the last I/O error */
33311 
33312   int nRef;                  /* Number of winShm objects pointing to this */
33313   winShm *pFirst;            /* All winShm objects pointing to this */
33314   winShmNode *pNext;         /* Next in list of all winShmNode objects */
33315 #ifdef SQLITE_DEBUG
33316   u8 nextShmId;              /* Next available winShm.id value */
33317 #endif
33318 };
33319 
33320 /*
33321 ** A global array of all winShmNode objects.
33322 **
33323 ** The winShmMutexHeld() must be true while reading or writing this list.
33324 */
33325 static winShmNode *winShmNodeList = 0;
33326 
33327 /*
33328 ** Structure used internally by this VFS to record the state of an
33329 ** open shared memory connection.
33330 **
33331 ** The following fields are initialized when this object is created and
33332 ** are read-only thereafter:
33333 **
33334 **    winShm.pShmNode
33335 **    winShm.id
33336 **
33337 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
33338 ** while accessing any read/write fields.
33339 */
33340 struct winShm {
33341   winShmNode *pShmNode;      /* The underlying winShmNode object */
33342   winShm *pNext;             /* Next winShm with the same winShmNode */
33343   u8 hasMutex;               /* True if holding the winShmNode mutex */
33344   u16 sharedMask;            /* Mask of shared locks held */
33345   u16 exclMask;              /* Mask of exclusive locks held */
33346 #ifdef SQLITE_DEBUG
33347   u8 id;                     /* Id of this connection with its winShmNode */
33348 #endif
33349 };
33350 
33351 /*
33352 ** Constants used for locking
33353 */
33354 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33355 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33356 
33357 /*
33358 ** Apply advisory locks for all n bytes beginning at ofst.
33359 */
33360 #define _SHM_UNLCK  1
33361 #define _SHM_RDLCK  2
33362 #define _SHM_WRLCK  3
33363 static int winShmSystemLock(
33364   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33365   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33366   int ofst,             /* Offset to first byte to be locked/unlocked */
33367   int nByte             /* Number of bytes to lock or unlock */
33368 ){
33369   OVERLAPPED ovlp;
33370   DWORD dwFlags;
33371   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33372 
33373   /* Access to the winShmNode object is serialized by the caller */
33374   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33375 
33376   /* Initialize the locking parameters */
33377   dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33378   if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33379 
33380   memset(&ovlp, 0, sizeof(OVERLAPPED));
33381   ovlp.Offset = ofst;
33382 
33383   /* Release/Acquire the system-level lock */
33384   if( lockType==_SHM_UNLCK ){
33385     rc = UnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
33386   }else{
33387     rc = LockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
33388   }
33389 
33390   if( rc!= 0 ){
33391     rc = SQLITE_OK;
33392   }else{
33393     pFile->lastErrno =  GetLastError();
33394     rc = SQLITE_BUSY;
33395   }
33396 
33397   OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
33398            pFile->hFile.h,
33399            rc==SQLITE_OK ? "ok" : "failed",
33400            lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
33401            pFile->lastErrno));
33402 
33403   return rc;
33404 }
33405 
33406 /* Forward references to VFS methods */
33407 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33408 static int winDelete(sqlite3_vfs *,const char*,int);
33409 
33410 /*
33411 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33412 **
33413 ** This is not a VFS shared-memory method; it is a utility function called
33414 ** by VFS shared-memory methods.
33415 */
33416 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33417   winShmNode **pp;
33418   winShmNode *p;
33419   BOOL bRc;
33420   assert( winShmMutexHeld() );
33421   pp = &winShmNodeList;
33422   while( (p = *pp)!=0 ){
33423     if( p->nRef==0 ){
33424       int i;
33425       if( p->mutex ) sqlite3_mutex_free(p->mutex);
33426       for(i=0; i<p->nRegion; i++){
33427         bRc = UnmapViewOfFile(p->aRegion[i].pMap);
33428         OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
33429                  (int)GetCurrentProcessId(), i,
33430                  bRc ? "ok" : "failed"));
33431         bRc = CloseHandle(p->aRegion[i].hMap);
33432         OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
33433                  (int)GetCurrentProcessId(), i,
33434                  bRc ? "ok" : "failed"));
33435       }
33436       if( p->hFile.h != INVALID_HANDLE_VALUE ){
33437         SimulateIOErrorBenign(1);
33438         winClose((sqlite3_file *)&p->hFile);
33439         SimulateIOErrorBenign(0);
33440       }
33441       if( deleteFlag ){
33442         SimulateIOErrorBenign(1);
33443         winDelete(pVfs, p->zFilename, 0);
33444         SimulateIOErrorBenign(0);
33445       }
33446       *pp = p->pNext;
33447       sqlite3_free(p->aRegion);
33448       sqlite3_free(p);
33449     }else{
33450       pp = &p->pNext;
33451     }
33452   }
33453 }
33454 
33455 /*
33456 ** Open the shared-memory area associated with database file pDbFd.
33457 **
33458 ** When opening a new shared-memory file, if no other instances of that
33459 ** file are currently open, in this process or in other processes, then
33460 ** the file must be truncated to zero length or have its header cleared.
33461 */
33462 static int winOpenSharedMemory(winFile *pDbFd){
33463   struct winShm *p;                  /* The connection to be opened */
33464   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33465   int rc;                            /* Result code */
33466   struct winShmNode *pNew;           /* Newly allocated winShmNode */
33467   int nName;                         /* Size of zName in bytes */
33468 
33469   assert( pDbFd->pShm==0 );    /* Not previously opened */
33470 
33471   /* Allocate space for the new sqlite3_shm object.  Also speculatively
33472   ** allocate space for a new winShmNode and filename.
33473   */
33474   p = sqlite3_malloc( sizeof(*p) );
33475   if( p==0 ) return SQLITE_NOMEM;
33476   memset(p, 0, sizeof(*p));
33477   nName = sqlite3Strlen30(pDbFd->zPath);
33478   pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 15 );
33479   if( pNew==0 ){
33480     sqlite3_free(p);
33481     return SQLITE_NOMEM;
33482   }
33483   memset(pNew, 0, sizeof(*pNew));
33484   pNew->zFilename = (char*)&pNew[1];
33485   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33486   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
33487 
33488   /* Look to see if there is an existing winShmNode that can be used.
33489   ** If no matching winShmNode currently exists, create a new one.
33490   */
33491   winShmEnterMutex();
33492   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33493     /* TBD need to come up with better match here.  Perhaps
33494     ** use FILE_ID_BOTH_DIR_INFO Structure.
33495     */
33496     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33497   }
33498   if( pShmNode ){
33499     sqlite3_free(pNew);
33500   }else{
33501     pShmNode = pNew;
33502     pNew = 0;
33503     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33504     pShmNode->pNext = winShmNodeList;
33505     winShmNodeList = pShmNode;
33506 
33507     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33508     if( pShmNode->mutex==0 ){
33509       rc = SQLITE_NOMEM;
33510       goto shm_open_err;
33511     }
33512 
33513     rc = winOpen(pDbFd->pVfs,
33514                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33515                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33516                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
33517                  0);
33518     if( SQLITE_OK!=rc ){
33519       rc = SQLITE_CANTOPEN_BKPT;
33520       goto shm_open_err;
33521     }
33522 
33523     /* Check to see if another process is holding the dead-man switch.
33524     ** If not, truncate the file to zero length.
33525     */
33526     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33527       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33528       if( rc!=SQLITE_OK ){
33529         rc = winLogError(SQLITE_IOERR_SHMOPEN, "winOpenShm", pDbFd->zPath);
33530       }
33531     }
33532     if( rc==SQLITE_OK ){
33533       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33534       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33535     }
33536     if( rc ) goto shm_open_err;
33537   }
33538 
33539   /* Make the new connection a child of the winShmNode */
33540   p->pShmNode = pShmNode;
33541 #ifdef SQLITE_DEBUG
33542   p->id = pShmNode->nextShmId++;
33543 #endif
33544   pShmNode->nRef++;
33545   pDbFd->pShm = p;
33546   winShmLeaveMutex();
33547 
33548   /* The reference count on pShmNode has already been incremented under
33549   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33550   ** new (struct winShm) object to the pShmNode has been set. All that is
33551   ** left to do is to link the new object into the linked list starting
33552   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33553   ** mutex.
33554   */
33555   sqlite3_mutex_enter(pShmNode->mutex);
33556   p->pNext = pShmNode->pFirst;
33557   pShmNode->pFirst = p;
33558   sqlite3_mutex_leave(pShmNode->mutex);
33559   return SQLITE_OK;
33560 
33561   /* Jump here on any error */
33562 shm_open_err:
33563   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33564   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33565   sqlite3_free(p);
33566   sqlite3_free(pNew);
33567   winShmLeaveMutex();
33568   return rc;
33569 }
33570 
33571 /*
33572 ** Close a connection to shared-memory.  Delete the underlying
33573 ** storage if deleteFlag is true.
33574 */
33575 static int winShmUnmap(
33576   sqlite3_file *fd,          /* Database holding shared memory */
33577   int deleteFlag             /* Delete after closing if true */
33578 ){
33579   winFile *pDbFd;       /* Database holding shared-memory */
33580   winShm *p;            /* The connection to be closed */
33581   winShmNode *pShmNode; /* The underlying shared-memory file */
33582   winShm **pp;          /* For looping over sibling connections */
33583 
33584   pDbFd = (winFile*)fd;
33585   p = pDbFd->pShm;
33586   if( p==0 ) return SQLITE_OK;
33587   pShmNode = p->pShmNode;
33588 
33589   /* Remove connection p from the set of connections associated
33590   ** with pShmNode */
33591   sqlite3_mutex_enter(pShmNode->mutex);
33592   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33593   *pp = p->pNext;
33594 
33595   /* Free the connection p */
33596   sqlite3_free(p);
33597   pDbFd->pShm = 0;
33598   sqlite3_mutex_leave(pShmNode->mutex);
33599 
33600   /* If pShmNode->nRef has reached 0, then close the underlying
33601   ** shared-memory file, too */
33602   winShmEnterMutex();
33603   assert( pShmNode->nRef>0 );
33604   pShmNode->nRef--;
33605   if( pShmNode->nRef==0 ){
33606     winShmPurge(pDbFd->pVfs, deleteFlag);
33607   }
33608   winShmLeaveMutex();
33609 
33610   return SQLITE_OK;
33611 }
33612 
33613 /*
33614 ** Change the lock state for a shared-memory segment.
33615 */
33616 static int winShmLock(
33617   sqlite3_file *fd,          /* Database file holding the shared memory */
33618   int ofst,                  /* First lock to acquire or release */
33619   int n,                     /* Number of locks to acquire or release */
33620   int flags                  /* What to do with the lock */
33621 ){
33622   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
33623   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
33624   winShm *pX;                           /* For looping over all siblings */
33625   winShmNode *pShmNode = p->pShmNode;
33626   int rc = SQLITE_OK;                   /* Result code */
33627   u16 mask;                             /* Mask of locks to take or release */
33628 
33629   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33630   assert( n>=1 );
33631   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
33632        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
33633        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33634        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33635   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33636 
33637   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
33638   assert( n>1 || mask==(1<<ofst) );
33639   sqlite3_mutex_enter(pShmNode->mutex);
33640   if( flags & SQLITE_SHM_UNLOCK ){
33641     u16 allMask = 0; /* Mask of locks held by siblings */
33642 
33643     /* See if any siblings hold this same lock */
33644     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33645       if( pX==p ) continue;
33646       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33647       allMask |= pX->sharedMask;
33648     }
33649 
33650     /* Unlock the system-level locks */
33651     if( (mask & allMask)==0 ){
33652       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
33653     }else{
33654       rc = SQLITE_OK;
33655     }
33656 
33657     /* Undo the local locks */
33658     if( rc==SQLITE_OK ){
33659       p->exclMask &= ~mask;
33660       p->sharedMask &= ~mask;
33661     }
33662   }else if( flags & SQLITE_SHM_SHARED ){
33663     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
33664 
33665     /* Find out which shared locks are already held by sibling connections.
33666     ** If any sibling already holds an exclusive lock, go ahead and return
33667     ** SQLITE_BUSY.
33668     */
33669     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33670       if( (pX->exclMask & mask)!=0 ){
33671         rc = SQLITE_BUSY;
33672         break;
33673       }
33674       allShared |= pX->sharedMask;
33675     }
33676 
33677     /* Get shared locks at the system level, if necessary */
33678     if( rc==SQLITE_OK ){
33679       if( (allShared & mask)==0 ){
33680         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
33681       }else{
33682         rc = SQLITE_OK;
33683       }
33684     }
33685 
33686     /* Get the local shared locks */
33687     if( rc==SQLITE_OK ){
33688       p->sharedMask |= mask;
33689     }
33690   }else{
33691     /* Make sure no sibling connections hold locks that will block this
33692     ** lock.  If any do, return SQLITE_BUSY right away.
33693     */
33694     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33695       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33696         rc = SQLITE_BUSY;
33697         break;
33698       }
33699     }
33700 
33701     /* Get the exclusive locks at the system level.  Then if successful
33702     ** also mark the local connection as being locked.
33703     */
33704     if( rc==SQLITE_OK ){
33705       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
33706       if( rc==SQLITE_OK ){
33707         assert( (p->sharedMask & mask)==0 );
33708         p->exclMask |= mask;
33709       }
33710     }
33711   }
33712   sqlite3_mutex_leave(pShmNode->mutex);
33713   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
33714            p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
33715            rc ? "failed" : "ok"));
33716   return rc;
33717 }
33718 
33719 /*
33720 ** Implement a memory barrier or memory fence on shared memory.
33721 **
33722 ** All loads and stores begun before the barrier must complete before
33723 ** any load or store begun after the barrier.
33724 */
33725 static void winShmBarrier(
33726   sqlite3_file *fd          /* Database holding the shared memory */
33727 ){
33728   UNUSED_PARAMETER(fd);
33729   /* MemoryBarrier(); // does not work -- do not know why not */
33730   winShmEnterMutex();
33731   winShmLeaveMutex();
33732 }
33733 
33734 /*
33735 ** This function is called to obtain a pointer to region iRegion of the
33736 ** shared-memory associated with the database file fd. Shared-memory regions
33737 ** are numbered starting from zero. Each shared-memory region is szRegion
33738 ** bytes in size.
33739 **
33740 ** If an error occurs, an error code is returned and *pp is set to NULL.
33741 **
33742 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
33743 ** region has not been allocated (by any client, including one running in a
33744 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33745 ** isWrite is non-zero and the requested shared-memory region has not yet
33746 ** been allocated, it is allocated by this function.
33747 **
33748 ** If the shared-memory region has already been allocated or is allocated by
33749 ** this call as described above, then it is mapped into this processes
33750 ** address space (if it is not already), *pp is set to point to the mapped
33751 ** memory and SQLITE_OK returned.
33752 */
33753 static int winShmMap(
33754   sqlite3_file *fd,               /* Handle open on database file */
33755   int iRegion,                    /* Region to retrieve */
33756   int szRegion,                   /* Size of regions */
33757   int isWrite,                    /* True to extend file if necessary */
33758   void volatile **pp              /* OUT: Mapped memory */
33759 ){
33760   winFile *pDbFd = (winFile*)fd;
33761   winShm *p = pDbFd->pShm;
33762   winShmNode *pShmNode;
33763   int rc = SQLITE_OK;
33764 
33765   if( !p ){
33766     rc = winOpenSharedMemory(pDbFd);
33767     if( rc!=SQLITE_OK ) return rc;
33768     p = pDbFd->pShm;
33769   }
33770   pShmNode = p->pShmNode;
33771 
33772   sqlite3_mutex_enter(pShmNode->mutex);
33773   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33774 
33775   if( pShmNode->nRegion<=iRegion ){
33776     struct ShmRegion *apNew;           /* New aRegion[] array */
33777     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
33778     sqlite3_int64 sz;                  /* Current size of wal-index file */
33779 
33780     pShmNode->szRegion = szRegion;
33781 
33782     /* The requested region is not mapped into this processes address space.
33783     ** Check to see if it has been allocated (i.e. if the wal-index file is
33784     ** large enough to contain the requested region).
33785     */
33786     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
33787     if( rc!=SQLITE_OK ){
33788       rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap1", pDbFd->zPath);
33789       goto shmpage_out;
33790     }
33791 
33792     if( sz<nByte ){
33793       /* The requested memory region does not exist. If isWrite is set to
33794       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
33795       **
33796       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
33797       ** the requested memory region.
33798       */
33799       if( !isWrite ) goto shmpage_out;
33800       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
33801       if( rc!=SQLITE_OK ){
33802         rc = winLogError(SQLITE_IOERR_SHMSIZE, "winShmMap2", pDbFd->zPath);
33803         goto shmpage_out;
33804       }
33805     }
33806 
33807     /* Map the requested memory region into this processes address space. */
33808     apNew = (struct ShmRegion *)sqlite3_realloc(
33809         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
33810     );
33811     if( !apNew ){
33812       rc = SQLITE_IOERR_NOMEM;
33813       goto shmpage_out;
33814     }
33815     pShmNode->aRegion = apNew;
33816 
33817     while( pShmNode->nRegion<=iRegion ){
33818       HANDLE hMap;                /* file-mapping handle */
33819       void *pMap = 0;             /* Mapped memory region */
33820 
33821       hMap = CreateFileMapping(pShmNode->hFile.h,
33822           NULL, PAGE_READWRITE, 0, nByte, NULL
33823       );
33824       OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
33825                (int)GetCurrentProcessId(), pShmNode->nRegion, nByte,
33826                hMap ? "ok" : "failed"));
33827       if( hMap ){
33828         int iOffset = pShmNode->nRegion*szRegion;
33829         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33830         pMap = MapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
33831             0, iOffset - iOffsetShift, szRegion + iOffsetShift
33832         );
33833         OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
33834                  (int)GetCurrentProcessId(), pShmNode->nRegion, iOffset, szRegion,
33835                  pMap ? "ok" : "failed"));
33836       }
33837       if( !pMap ){
33838         pShmNode->lastErrno = GetLastError();
33839         rc = winLogError(SQLITE_IOERR_SHMMAP, "winShmMap3", pDbFd->zPath);
33840         if( hMap ) CloseHandle(hMap);
33841         goto shmpage_out;
33842       }
33843 
33844       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
33845       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
33846       pShmNode->nRegion++;
33847     }
33848   }
33849 
33850 shmpage_out:
33851   if( pShmNode->nRegion>iRegion ){
33852     int iOffset = iRegion*szRegion;
33853     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
33854     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
33855     *pp = (void *)&p[iOffsetShift];
33856   }else{
33857     *pp = 0;
33858   }
33859   sqlite3_mutex_leave(pShmNode->mutex);
33860   return rc;
33861 }
33862 
33863 #else
33864 # define winShmMap     0
33865 # define winShmLock    0
33866 # define winShmBarrier 0
33867 # define winShmUnmap   0
33868 #endif /* #ifndef SQLITE_OMIT_WAL */
33869 
33870 /*
33871 ** Here ends the implementation of all sqlite3_file methods.
33872 **
33873 ********************** End sqlite3_file Methods *******************************
33874 ******************************************************************************/
33875 
33876 /*
33877 ** This vector defines all the methods that can operate on an
33878 ** sqlite3_file for win32.
33879 */
33880 static const sqlite3_io_methods winIoMethod = {
33881   2,                              /* iVersion */
33882   winClose,                       /* xClose */
33883   winRead,                        /* xRead */
33884   winWrite,                       /* xWrite */
33885   winTruncate,                    /* xTruncate */
33886   winSync,                        /* xSync */
33887   winFileSize,                    /* xFileSize */
33888   winLock,                        /* xLock */
33889   winUnlock,                      /* xUnlock */
33890   winCheckReservedLock,           /* xCheckReservedLock */
33891   winFileControl,                 /* xFileControl */
33892   winSectorSize,                  /* xSectorSize */
33893   winDeviceCharacteristics,       /* xDeviceCharacteristics */
33894   winShmMap,                      /* xShmMap */
33895   winShmLock,                     /* xShmLock */
33896   winShmBarrier,                  /* xShmBarrier */
33897   winShmUnmap                     /* xShmUnmap */
33898 };
33899 
33900 /****************************************************************************
33901 **************************** sqlite3_vfs methods ****************************
33902 **
33903 ** This division contains the implementation of methods on the
33904 ** sqlite3_vfs object.
33905 */
33906 
33907 /*
33908 ** Convert a UTF-8 filename into whatever form the underlying
33909 ** operating system wants filenames in.  Space to hold the result
33910 ** is obtained from malloc and must be freed by the calling
33911 ** function.
33912 */
33913 static void *convertUtf8Filename(const char *zFilename){
33914   void *zConverted = 0;
33915   if( isNT() ){
33916     zConverted = utf8ToUnicode(zFilename);
33917 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33918 */
33919 #if SQLITE_OS_WINCE==0
33920   }else{
33921     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
33922 #endif
33923   }
33924   /* caller will handle out of memory */
33925   return zConverted;
33926 }
33927 
33928 /*
33929 ** Create a temporary file name in zBuf.  zBuf must be big enough to
33930 ** hold at pVfs->mxPathname characters.
33931 */
33932 static int getTempname(int nBuf, char *zBuf){
33933   static char zChars[] =
33934     "abcdefghijklmnopqrstuvwxyz"
33935     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
33936     "0123456789";
33937   size_t i, j;
33938   char zTempPath[MAX_PATH+1];
33939 
33940   /* It's odd to simulate an io-error here, but really this is just
33941   ** using the io-error infrastructure to test that SQLite handles this
33942   ** function failing.
33943   */
33944   SimulateIOError( return SQLITE_IOERR );
33945 
33946   if( sqlite3_temp_directory ){
33947     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
33948   }else if( isNT() ){
33949     char *zMulti;
33950     WCHAR zWidePath[MAX_PATH];
33951     GetTempPathW(MAX_PATH-30, zWidePath);
33952     zMulti = unicodeToUtf8(zWidePath);
33953     if( zMulti ){
33954       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
33955       free(zMulti);
33956     }else{
33957       return SQLITE_NOMEM;
33958     }
33959 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33960 ** Since the ASCII version of these Windows API do not exist for WINCE,
33961 ** it's important to not reference them for WINCE builds.
33962 */
33963 #if SQLITE_OS_WINCE==0
33964   }else{
33965     char *zUtf8;
33966     char zMbcsPath[MAX_PATH];
33967     GetTempPathA(MAX_PATH-30, zMbcsPath);
33968     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
33969     if( zUtf8 ){
33970       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
33971       free(zUtf8);
33972     }else{
33973       return SQLITE_NOMEM;
33974     }
33975 #endif
33976   }
33977 
33978   /* Check that the output buffer is large enough for the temporary file
33979   ** name. If it is not, return SQLITE_ERROR.
33980   */
33981   if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 17) >= nBuf ){
33982     return SQLITE_ERROR;
33983   }
33984 
33985   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
33986   zTempPath[i] = 0;
33987 
33988   sqlite3_snprintf(nBuf-17, zBuf,
33989                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
33990   j = sqlite3Strlen30(zBuf);
33991   sqlite3_randomness(15, &zBuf[j]);
33992   for(i=0; i<15; i++, j++){
33993     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
33994   }
33995   zBuf[j] = 0;
33996 
33997   OSTRACE(("TEMP FILENAME: %s\n", zBuf));
33998   return SQLITE_OK;
33999 }
34000 
34001 /*
34002 ** Open a file.
34003 */
34004 static int winOpen(
34005   sqlite3_vfs *pVfs,        /* Not used */
34006   const char *zName,        /* Name of the file (UTF-8) */
34007   sqlite3_file *id,         /* Write the SQLite file handle here */
34008   int flags,                /* Open mode flags */
34009   int *pOutFlags            /* Status return flags */
34010 ){
34011   HANDLE h;
34012   DWORD dwDesiredAccess;
34013   DWORD dwShareMode;
34014   DWORD dwCreationDisposition;
34015   DWORD dwFlagsAndAttributes = 0;
34016 #if SQLITE_OS_WINCE
34017   int isTemp = 0;
34018 #endif
34019   winFile *pFile = (winFile*)id;
34020   void *zConverted;              /* Filename in OS encoding */
34021   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
34022   int cnt = 0;
34023 
34024   /* If argument zPath is a NULL pointer, this function is required to open
34025   ** a temporary file. Use this buffer to store the file name in.
34026   */
34027   char zTmpname[MAX_PATH+1];     /* Buffer used to create temp filename */
34028 
34029   int rc = SQLITE_OK;            /* Function Return Code */
34030 #if !defined(NDEBUG) || SQLITE_OS_WINCE
34031   int eType = flags&0xFFFFFF00;  /* Type of file to open */
34032 #endif
34033 
34034   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
34035   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
34036   int isCreate     = (flags & SQLITE_OPEN_CREATE);
34037 #ifndef NDEBUG
34038   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
34039 #endif
34040   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
34041 
34042 #ifndef NDEBUG
34043   int isOpenJournal = (isCreate && (
34044         eType==SQLITE_OPEN_MASTER_JOURNAL
34045      || eType==SQLITE_OPEN_MAIN_JOURNAL
34046      || eType==SQLITE_OPEN_WAL
34047   ));
34048 #endif
34049 
34050   /* Check the following statements are true:
34051   **
34052   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
34053   **   (b) if CREATE is set, then READWRITE must also be set, and
34054   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
34055   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
34056   */
34057   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34058   assert(isCreate==0 || isReadWrite);
34059   assert(isExclusive==0 || isCreate);
34060   assert(isDelete==0 || isCreate);
34061 
34062   /* The main DB, main journal, WAL file and master journal are never
34063   ** automatically deleted. Nor are they ever temporary files.  */
34064   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34065   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34066   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34067   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34068 
34069   /* Assert that the upper layer has set one of the "file-type" flags. */
34070   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
34071        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
34072        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
34073        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34074   );
34075 
34076   assert( id!=0 );
34077   UNUSED_PARAMETER(pVfs);
34078 
34079   pFile->h = INVALID_HANDLE_VALUE;
34080 
34081   /* If the second argument to this function is NULL, generate a
34082   ** temporary file name to use
34083   */
34084   if( !zUtf8Name ){
34085     assert(isDelete && !isOpenJournal);
34086     rc = getTempname(MAX_PATH+1, zTmpname);
34087     if( rc!=SQLITE_OK ){
34088       return rc;
34089     }
34090     zUtf8Name = zTmpname;
34091   }
34092 
34093   /* Convert the filename to the system encoding. */
34094   zConverted = convertUtf8Filename(zUtf8Name);
34095   if( zConverted==0 ){
34096     return SQLITE_NOMEM;
34097   }
34098 
34099   if( isReadWrite ){
34100     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
34101   }else{
34102     dwDesiredAccess = GENERIC_READ;
34103   }
34104 
34105   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
34106   ** created. SQLite doesn't use it to indicate "exclusive access"
34107   ** as it is usually understood.
34108   */
34109   if( isExclusive ){
34110     /* Creates a new file, only if it does not already exist. */
34111     /* If the file exists, it fails. */
34112     dwCreationDisposition = CREATE_NEW;
34113   }else if( isCreate ){
34114     /* Open existing file, or create if it doesn't exist */
34115     dwCreationDisposition = OPEN_ALWAYS;
34116   }else{
34117     /* Opens a file, only if it exists. */
34118     dwCreationDisposition = OPEN_EXISTING;
34119   }
34120 
34121   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
34122 
34123   if( isDelete ){
34124 #if SQLITE_OS_WINCE
34125     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
34126     isTemp = 1;
34127 #else
34128     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
34129                                | FILE_ATTRIBUTE_HIDDEN
34130                                | FILE_FLAG_DELETE_ON_CLOSE;
34131 #endif
34132   }else{
34133     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
34134   }
34135   /* Reports from the internet are that performance is always
34136   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
34137 #if SQLITE_OS_WINCE
34138   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
34139 #endif
34140 
34141   if( isNT() ){
34142     while( (h = CreateFileW((WCHAR*)zConverted,
34143                             dwDesiredAccess,
34144                             dwShareMode, NULL,
34145                             dwCreationDisposition,
34146                             dwFlagsAndAttributes,
34147                             NULL))==INVALID_HANDLE_VALUE &&
34148                             retryIoerr(&cnt) ){}
34149 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34150 ** Since the ASCII version of these Windows API do not exist for WINCE,
34151 ** it's important to not reference them for WINCE builds.
34152 */
34153 #if SQLITE_OS_WINCE==0
34154   }else{
34155     while( (h = CreateFileA((char*)zConverted,
34156                             dwDesiredAccess,
34157                             dwShareMode, NULL,
34158                             dwCreationDisposition,
34159                             dwFlagsAndAttributes,
34160                             NULL))==INVALID_HANDLE_VALUE &&
34161                             retryIoerr(&cnt) ){}
34162 #endif
34163   }
34164 
34165   logIoerr(cnt);
34166 
34167   OSTRACE(("OPEN %d %s 0x%lx %s\n",
34168            h, zName, dwDesiredAccess,
34169            h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
34170 
34171   if( h==INVALID_HANDLE_VALUE ){
34172     pFile->lastErrno = GetLastError();
34173     winLogError(SQLITE_CANTOPEN, "winOpen", zUtf8Name);
34174     free(zConverted);
34175     if( isReadWrite ){
34176       return winOpen(pVfs, zName, id,
34177              ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
34178     }else{
34179       return SQLITE_CANTOPEN_BKPT;
34180     }
34181   }
34182 
34183   if( pOutFlags ){
34184     if( isReadWrite ){
34185       *pOutFlags = SQLITE_OPEN_READWRITE;
34186     }else{
34187       *pOutFlags = SQLITE_OPEN_READONLY;
34188     }
34189   }
34190 
34191   memset(pFile, 0, sizeof(*pFile));
34192   pFile->pMethod = &winIoMethod;
34193   pFile->h = h;
34194   pFile->lastErrno = NO_ERROR;
34195   pFile->pVfs = pVfs;
34196   pFile->pShm = 0;
34197   pFile->zPath = zName;
34198   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
34199 
34200 #if SQLITE_OS_WINCE
34201   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34202        && !winceCreateLock(zName, pFile)
34203   ){
34204     CloseHandle(h);
34205     free(zConverted);
34206     return SQLITE_CANTOPEN_BKPT;
34207   }
34208   if( isTemp ){
34209     pFile->zDeleteOnClose = zConverted;
34210   }else
34211 #endif
34212   {
34213     free(zConverted);
34214   }
34215 
34216   OpenCounter(+1);
34217   return rc;
34218 }
34219 
34220 /*
34221 ** Delete the named file.
34222 **
34223 ** Note that windows does not allow a file to be deleted if some other
34224 ** process has it open.  Sometimes a virus scanner or indexing program
34225 ** will open a journal file shortly after it is created in order to do
34226 ** whatever it does.  While this other process is holding the
34227 ** file open, we will be unable to delete it.  To work around this
34228 ** problem, we delay 100 milliseconds and try to delete again.  Up
34229 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34230 ** up and returning an error.
34231 */
34232 static int winDelete(
34233   sqlite3_vfs *pVfs,          /* Not used on win32 */
34234   const char *zFilename,      /* Name of file to delete */
34235   int syncDir                 /* Not used on win32 */
34236 ){
34237   int cnt = 0;
34238   int rc;
34239   void *zConverted;
34240   UNUSED_PARAMETER(pVfs);
34241   UNUSED_PARAMETER(syncDir);
34242 
34243   SimulateIOError(return SQLITE_IOERR_DELETE);
34244   zConverted = convertUtf8Filename(zFilename);
34245   if( zConverted==0 ){
34246     return SQLITE_NOMEM;
34247   }
34248   if( isNT() ){
34249     rc = 1;
34250     while( GetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
34251            (rc = DeleteFileW(zConverted))==0 && retryIoerr(&cnt) ){}
34252     rc = rc ? SQLITE_OK : SQLITE_ERROR;
34253 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34254 ** Since the ASCII version of these Windows API do not exist for WINCE,
34255 ** it's important to not reference them for WINCE builds.
34256 */
34257 #if SQLITE_OS_WINCE==0
34258   }else{
34259     rc = 1;
34260     while( GetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
34261            (rc = DeleteFileA(zConverted))==0 && retryIoerr(&cnt) ){}
34262     rc = rc ? SQLITE_OK : SQLITE_ERROR;
34263 #endif
34264   }
34265   if( rc ){
34266     rc = winLogError(SQLITE_IOERR_DELETE, "winDelete", zFilename);
34267   }else{
34268     logIoerr(cnt);
34269   }
34270   free(zConverted);
34271   OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
34272   return rc;
34273 }
34274 
34275 /*
34276 ** Check the existance and status of a file.
34277 */
34278 static int winAccess(
34279   sqlite3_vfs *pVfs,         /* Not used on win32 */
34280   const char *zFilename,     /* Name of file to check */
34281   int flags,                 /* Type of test to make on this file */
34282   int *pResOut               /* OUT: Result */
34283 ){
34284   DWORD attr;
34285   int rc = 0;
34286   void *zConverted;
34287   UNUSED_PARAMETER(pVfs);
34288 
34289   SimulateIOError( return SQLITE_IOERR_ACCESS; );
34290   zConverted = convertUtf8Filename(zFilename);
34291   if( zConverted==0 ){
34292     return SQLITE_NOMEM;
34293   }
34294   if( isNT() ){
34295     int cnt = 0;
34296     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34297     memset(&sAttrData, 0, sizeof(sAttrData));
34298     while( !(rc = GetFileAttributesExW((WCHAR*)zConverted,
34299                              GetFileExInfoStandard,
34300                              &sAttrData)) && retryIoerr(&cnt) ){}
34301     if( rc ){
34302       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
34303       ** as if it does not exist.
34304       */
34305       if(    flags==SQLITE_ACCESS_EXISTS
34306           && sAttrData.nFileSizeHigh==0
34307           && sAttrData.nFileSizeLow==0 ){
34308         attr = INVALID_FILE_ATTRIBUTES;
34309       }else{
34310         attr = sAttrData.dwFileAttributes;
34311       }
34312     }else{
34313       logIoerr(cnt);
34314       if( GetLastError()!=ERROR_FILE_NOT_FOUND ){
34315         winLogError(SQLITE_IOERR_ACCESS, "winAccess", zFilename);
34316         free(zConverted);
34317         return SQLITE_IOERR_ACCESS;
34318       }else{
34319         attr = INVALID_FILE_ATTRIBUTES;
34320       }
34321     }
34322 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34323 ** Since the ASCII version of these Windows API do not exist for WINCE,
34324 ** it's important to not reference them for WINCE builds.
34325 */
34326 #if SQLITE_OS_WINCE==0
34327   }else{
34328     attr = GetFileAttributesA((char*)zConverted);
34329 #endif
34330   }
34331   free(zConverted);
34332   switch( flags ){
34333     case SQLITE_ACCESS_READ:
34334     case SQLITE_ACCESS_EXISTS:
34335       rc = attr!=INVALID_FILE_ATTRIBUTES;
34336       break;
34337     case SQLITE_ACCESS_READWRITE:
34338       rc = attr!=INVALID_FILE_ATTRIBUTES &&
34339              (attr & FILE_ATTRIBUTE_READONLY)==0;
34340       break;
34341     default:
34342       assert(!"Invalid flags argument");
34343   }
34344   *pResOut = rc;
34345   return SQLITE_OK;
34346 }
34347 
34348 
34349 /*
34350 ** Turn a relative pathname into a full pathname.  Write the full
34351 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
34352 ** bytes in size.
34353 */
34354 static int winFullPathname(
34355   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
34356   const char *zRelative,        /* Possibly relative input path */
34357   int nFull,                    /* Size of output buffer in bytes */
34358   char *zFull                   /* Output buffer */
34359 ){
34360 
34361 #if defined(__CYGWIN__)
34362   SimulateIOError( return SQLITE_ERROR );
34363   UNUSED_PARAMETER(nFull);
34364   cygwin_conv_to_full_win32_path(zRelative, zFull);
34365   return SQLITE_OK;
34366 #endif
34367 
34368 #if SQLITE_OS_WINCE
34369   SimulateIOError( return SQLITE_ERROR );
34370   UNUSED_PARAMETER(nFull);
34371   /* WinCE has no concept of a relative pathname, or so I am told. */
34372   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
34373   return SQLITE_OK;
34374 #endif
34375 
34376 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
34377   int nByte;
34378   void *zConverted;
34379   char *zOut;
34380 
34381   /* If this path name begins with "/X:", where "X" is any alphabetic
34382   ** character, discard the initial "/" from the pathname.
34383   */
34384   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
34385     zRelative++;
34386   }
34387 
34388   /* It's odd to simulate an io-error here, but really this is just
34389   ** using the io-error infrastructure to test that SQLite handles this
34390   ** function failing. This function could fail if, for example, the
34391   ** current working directory has been unlinked.
34392   */
34393   SimulateIOError( return SQLITE_ERROR );
34394   UNUSED_PARAMETER(nFull);
34395   zConverted = convertUtf8Filename(zRelative);
34396   if( isNT() ){
34397     WCHAR *zTemp;
34398     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
34399     zTemp = malloc( nByte*sizeof(zTemp[0]) );
34400     if( zTemp==0 ){
34401       free(zConverted);
34402       return SQLITE_NOMEM;
34403     }
34404     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
34405     free(zConverted);
34406     zOut = unicodeToUtf8(zTemp);
34407     free(zTemp);
34408 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34409 ** Since the ASCII version of these Windows API do not exist for WINCE,
34410 ** it's important to not reference them for WINCE builds.
34411 */
34412 #if SQLITE_OS_WINCE==0
34413   }else{
34414     char *zTemp;
34415     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
34416     zTemp = malloc( nByte*sizeof(zTemp[0]) );
34417     if( zTemp==0 ){
34418       free(zConverted);
34419       return SQLITE_NOMEM;
34420     }
34421     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
34422     free(zConverted);
34423     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34424     free(zTemp);
34425 #endif
34426   }
34427   if( zOut ){
34428     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
34429     free(zOut);
34430     return SQLITE_OK;
34431   }else{
34432     return SQLITE_NOMEM;
34433   }
34434 #endif
34435 }
34436 
34437 /*
34438 ** Get the sector size of the device used to store
34439 ** file.
34440 */
34441 static int getSectorSize(
34442     sqlite3_vfs *pVfs,
34443     const char *zRelative     /* UTF-8 file name */
34444 ){
34445   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
34446   /* GetDiskFreeSpace is not supported under WINCE */
34447 #if SQLITE_OS_WINCE
34448   UNUSED_PARAMETER(pVfs);
34449   UNUSED_PARAMETER(zRelative);
34450 #else
34451   char zFullpath[MAX_PATH+1];
34452   int rc;
34453   DWORD dwRet = 0;
34454   DWORD dwDummy;
34455 
34456   /*
34457   ** We need to get the full path name of the file
34458   ** to get the drive letter to look up the sector
34459   ** size.
34460   */
34461   SimulateIOErrorBenign(1);
34462   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
34463   SimulateIOErrorBenign(0);
34464   if( rc == SQLITE_OK )
34465   {
34466     void *zConverted = convertUtf8Filename(zFullpath);
34467     if( zConverted ){
34468       if( isNT() ){
34469         /* trim path to just drive reference */
34470         WCHAR *p = zConverted;
34471         for(;*p;p++){
34472           if( *p == '\\' ){
34473             *p = '\0';
34474             break;
34475           }
34476         }
34477         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
34478                                   &dwDummy,
34479                                   &bytesPerSector,
34480                                   &dwDummy,
34481                                   &dwDummy);
34482       }else{
34483         /* trim path to just drive reference */
34484         char *p = (char *)zConverted;
34485         for(;*p;p++){
34486           if( *p == '\\' ){
34487             *p = '\0';
34488             break;
34489           }
34490         }
34491         dwRet = GetDiskFreeSpaceA((char*)zConverted,
34492                                   &dwDummy,
34493                                   &bytesPerSector,
34494                                   &dwDummy,
34495                                   &dwDummy);
34496       }
34497       free(zConverted);
34498     }
34499     if( !dwRet ){
34500       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
34501     }
34502   }
34503 #endif
34504   return (int) bytesPerSector;
34505 }
34506 
34507 #ifndef SQLITE_OMIT_LOAD_EXTENSION
34508 /*
34509 ** Interfaces for opening a shared library, finding entry points
34510 ** within the shared library, and closing the shared library.
34511 */
34512 /*
34513 ** Interfaces for opening a shared library, finding entry points
34514 ** within the shared library, and closing the shared library.
34515 */
34516 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
34517   HANDLE h;
34518   void *zConverted = convertUtf8Filename(zFilename);
34519   UNUSED_PARAMETER(pVfs);
34520   if( zConverted==0 ){
34521     return 0;
34522   }
34523   if( isNT() ){
34524     h = LoadLibraryW((WCHAR*)zConverted);
34525 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34526 ** Since the ASCII version of these Windows API do not exist for WINCE,
34527 ** it's important to not reference them for WINCE builds.
34528 */
34529 #if SQLITE_OS_WINCE==0
34530   }else{
34531     h = LoadLibraryA((char*)zConverted);
34532 #endif
34533   }
34534   free(zConverted);
34535   return (void*)h;
34536 }
34537 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
34538   UNUSED_PARAMETER(pVfs);
34539   getLastErrorMsg(nBuf, zBufOut);
34540 }
34541 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
34542   UNUSED_PARAMETER(pVfs);
34543 #if SQLITE_OS_WINCE
34544   /* The GetProcAddressA() routine is only available on wince. */
34545   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
34546 #else
34547   /* All other windows platforms expect GetProcAddress() to take
34548   ** an Ansi string regardless of the _UNICODE setting */
34549   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
34550 #endif
34551 }
34552 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
34553   UNUSED_PARAMETER(pVfs);
34554   FreeLibrary((HANDLE)pHandle);
34555 }
34556 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
34557   #define winDlOpen  0
34558   #define winDlError 0
34559   #define winDlSym   0
34560   #define winDlClose 0
34561 #endif
34562 
34563 
34564 /*
34565 ** Write up to nBuf bytes of randomness into zBuf.
34566 */
34567 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34568   int n = 0;
34569   UNUSED_PARAMETER(pVfs);
34570 #if defined(SQLITE_TEST)
34571   n = nBuf;
34572   memset(zBuf, 0, nBuf);
34573 #else
34574   if( sizeof(SYSTEMTIME)<=nBuf-n ){
34575     SYSTEMTIME x;
34576     GetSystemTime(&x);
34577     memcpy(&zBuf[n], &x, sizeof(x));
34578     n += sizeof(x);
34579   }
34580   if( sizeof(DWORD)<=nBuf-n ){
34581     DWORD pid = GetCurrentProcessId();
34582     memcpy(&zBuf[n], &pid, sizeof(pid));
34583     n += sizeof(pid);
34584   }
34585   if( sizeof(DWORD)<=nBuf-n ){
34586     DWORD cnt = GetTickCount();
34587     memcpy(&zBuf[n], &cnt, sizeof(cnt));
34588     n += sizeof(cnt);
34589   }
34590   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
34591     LARGE_INTEGER i;
34592     QueryPerformanceCounter(&i);
34593     memcpy(&zBuf[n], &i, sizeof(i));
34594     n += sizeof(i);
34595   }
34596 #endif
34597   return n;
34598 }
34599 
34600 
34601 /*
34602 ** Sleep for a little while.  Return the amount of time slept.
34603 */
34604 static int winSleep(sqlite3_vfs *pVfs, int microsec){
34605   Sleep((microsec+999)/1000);
34606   UNUSED_PARAMETER(pVfs);
34607   return ((microsec+999)/1000)*1000;
34608 }
34609 
34610 /*
34611 ** The following variable, if set to a non-zero value, is interpreted as
34612 ** the number of seconds since 1970 and is used to set the result of
34613 ** sqlite3OsCurrentTime() during testing.
34614 */
34615 #ifdef SQLITE_TEST
34616 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
34617 #endif
34618 
34619 /*
34620 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
34621 ** the current time and date as a Julian Day number times 86_400_000.  In
34622 ** other words, write into *piNow the number of milliseconds since the Julian
34623 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
34624 ** proleptic Gregorian calendar.
34625 **
34626 ** On success, return 0.  Return 1 if the time and date cannot be found.
34627 */
34628 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
34629   /* FILETIME structure is a 64-bit value representing the number of
34630      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
34631   */
34632   FILETIME ft;
34633   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
34634 #ifdef SQLITE_TEST
34635   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
34636 #endif
34637   /* 2^32 - to avoid use of LL and warnings in gcc */
34638   static const sqlite3_int64 max32BitValue =
34639       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
34640 
34641 #if SQLITE_OS_WINCE
34642   SYSTEMTIME time;
34643   GetSystemTime(&time);
34644   /* if SystemTimeToFileTime() fails, it returns zero. */
34645   if (!SystemTimeToFileTime(&time,&ft)){
34646     return 1;
34647   }
34648 #else
34649   GetSystemTimeAsFileTime( &ft );
34650 #endif
34651 
34652   *piNow = winFiletimeEpoch +
34653             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
34654                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
34655 
34656 #ifdef SQLITE_TEST
34657   if( sqlite3_current_time ){
34658     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
34659   }
34660 #endif
34661   UNUSED_PARAMETER(pVfs);
34662   return 0;
34663 }
34664 
34665 /*
34666 ** Find the current time (in Universal Coordinated Time).  Write the
34667 ** current time and date as a Julian Day number into *prNow and
34668 ** return 0.  Return 1 if the time and date cannot be found.
34669 */
34670 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
34671   int rc;
34672   sqlite3_int64 i;
34673   rc = winCurrentTimeInt64(pVfs, &i);
34674   if( !rc ){
34675     *prNow = i/86400000.0;
34676   }
34677   return rc;
34678 }
34679 
34680 /*
34681 ** The idea is that this function works like a combination of
34682 ** GetLastError() and FormatMessage() on windows (or errno and
34683 ** strerror_r() on unix). After an error is returned by an OS
34684 ** function, SQLite calls this function with zBuf pointing to
34685 ** a buffer of nBuf bytes. The OS layer should populate the
34686 ** buffer with a nul-terminated UTF-8 encoded error message
34687 ** describing the last IO error to have occurred within the calling
34688 ** thread.
34689 **
34690 ** If the error message is too large for the supplied buffer,
34691 ** it should be truncated. The return value of xGetLastError
34692 ** is zero if the error message fits in the buffer, or non-zero
34693 ** otherwise (if the message was truncated). If non-zero is returned,
34694 ** then it is not necessary to include the nul-terminator character
34695 ** in the output buffer.
34696 **
34697 ** Not supplying an error message will have no adverse effect
34698 ** on SQLite. It is fine to have an implementation that never
34699 ** returns an error message:
34700 **
34701 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34702 **     assert(zBuf[0]=='\0');
34703 **     return 0;
34704 **   }
34705 **
34706 ** However if an error message is supplied, it will be incorporated
34707 ** by sqlite into the error message available to the user using
34708 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
34709 */
34710 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
34711   UNUSED_PARAMETER(pVfs);
34712   return getLastErrorMsg(nBuf, zBuf);
34713 }
34714 
34715 
34716 
34717 /*
34718 ** Initialize and deinitialize the operating system interface.
34719 */
34720 SQLITE_API int sqlite3_os_init(void){
34721   static sqlite3_vfs winVfs = {
34722     3,                   /* iVersion */
34723     sizeof(winFile),     /* szOsFile */
34724     MAX_PATH,            /* mxPathname */
34725     0,                   /* pNext */
34726     "win32",             /* zName */
34727     0,                   /* pAppData */
34728     winOpen,             /* xOpen */
34729     winDelete,           /* xDelete */
34730     winAccess,           /* xAccess */
34731     winFullPathname,     /* xFullPathname */
34732     winDlOpen,           /* xDlOpen */
34733     winDlError,          /* xDlError */
34734     winDlSym,            /* xDlSym */
34735     winDlClose,          /* xDlClose */
34736     winRandomness,       /* xRandomness */
34737     winSleep,            /* xSleep */
34738     winCurrentTime,      /* xCurrentTime */
34739     winGetLastError,     /* xGetLastError */
34740     winCurrentTimeInt64, /* xCurrentTimeInt64 */
34741     0,                   /* xSetSystemCall */
34742     0,                   /* xGetSystemCall */
34743     0,                   /* xNextSystemCall */
34744   };
34745 
34746 #ifndef SQLITE_OMIT_WAL
34747   /* get memory map allocation granularity */
34748   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
34749   GetSystemInfo(&winSysInfo);
34750   assert(winSysInfo.dwAllocationGranularity > 0);
34751 #endif
34752 
34753   sqlite3_vfs_register(&winVfs, 1);
34754   return SQLITE_OK;
34755 }
34756 SQLITE_API int sqlite3_os_end(void){
34757   return SQLITE_OK;
34758 }
34759 
34760 #endif /* SQLITE_OS_WIN */
34761 
34762 /************** End of os_win.c **********************************************/
34763 /************** Begin file bitvec.c ******************************************/
34764 /*
34765 ** 2008 February 16
34766 **
34767 ** The author disclaims copyright to this source code.  In place of
34768 ** a legal notice, here is a blessing:
34769 **
34770 **    May you do good and not evil.
34771 **    May you find forgiveness for yourself and forgive others.
34772 **    May you share freely, never taking more than you give.
34773 **
34774 *************************************************************************
34775 ** This file implements an object that represents a fixed-length
34776 ** bitmap.  Bits are numbered starting with 1.
34777 **
34778 ** A bitmap is used to record which pages of a database file have been
34779 ** journalled during a transaction, or which pages have the "dont-write"
34780 ** property.  Usually only a few pages are meet either condition.
34781 ** So the bitmap is usually sparse and has low cardinality.
34782 ** But sometimes (for example when during a DROP of a large table) most
34783 ** or all of the pages in a database can get journalled.  In those cases,
34784 ** the bitmap becomes dense with high cardinality.  The algorithm needs
34785 ** to handle both cases well.
34786 **
34787 ** The size of the bitmap is fixed when the object is created.
34788 **
34789 ** All bits are clear when the bitmap is created.  Individual bits
34790 ** may be set or cleared one at a time.
34791 **
34792 ** Test operations are about 100 times more common that set operations.
34793 ** Clear operations are exceedingly rare.  There are usually between
34794 ** 5 and 500 set operations per Bitvec object, though the number of sets can
34795 ** sometimes grow into tens of thousands or larger.  The size of the
34796 ** Bitvec object is the number of pages in the database file at the
34797 ** start of a transaction, and is thus usually less than a few thousand,
34798 ** but can be as large as 2 billion for a really big database.
34799 */
34800 
34801 /* Size of the Bitvec structure in bytes. */
34802 #define BITVEC_SZ        512
34803 
34804 /* Round the union size down to the nearest pointer boundary, since that's how
34805 ** it will be aligned within the Bitvec struct. */
34806 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
34807 
34808 /* Type of the array "element" for the bitmap representation.
34809 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
34810 ** Setting this to the "natural word" size of your CPU may improve
34811 ** performance. */
34812 #define BITVEC_TELEM     u8
34813 /* Size, in bits, of the bitmap element. */
34814 #define BITVEC_SZELEM    8
34815 /* Number of elements in a bitmap array. */
34816 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
34817 /* Number of bits in the bitmap array. */
34818 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
34819 
34820 /* Number of u32 values in hash table. */
34821 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
34822 /* Maximum number of entries in hash table before
34823 ** sub-dividing and re-hashing. */
34824 #define BITVEC_MXHASH    (BITVEC_NINT/2)
34825 /* Hashing function for the aHash representation.
34826 ** Empirical testing showed that the *37 multiplier
34827 ** (an arbitrary prime)in the hash function provided
34828 ** no fewer collisions than the no-op *1. */
34829 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
34830 
34831 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
34832 
34833 
34834 /*
34835 ** A bitmap is an instance of the following structure.
34836 **
34837 ** This bitmap records the existance of zero or more bits
34838 ** with values between 1 and iSize, inclusive.
34839 **
34840 ** There are three possible representations of the bitmap.
34841 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
34842 ** bitmap.  The least significant bit is bit 1.
34843 **
34844 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
34845 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
34846 **
34847 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
34848 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
34849 ** handles up to iDivisor separate values of i.  apSub[0] holds
34850 ** values between 1 and iDivisor.  apSub[1] holds values between
34851 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
34852 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
34853 ** to hold deal with values between 1 and iDivisor.
34854 */
34855 struct Bitvec {
34856   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
34857   u32 nSet;       /* Number of bits that are set - only valid for aHash
34858                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
34859                   ** this would be 125. */
34860   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
34861                   /* Should >=0 for apSub element. */
34862                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
34863                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
34864   union {
34865     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
34866     u32 aHash[BITVEC_NINT];      /* Hash table representation */
34867     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
34868   } u;
34869 };
34870 
34871 /*
34872 ** Create a new bitmap object able to handle bits between 0 and iSize,
34873 ** inclusive.  Return a pointer to the new object.  Return NULL if
34874 ** malloc fails.
34875 */
34876 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
34877   Bitvec *p;
34878   assert( sizeof(*p)==BITVEC_SZ );
34879   p = sqlite3MallocZero( sizeof(*p) );
34880   if( p ){
34881     p->iSize = iSize;
34882   }
34883   return p;
34884 }
34885 
34886 /*
34887 ** Check to see if the i-th bit is set.  Return true or false.
34888 ** If p is NULL (if the bitmap has not been created) or if
34889 ** i is out of range, then return false.
34890 */
34891 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
34892   if( p==0 ) return 0;
34893   if( i>p->iSize || i==0 ) return 0;
34894   i--;
34895   while( p->iDivisor ){
34896     u32 bin = i/p->iDivisor;
34897     i = i%p->iDivisor;
34898     p = p->u.apSub[bin];
34899     if (!p) {
34900       return 0;
34901     }
34902   }
34903   if( p->iSize<=BITVEC_NBIT ){
34904     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
34905   } else{
34906     u32 h = BITVEC_HASH(i++);
34907     while( p->u.aHash[h] ){
34908       if( p->u.aHash[h]==i ) return 1;
34909       h = (h+1) % BITVEC_NINT;
34910     }
34911     return 0;
34912   }
34913 }
34914 
34915 /*
34916 ** Set the i-th bit.  Return 0 on success and an error code if
34917 ** anything goes wrong.
34918 **
34919 ** This routine might cause sub-bitmaps to be allocated.  Failing
34920 ** to get the memory needed to hold the sub-bitmap is the only
34921 ** that can go wrong with an insert, assuming p and i are valid.
34922 **
34923 ** The calling function must ensure that p is a valid Bitvec object
34924 ** and that the value for "i" is within range of the Bitvec object.
34925 ** Otherwise the behavior is undefined.
34926 */
34927 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
34928   u32 h;
34929   if( p==0 ) return SQLITE_OK;
34930   assert( i>0 );
34931   assert( i<=p->iSize );
34932   i--;
34933   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
34934     u32 bin = i/p->iDivisor;
34935     i = i%p->iDivisor;
34936     if( p->u.apSub[bin]==0 ){
34937       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
34938       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
34939     }
34940     p = p->u.apSub[bin];
34941   }
34942   if( p->iSize<=BITVEC_NBIT ){
34943     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
34944     return SQLITE_OK;
34945   }
34946   h = BITVEC_HASH(i++);
34947   /* if there wasn't a hash collision, and this doesn't */
34948   /* completely fill the hash, then just add it without */
34949   /* worring about sub-dividing and re-hashing. */
34950   if( !p->u.aHash[h] ){
34951     if (p->nSet<(BITVEC_NINT-1)) {
34952       goto bitvec_set_end;
34953     } else {
34954       goto bitvec_set_rehash;
34955     }
34956   }
34957   /* there was a collision, check to see if it's already */
34958   /* in hash, if not, try to find a spot for it */
34959   do {
34960     if( p->u.aHash[h]==i ) return SQLITE_OK;
34961     h++;
34962     if( h>=BITVEC_NINT ) h = 0;
34963   } while( p->u.aHash[h] );
34964   /* we didn't find it in the hash.  h points to the first */
34965   /* available free spot. check to see if this is going to */
34966   /* make our hash too "full".  */
34967 bitvec_set_rehash:
34968   if( p->nSet>=BITVEC_MXHASH ){
34969     unsigned int j;
34970     int rc;
34971     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
34972     if( aiValues==0 ){
34973       return SQLITE_NOMEM;
34974     }else{
34975       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
34976       memset(p->u.apSub, 0, sizeof(p->u.apSub));
34977       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
34978       rc = sqlite3BitvecSet(p, i);
34979       for(j=0; j<BITVEC_NINT; j++){
34980         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
34981       }
34982       sqlite3StackFree(0, aiValues);
34983       return rc;
34984     }
34985   }
34986 bitvec_set_end:
34987   p->nSet++;
34988   p->u.aHash[h] = i;
34989   return SQLITE_OK;
34990 }
34991 
34992 /*
34993 ** Clear the i-th bit.
34994 **
34995 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
34996 ** that BitvecClear can use to rebuilt its hash table.
34997 */
34998 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
34999   if( p==0 ) return;
35000   assert( i>0 );
35001   i--;
35002   while( p->iDivisor ){
35003     u32 bin = i/p->iDivisor;
35004     i = i%p->iDivisor;
35005     p = p->u.apSub[bin];
35006     if (!p) {
35007       return;
35008     }
35009   }
35010   if( p->iSize<=BITVEC_NBIT ){
35011     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
35012   }else{
35013     unsigned int j;
35014     u32 *aiValues = pBuf;
35015     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35016     memset(p->u.aHash, 0, sizeof(p->u.aHash));
35017     p->nSet = 0;
35018     for(j=0; j<BITVEC_NINT; j++){
35019       if( aiValues[j] && aiValues[j]!=(i+1) ){
35020         u32 h = BITVEC_HASH(aiValues[j]-1);
35021         p->nSet++;
35022         while( p->u.aHash[h] ){
35023           h++;
35024           if( h>=BITVEC_NINT ) h = 0;
35025         }
35026         p->u.aHash[h] = aiValues[j];
35027       }
35028     }
35029   }
35030 }
35031 
35032 /*
35033 ** Destroy a bitmap object.  Reclaim all memory used.
35034 */
35035 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
35036   if( p==0 ) return;
35037   if( p->iDivisor ){
35038     unsigned int i;
35039     for(i=0; i<BITVEC_NPTR; i++){
35040       sqlite3BitvecDestroy(p->u.apSub[i]);
35041     }
35042   }
35043   sqlite3_free(p);
35044 }
35045 
35046 /*
35047 ** Return the value of the iSize parameter specified when Bitvec *p
35048 ** was created.
35049 */
35050 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
35051   return p->iSize;
35052 }
35053 
35054 #ifndef SQLITE_OMIT_BUILTIN_TEST
35055 /*
35056 ** Let V[] be an array of unsigned characters sufficient to hold
35057 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
35058 ** Then the following macros can be used to set, clear, or test
35059 ** individual bits within V.
35060 */
35061 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
35062 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
35063 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
35064 
35065 /*
35066 ** This routine runs an extensive test of the Bitvec code.
35067 **
35068 ** The input is an array of integers that acts as a program
35069 ** to test the Bitvec.  The integers are opcodes followed
35070 ** by 0, 1, or 3 operands, depending on the opcode.  Another
35071 ** opcode follows immediately after the last operand.
35072 **
35073 ** There are 6 opcodes numbered from 0 through 5.  0 is the
35074 ** "halt" opcode and causes the test to end.
35075 **
35076 **    0          Halt and return the number of errors
35077 **    1 N S X    Set N bits beginning with S and incrementing by X
35078 **    2 N S X    Clear N bits beginning with S and incrementing by X
35079 **    3 N        Set N randomly chosen bits
35080 **    4 N        Clear N randomly chosen bits
35081 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
35082 **
35083 ** The opcodes 1 through 4 perform set and clear operations are performed
35084 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35085 ** Opcode 5 works on the linear array only, not on the Bitvec.
35086 ** Opcode 5 is used to deliberately induce a fault in order to
35087 ** confirm that error detection works.
35088 **
35089 ** At the conclusion of the test the linear array is compared
35090 ** against the Bitvec object.  If there are any differences,
35091 ** an error is returned.  If they are the same, zero is returned.
35092 **
35093 ** If a memory allocation error occurs, return -1.
35094 */
35095 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35096   Bitvec *pBitvec = 0;
35097   unsigned char *pV = 0;
35098   int rc = -1;
35099   int i, nx, pc, op;
35100   void *pTmpSpace;
35101 
35102   /* Allocate the Bitvec to be tested and a linear array of
35103   ** bits to act as the reference */
35104   pBitvec = sqlite3BitvecCreate( sz );
35105   pV = sqlite3_malloc( (sz+7)/8 + 1 );
35106   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35107   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
35108   memset(pV, 0, (sz+7)/8 + 1);
35109 
35110   /* NULL pBitvec tests */
35111   sqlite3BitvecSet(0, 1);
35112   sqlite3BitvecClear(0, 1, pTmpSpace);
35113 
35114   /* Run the program */
35115   pc = 0;
35116   while( (op = aOp[pc])!=0 ){
35117     switch( op ){
35118       case 1:
35119       case 2:
35120       case 5: {
35121         nx = 4;
35122         i = aOp[pc+2] - 1;
35123         aOp[pc+2] += aOp[pc+3];
35124         break;
35125       }
35126       case 3:
35127       case 4:
35128       default: {
35129         nx = 2;
35130         sqlite3_randomness(sizeof(i), &i);
35131         break;
35132       }
35133     }
35134     if( (--aOp[pc+1]) > 0 ) nx = 0;
35135     pc += nx;
35136     i = (i & 0x7fffffff)%sz;
35137     if( (op & 1)!=0 ){
35138       SETBIT(pV, (i+1));
35139       if( op!=5 ){
35140         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
35141       }
35142     }else{
35143       CLEARBIT(pV, (i+1));
35144       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
35145     }
35146   }
35147 
35148   /* Test to make sure the linear array exactly matches the
35149   ** Bitvec object.  Start with the assumption that they do
35150   ** match (rc==0).  Change rc to non-zero if a discrepancy
35151   ** is found.
35152   */
35153   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
35154           + sqlite3BitvecTest(pBitvec, 0)
35155           + (sqlite3BitvecSize(pBitvec) - sz);
35156   for(i=1; i<=sz; i++){
35157     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
35158       rc = i;
35159       break;
35160     }
35161   }
35162 
35163   /* Free allocated structure */
35164 bitvec_end:
35165   sqlite3_free(pTmpSpace);
35166   sqlite3_free(pV);
35167   sqlite3BitvecDestroy(pBitvec);
35168   return rc;
35169 }
35170 #endif /* SQLITE_OMIT_BUILTIN_TEST */
35171 
35172 /************** End of bitvec.c **********************************************/
35173 /************** Begin file pcache.c ******************************************/
35174 /*
35175 ** 2008 August 05
35176 **
35177 ** The author disclaims copyright to this source code.  In place of
35178 ** a legal notice, here is a blessing:
35179 **
35180 **    May you do good and not evil.
35181 **    May you find forgiveness for yourself and forgive others.
35182 **    May you share freely, never taking more than you give.
35183 **
35184 *************************************************************************
35185 ** This file implements that page cache.
35186 */
35187 
35188 /*
35189 ** A complete page cache is an instance of this structure.
35190 */
35191 struct PCache {
35192   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
35193   PgHdr *pSynced;                     /* Last synced page in dirty page list */
35194   int nRef;                           /* Number of referenced pages */
35195   int nMax;                           /* Configured cache size */
35196   int szPage;                         /* Size of every page in this cache */
35197   int szExtra;                        /* Size of extra space for each page */
35198   int bPurgeable;                     /* True if pages are on backing store */
35199   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
35200   void *pStress;                      /* Argument to xStress */
35201   sqlite3_pcache *pCache;             /* Pluggable cache module */
35202   PgHdr *pPage1;                      /* Reference to page 1 */
35203 };
35204 
35205 /*
35206 ** Some of the assert() macros in this code are too expensive to run
35207 ** even during normal debugging.  Use them only rarely on long-running
35208 ** tests.  Enable the expensive asserts using the
35209 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
35210 */
35211 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
35212 # define expensive_assert(X)  assert(X)
35213 #else
35214 # define expensive_assert(X)
35215 #endif
35216 
35217 /********************************** Linked List Management ********************/
35218 
35219 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
35220 /*
35221 ** Check that the pCache->pSynced variable is set correctly. If it
35222 ** is not, either fail an assert or return zero. Otherwise, return
35223 ** non-zero. This is only used in debugging builds, as follows:
35224 **
35225 **   expensive_assert( pcacheCheckSynced(pCache) );
35226 */
35227 static int pcacheCheckSynced(PCache *pCache){
35228   PgHdr *p;
35229   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
35230     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
35231   }
35232   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
35233 }
35234 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
35235 
35236 /*
35237 ** Remove page pPage from the list of dirty pages.
35238 */
35239 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
35240   PCache *p = pPage->pCache;
35241 
35242   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
35243   assert( pPage->pDirtyPrev || pPage==p->pDirty );
35244 
35245   /* Update the PCache1.pSynced variable if necessary. */
35246   if( p->pSynced==pPage ){
35247     PgHdr *pSynced = pPage->pDirtyPrev;
35248     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
35249       pSynced = pSynced->pDirtyPrev;
35250     }
35251     p->pSynced = pSynced;
35252   }
35253 
35254   if( pPage->pDirtyNext ){
35255     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
35256   }else{
35257     assert( pPage==p->pDirtyTail );
35258     p->pDirtyTail = pPage->pDirtyPrev;
35259   }
35260   if( pPage->pDirtyPrev ){
35261     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
35262   }else{
35263     assert( pPage==p->pDirty );
35264     p->pDirty = pPage->pDirtyNext;
35265   }
35266   pPage->pDirtyNext = 0;
35267   pPage->pDirtyPrev = 0;
35268 
35269   expensive_assert( pcacheCheckSynced(p) );
35270 }
35271 
35272 /*
35273 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
35274 ** pPage).
35275 */
35276 static void pcacheAddToDirtyList(PgHdr *pPage){
35277   PCache *p = pPage->pCache;
35278 
35279   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
35280 
35281   pPage->pDirtyNext = p->pDirty;
35282   if( pPage->pDirtyNext ){
35283     assert( pPage->pDirtyNext->pDirtyPrev==0 );
35284     pPage->pDirtyNext->pDirtyPrev = pPage;
35285   }
35286   p->pDirty = pPage;
35287   if( !p->pDirtyTail ){
35288     p->pDirtyTail = pPage;
35289   }
35290   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
35291     p->pSynced = pPage;
35292   }
35293   expensive_assert( pcacheCheckSynced(p) );
35294 }
35295 
35296 /*
35297 ** Wrapper around the pluggable caches xUnpin method. If the cache is
35298 ** being used for an in-memory database, this function is a no-op.
35299 */
35300 static void pcacheUnpin(PgHdr *p){
35301   PCache *pCache = p->pCache;
35302   if( pCache->bPurgeable ){
35303     if( p->pgno==1 ){
35304       pCache->pPage1 = 0;
35305     }
35306     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
35307   }
35308 }
35309 
35310 /*************************************************** General Interfaces ******
35311 **
35312 ** Initialize and shutdown the page cache subsystem. Neither of these
35313 ** functions are threadsafe.
35314 */
35315 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
35316   if( sqlite3GlobalConfig.pcache.xInit==0 ){
35317     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
35318     ** built-in default page cache is used instead of the application defined
35319     ** page cache. */
35320     sqlite3PCacheSetDefault();
35321   }
35322   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
35323 }
35324 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
35325   if( sqlite3GlobalConfig.pcache.xShutdown ){
35326     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
35327     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
35328   }
35329 }
35330 
35331 /*
35332 ** Return the size in bytes of a PCache object.
35333 */
35334 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
35335 
35336 /*
35337 ** Create a new PCache object. Storage space to hold the object
35338 ** has already been allocated and is passed in as the p pointer.
35339 ** The caller discovers how much space needs to be allocated by
35340 ** calling sqlite3PcacheSize().
35341 */
35342 SQLITE_PRIVATE void sqlite3PcacheOpen(
35343   int szPage,                  /* Size of every page */
35344   int szExtra,                 /* Extra space associated with each page */
35345   int bPurgeable,              /* True if pages are on backing store */
35346   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
35347   void *pStress,               /* Argument to xStress */
35348   PCache *p                    /* Preallocated space for the PCache */
35349 ){
35350   memset(p, 0, sizeof(PCache));
35351   p->szPage = szPage;
35352   p->szExtra = szExtra;
35353   p->bPurgeable = bPurgeable;
35354   p->xStress = xStress;
35355   p->pStress = pStress;
35356   p->nMax = 100;
35357 }
35358 
35359 /*
35360 ** Change the page size for PCache object. The caller must ensure that there
35361 ** are no outstanding page references when this function is called.
35362 */
35363 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
35364   assert( pCache->nRef==0 && pCache->pDirty==0 );
35365   if( pCache->pCache ){
35366     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
35367     pCache->pCache = 0;
35368     pCache->pPage1 = 0;
35369   }
35370   pCache->szPage = szPage;
35371 }
35372 
35373 /*
35374 ** Try to obtain a page from the cache.
35375 */
35376 SQLITE_PRIVATE int sqlite3PcacheFetch(
35377   PCache *pCache,       /* Obtain the page from this cache */
35378   Pgno pgno,            /* Page number to obtain */
35379   int createFlag,       /* If true, create page if it does not exist already */
35380   PgHdr **ppPage        /* Write the page here */
35381 ){
35382   PgHdr *pPage = 0;
35383   int eCreate;
35384 
35385   assert( pCache!=0 );
35386   assert( createFlag==1 || createFlag==0 );
35387   assert( pgno>0 );
35388 
35389   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
35390   ** allocate it now.
35391   */
35392   if( !pCache->pCache && createFlag ){
35393     sqlite3_pcache *p;
35394     int nByte;
35395     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
35396     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
35397     if( !p ){
35398       return SQLITE_NOMEM;
35399     }
35400     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
35401     pCache->pCache = p;
35402   }
35403 
35404   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
35405   if( pCache->pCache ){
35406     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
35407   }
35408 
35409   if( !pPage && eCreate==1 ){
35410     PgHdr *pPg;
35411 
35412     /* Find a dirty page to write-out and recycle. First try to find a
35413     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
35414     ** cleared), but if that is not possible settle for any other
35415     ** unreferenced dirty page.
35416     */
35417     expensive_assert( pcacheCheckSynced(pCache) );
35418     for(pPg=pCache->pSynced;
35419         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
35420         pPg=pPg->pDirtyPrev
35421     );
35422     pCache->pSynced = pPg;
35423     if( !pPg ){
35424       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
35425     }
35426     if( pPg ){
35427       int rc;
35428 #ifdef SQLITE_LOG_CACHE_SPILL
35429       sqlite3_log(SQLITE_FULL,
35430                   "spill page %d making room for %d - cache used: %d/%d",
35431                   pPg->pgno, pgno,
35432                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
35433                   pCache->nMax);
35434 #endif
35435       rc = pCache->xStress(pCache->pStress, pPg);
35436       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
35437         return rc;
35438       }
35439     }
35440 
35441     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
35442   }
35443 
35444   if( pPage ){
35445     if( !pPage->pData ){
35446       memset(pPage, 0, sizeof(PgHdr));
35447       pPage->pData = (void *)&pPage[1];
35448       pPage->pExtra = (void*)&((char *)pPage->pData)[pCache->szPage];
35449       memset(pPage->pExtra, 0, pCache->szExtra);
35450       pPage->pCache = pCache;
35451       pPage->pgno = pgno;
35452     }
35453     assert( pPage->pCache==pCache );
35454     assert( pPage->pgno==pgno );
35455     assert( pPage->pData==(void *)&pPage[1] );
35456     assert( pPage->pExtra==(void *)&((char *)&pPage[1])[pCache->szPage] );
35457 
35458     if( 0==pPage->nRef ){
35459       pCache->nRef++;
35460     }
35461     pPage->nRef++;
35462     if( pgno==1 ){
35463       pCache->pPage1 = pPage;
35464     }
35465   }
35466   *ppPage = pPage;
35467   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
35468 }
35469 
35470 /*
35471 ** Decrement the reference count on a page. If the page is clean and the
35472 ** reference count drops to 0, then it is made elible for recycling.
35473 */
35474 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
35475   assert( p->nRef>0 );
35476   p->nRef--;
35477   if( p->nRef==0 ){
35478     PCache *pCache = p->pCache;
35479     pCache->nRef--;
35480     if( (p->flags&PGHDR_DIRTY)==0 ){
35481       pcacheUnpin(p);
35482     }else{
35483       /* Move the page to the head of the dirty list. */
35484       pcacheRemoveFromDirtyList(p);
35485       pcacheAddToDirtyList(p);
35486     }
35487   }
35488 }
35489 
35490 /*
35491 ** Increase the reference count of a supplied page by 1.
35492 */
35493 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
35494   assert(p->nRef>0);
35495   p->nRef++;
35496 }
35497 
35498 /*
35499 ** Drop a page from the cache. There must be exactly one reference to the
35500 ** page. This function deletes that reference, so after it returns the
35501 ** page pointed to by p is invalid.
35502 */
35503 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
35504   PCache *pCache;
35505   assert( p->nRef==1 );
35506   if( p->flags&PGHDR_DIRTY ){
35507     pcacheRemoveFromDirtyList(p);
35508   }
35509   pCache = p->pCache;
35510   pCache->nRef--;
35511   if( p->pgno==1 ){
35512     pCache->pPage1 = 0;
35513   }
35514   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
35515 }
35516 
35517 /*
35518 ** Make sure the page is marked as dirty. If it isn't dirty already,
35519 ** make it so.
35520 */
35521 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
35522   p->flags &= ~PGHDR_DONT_WRITE;
35523   assert( p->nRef>0 );
35524   if( 0==(p->flags & PGHDR_DIRTY) ){
35525     p->flags |= PGHDR_DIRTY;
35526     pcacheAddToDirtyList( p);
35527   }
35528 }
35529 
35530 /*
35531 ** Make sure the page is marked as clean. If it isn't clean already,
35532 ** make it so.
35533 */
35534 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
35535   if( (p->flags & PGHDR_DIRTY) ){
35536     pcacheRemoveFromDirtyList(p);
35537     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
35538     if( p->nRef==0 ){
35539       pcacheUnpin(p);
35540     }
35541   }
35542 }
35543 
35544 /*
35545 ** Make every page in the cache clean.
35546 */
35547 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
35548   PgHdr *p;
35549   while( (p = pCache->pDirty)!=0 ){
35550     sqlite3PcacheMakeClean(p);
35551   }
35552 }
35553 
35554 /*
35555 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
35556 */
35557 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
35558   PgHdr *p;
35559   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35560     p->flags &= ~PGHDR_NEED_SYNC;
35561   }
35562   pCache->pSynced = pCache->pDirtyTail;
35563 }
35564 
35565 /*
35566 ** Change the page number of page p to newPgno.
35567 */
35568 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
35569   PCache *pCache = p->pCache;
35570   assert( p->nRef>0 );
35571   assert( newPgno>0 );
35572   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
35573   p->pgno = newPgno;
35574   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
35575     pcacheRemoveFromDirtyList(p);
35576     pcacheAddToDirtyList(p);
35577   }
35578 }
35579 
35580 /*
35581 ** Drop every cache entry whose page number is greater than "pgno". The
35582 ** caller must ensure that there are no outstanding references to any pages
35583 ** other than page 1 with a page number greater than pgno.
35584 **
35585 ** If there is a reference to page 1 and the pgno parameter passed to this
35586 ** function is 0, then the data area associated with page 1 is zeroed, but
35587 ** the page object is not dropped.
35588 */
35589 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
35590   if( pCache->pCache ){
35591     PgHdr *p;
35592     PgHdr *pNext;
35593     for(p=pCache->pDirty; p; p=pNext){
35594       pNext = p->pDirtyNext;
35595       /* This routine never gets call with a positive pgno except right
35596       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
35597       ** it must be that pgno==0.
35598       */
35599       assert( p->pgno>0 );
35600       if( ALWAYS(p->pgno>pgno) ){
35601         assert( p->flags&PGHDR_DIRTY );
35602         sqlite3PcacheMakeClean(p);
35603       }
35604     }
35605     if( pgno==0 && pCache->pPage1 ){
35606       memset(pCache->pPage1->pData, 0, pCache->szPage);
35607       pgno = 1;
35608     }
35609     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
35610   }
35611 }
35612 
35613 /*
35614 ** Close a cache.
35615 */
35616 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
35617   if( pCache->pCache ){
35618     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
35619   }
35620 }
35621 
35622 /*
35623 ** Discard the contents of the cache.
35624 */
35625 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
35626   sqlite3PcacheTruncate(pCache, 0);
35627 }
35628 
35629 /*
35630 ** Merge two lists of pages connected by pDirty and in pgno order.
35631 ** Do not both fixing the pDirtyPrev pointers.
35632 */
35633 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
35634   PgHdr result, *pTail;
35635   pTail = &result;
35636   while( pA && pB ){
35637     if( pA->pgno<pB->pgno ){
35638       pTail->pDirty = pA;
35639       pTail = pA;
35640       pA = pA->pDirty;
35641     }else{
35642       pTail->pDirty = pB;
35643       pTail = pB;
35644       pB = pB->pDirty;
35645     }
35646   }
35647   if( pA ){
35648     pTail->pDirty = pA;
35649   }else if( pB ){
35650     pTail->pDirty = pB;
35651   }else{
35652     pTail->pDirty = 0;
35653   }
35654   return result.pDirty;
35655 }
35656 
35657 /*
35658 ** Sort the list of pages in accending order by pgno.  Pages are
35659 ** connected by pDirty pointers.  The pDirtyPrev pointers are
35660 ** corrupted by this sort.
35661 **
35662 ** Since there cannot be more than 2^31 distinct pages in a database,
35663 ** there cannot be more than 31 buckets required by the merge sorter.
35664 ** One extra bucket is added to catch overflow in case something
35665 ** ever changes to make the previous sentence incorrect.
35666 */
35667 #define N_SORT_BUCKET  32
35668 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
35669   PgHdr *a[N_SORT_BUCKET], *p;
35670   int i;
35671   memset(a, 0, sizeof(a));
35672   while( pIn ){
35673     p = pIn;
35674     pIn = p->pDirty;
35675     p->pDirty = 0;
35676     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
35677       if( a[i]==0 ){
35678         a[i] = p;
35679         break;
35680       }else{
35681         p = pcacheMergeDirtyList(a[i], p);
35682         a[i] = 0;
35683       }
35684     }
35685     if( NEVER(i==N_SORT_BUCKET-1) ){
35686       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
35687       ** the input list.  But that is impossible.
35688       */
35689       a[i] = pcacheMergeDirtyList(a[i], p);
35690     }
35691   }
35692   p = a[0];
35693   for(i=1; i<N_SORT_BUCKET; i++){
35694     p = pcacheMergeDirtyList(p, a[i]);
35695   }
35696   return p;
35697 }
35698 
35699 /*
35700 ** Return a list of all dirty pages in the cache, sorted by page number.
35701 */
35702 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
35703   PgHdr *p;
35704   for(p=pCache->pDirty; p; p=p->pDirtyNext){
35705     p->pDirty = p->pDirtyNext;
35706   }
35707   return pcacheSortDirtyList(pCache->pDirty);
35708 }
35709 
35710 /*
35711 ** Return the total number of referenced pages held by the cache.
35712 */
35713 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
35714   return pCache->nRef;
35715 }
35716 
35717 /*
35718 ** Return the number of references to the page supplied as an argument.
35719 */
35720 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
35721   return p->nRef;
35722 }
35723 
35724 /*
35725 ** Return the total number of pages in the cache.
35726 */
35727 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
35728   int nPage = 0;
35729   if( pCache->pCache ){
35730     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
35731   }
35732   return nPage;
35733 }
35734 
35735 #ifdef SQLITE_TEST
35736 /*
35737 ** Get the suggested cache-size value.
35738 */
35739 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
35740   return pCache->nMax;
35741 }
35742 #endif
35743 
35744 /*
35745 ** Set the suggested cache-size value.
35746 */
35747 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
35748   pCache->nMax = mxPage;
35749   if( pCache->pCache ){
35750     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
35751   }
35752 }
35753 
35754 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
35755 /*
35756 ** For all dirty pages currently in the cache, invoke the specified
35757 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
35758 ** defined.
35759 */
35760 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
35761   PgHdr *pDirty;
35762   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
35763     xIter(pDirty);
35764   }
35765 }
35766 #endif
35767 
35768 /************** End of pcache.c **********************************************/
35769 /************** Begin file pcache1.c *****************************************/
35770 /*
35771 ** 2008 November 05
35772 **
35773 ** The author disclaims copyright to this source code.  In place of
35774 ** a legal notice, here is a blessing:
35775 **
35776 **    May you do good and not evil.
35777 **    May you find forgiveness for yourself and forgive others.
35778 **    May you share freely, never taking more than you give.
35779 **
35780 *************************************************************************
35781 **
35782 ** This file implements the default page cache implementation (the
35783 ** sqlite3_pcache interface). It also contains part of the implementation
35784 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
35785 ** If the default page cache implementation is overriden, then neither of
35786 ** these two features are available.
35787 */
35788 
35789 
35790 typedef struct PCache1 PCache1;
35791 typedef struct PgHdr1 PgHdr1;
35792 typedef struct PgFreeslot PgFreeslot;
35793 typedef struct PGroup PGroup;
35794 
35795 typedef struct PGroupBlock PGroupBlock;
35796 typedef struct PGroupBlockList PGroupBlockList;
35797 
35798 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
35799 ** of one or more PCaches that are able to recycle each others unpinned
35800 ** pages when they are under memory pressure.  A PGroup is an instance of
35801 ** the following object.
35802 **
35803 ** This page cache implementation works in one of two modes:
35804 **
35805 **   (1)  Every PCache is the sole member of its own PGroup.  There is
35806 **        one PGroup per PCache.
35807 **
35808 **   (2)  There is a single global PGroup that all PCaches are a member
35809 **        of.
35810 **
35811 ** Mode 1 uses more memory (since PCache instances are not able to rob
35812 ** unused pages from other PCaches) but it also operates without a mutex,
35813 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
35814 ** threadsafe, but is able recycle pages more efficient.
35815 **
35816 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
35817 ** PGroup which is the pcache1.grp global variable and its mutex is
35818 ** SQLITE_MUTEX_STATIC_LRU.
35819 */
35820 struct PGroup {
35821   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
35822   int nMaxPage;                  /* Sum of nMax for purgeable caches */
35823   int nMinPage;                  /* Sum of nMin for purgeable caches */
35824   int mxPinned;                  /* nMaxpage + 10 - nMinPage */
35825   int nCurrentPage;              /* Number of purgeable pages allocated */
35826   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
35827 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
35828   int isBusy;                    /* Do not run ReleaseMemory() if true */
35829   PGroupBlockList *pBlockList;   /* List of block-lists for this group */
35830 #endif
35831 };
35832 
35833 /*
35834 ** If SQLITE_PAGECACHE_BLOCKALLOC is defined when the library is built,
35835 ** each PGroup structure has a linked list of the the following starting
35836 ** at PGroup.pBlockList. There is one entry for each distinct page-size
35837 ** currently used by members of the PGroup (i.e. 1024 bytes, 4096 bytes
35838 ** etc.). Variable PGroupBlockList.nByte is set to the actual allocation
35839 ** size requested by each pcache, which is the database page-size plus
35840 ** the various header structures used by the pcache, pager and btree layers.
35841 ** Usually around (pgsz+200) bytes.
35842 **
35843 ** This size (pgsz+200) bytes is not allocated efficiently by some
35844 ** implementations of malloc. In particular, some implementations are only
35845 ** able to allocate blocks of memory chunks of 2^N bytes, where N is some
35846 ** integer value. Since the page-size is a power of 2, this means we
35847 ** end up wasting (pgsz-200) bytes in each allocation.
35848 **
35849 ** If SQLITE_PAGECACHE_BLOCKALLOC is defined, the (pgsz+200) byte blocks
35850 ** are not allocated directly. Instead, blocks of roughly M*(pgsz+200) bytes
35851 ** are requested from malloc allocator. After a block is returned,
35852 ** sqlite3MallocSize() is used to determine how many (pgsz+200) byte
35853 ** allocations can fit in the space returned by malloc(). This value may
35854 ** be more than M.
35855 **
35856 ** The blocks are stored in a doubly-linked list. Variable PGroupBlock.nEntry
35857 ** contains the number of allocations that will fit in the aData[] space.
35858 ** nEntry is limited to the number of bits in bitmask mUsed. If a slot
35859 ** within aData is in use, the corresponding bit in mUsed is set. Thus
35860 ** when (mUsed+1==(1 << nEntry)) the block is completely full.
35861 **
35862 ** Each time a slot within a block is freed, the block is moved to the start
35863 ** of the linked-list. And if a block becomes completely full, then it is
35864 ** moved to the end of the list. As a result, when searching for a free
35865 ** slot, only the first block in the list need be examined. If it is full,
35866 ** then it is guaranteed that all blocks are full.
35867 */
35868 struct PGroupBlockList {
35869   int nByte;                     /* Size of each allocation in bytes */
35870   PGroupBlock *pFirst;           /* First PGroupBlock in list */
35871   PGroupBlock *pLast;            /* Last PGroupBlock in list */
35872   PGroupBlockList *pNext;        /* Next block-list attached to group */
35873 };
35874 
35875 struct PGroupBlock {
35876   Bitmask mUsed;                 /* Mask of used slots */
35877   int nEntry;                    /* Maximum number of allocations in aData[] */
35878   u8 *aData;                     /* Pointer to data block */
35879   PGroupBlock *pNext;            /* Next PGroupBlock in list */
35880   PGroupBlock *pPrev;            /* Previous PGroupBlock in list */
35881   PGroupBlockList *pList;        /* Owner list */
35882 };
35883 
35884 /* Minimum value for PGroupBlock.nEntry */
35885 #define PAGECACHE_BLOCKALLOC_MINENTRY 15
35886 
35887 /* Each page cache is an instance of the following object.  Every
35888 ** open database file (including each in-memory database and each
35889 ** temporary or transient database) has a single page cache which
35890 ** is an instance of this object.
35891 **
35892 ** Pointers to structures of this type are cast and returned as
35893 ** opaque sqlite3_pcache* handles.
35894 */
35895 struct PCache1 {
35896   /* Cache configuration parameters. Page size (szPage) and the purgeable
35897   ** flag (bPurgeable) are set when the cache is created. nMax may be
35898   ** modified at any time by a call to the pcache1CacheSize() method.
35899   ** The PGroup mutex must be held when accessing nMax.
35900   */
35901   PGroup *pGroup;                     /* PGroup this cache belongs to */
35902   int szPage;                         /* Size of allocated pages in bytes */
35903   int bPurgeable;                     /* True if cache is purgeable */
35904   unsigned int nMin;                  /* Minimum number of pages reserved */
35905   unsigned int nMax;                  /* Configured "cache_size" value */
35906   unsigned int n90pct;                /* nMax*9/10 */
35907 
35908   /* Hash table of all pages. The following variables may only be accessed
35909   ** when the accessor is holding the PGroup mutex.
35910   */
35911   unsigned int nRecyclable;           /* Number of pages in the LRU list */
35912   unsigned int nPage;                 /* Total number of pages in apHash */
35913   unsigned int nHash;                 /* Number of slots in apHash[] */
35914   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
35915 
35916   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
35917 };
35918 
35919 /*
35920 ** Each cache entry is represented by an instance of the following
35921 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
35922 ** directly before this structure in memory (see the PGHDR1_TO_PAGE()
35923 ** macro below).
35924 */
35925 struct PgHdr1 {
35926   unsigned int iKey;             /* Key value (page number) */
35927   PgHdr1 *pNext;                 /* Next in hash table chain */
35928   PCache1 *pCache;               /* Cache that currently owns this page */
35929   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
35930   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
35931 };
35932 
35933 /*
35934 ** Free slots in the allocator used to divide up the buffer provided using
35935 ** the SQLITE_CONFIG_PAGECACHE mechanism.
35936 */
35937 struct PgFreeslot {
35938   PgFreeslot *pNext;  /* Next free slot */
35939 };
35940 
35941 /*
35942 ** Global data used by this cache.
35943 */
35944 static SQLITE_WSD struct PCacheGlobal {
35945   PGroup grp;                    /* The global PGroup for mode (2) */
35946 
35947   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
35948   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
35949   ** fixed at sqlite3_initialize() time and do not require mutex protection.
35950   ** The nFreeSlot and pFree values do require mutex protection.
35951   */
35952   int isInit;                    /* True if initialized */
35953   int szSlot;                    /* Size of each free slot */
35954   int nSlot;                     /* The number of pcache slots */
35955   int nReserve;                  /* Try to keep nFreeSlot above this */
35956   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
35957   /* Above requires no mutex.  Use mutex below for variable that follow. */
35958   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
35959   int nFreeSlot;                 /* Number of unused pcache slots */
35960   PgFreeslot *pFree;             /* Free page blocks */
35961   /* The following value requires a mutex to change.  We skip the mutex on
35962   ** reading because (1) most platforms read a 32-bit integer atomically and
35963   ** (2) even if an incorrect value is read, no great harm is done since this
35964   ** is really just an optimization. */
35965   int bUnderPressure;            /* True if low on PAGECACHE memory */
35966 } pcache1_g;
35967 
35968 /*
35969 ** All code in this file should access the global structure above via the
35970 ** alias "pcache1". This ensures that the WSD emulation is used when
35971 ** compiling for systems that do not support real WSD.
35972 */
35973 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
35974 
35975 /*
35976 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
35977 ** bytes of data are located directly before it in memory (i.e. the total
35978 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
35979 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
35980 ** an argument and returns a pointer to the associated block of szPage
35981 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
35982 ** a pointer to a block of szPage bytes of data and the return value is
35983 ** a pointer to the associated PgHdr1 structure.
35984 **
35985 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
35986 */
35987 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
35988 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
35989 
35990 /*
35991 ** Blocks used by the SQLITE_PAGECACHE_BLOCKALLOC blocks to store/retrieve
35992 ** a PGroupBlock pointer based on a pointer to a page buffer.
35993 */
35994 #define PAGE_SET_BLOCKPTR(pCache, pPg, pBlock) \
35995   ( *(PGroupBlock **)&(((u8*)pPg)[sizeof(PgHdr1) + pCache->szPage]) = pBlock )
35996 
35997 #define PAGE_GET_BLOCKPTR(pCache, pPg) \
35998   ( *(PGroupBlock **)&(((u8*)pPg)[sizeof(PgHdr1) + pCache->szPage]) )
35999 
36000 
36001 /*
36002 ** Macros to enter and leave the PCache LRU mutex.
36003 */
36004 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
36005 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
36006 
36007 /******************************************************************************/
36008 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
36009 
36010 /*
36011 ** This function is called during initialization if a static buffer is
36012 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
36013 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
36014 ** enough to contain 'n' buffers of 'sz' bytes each.
36015 **
36016 ** This routine is called from sqlite3_initialize() and so it is guaranteed
36017 ** to be serialized already.  There is no need for further mutexing.
36018 */
36019 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
36020   if( pcache1.isInit ){
36021     PgFreeslot *p;
36022     sz = ROUNDDOWN8(sz);
36023     pcache1.szSlot = sz;
36024     pcache1.nSlot = pcache1.nFreeSlot = n;
36025     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
36026     pcache1.pStart = pBuf;
36027     pcache1.pFree = 0;
36028     pcache1.bUnderPressure = 0;
36029     while( n-- ){
36030       p = (PgFreeslot*)pBuf;
36031       p->pNext = pcache1.pFree;
36032       pcache1.pFree = p;
36033       pBuf = (void*)&((char*)pBuf)[sz];
36034     }
36035     pcache1.pEnd = pBuf;
36036   }
36037 }
36038 
36039 /*
36040 ** Malloc function used within this file to allocate space from the buffer
36041 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
36042 ** such buffer exists or there is no space left in it, this function falls
36043 ** back to sqlite3Malloc().
36044 **
36045 ** Multiple threads can run this routine at the same time.  Global variables
36046 ** in pcache1 need to be protected via mutex.
36047 */
36048 static void *pcache1Alloc(int nByte){
36049   void *p = 0;
36050   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36051   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
36052   if( nByte<=pcache1.szSlot ){
36053     sqlite3_mutex_enter(pcache1.mutex);
36054     p = (PgHdr1 *)pcache1.pFree;
36055     if( p ){
36056       pcache1.pFree = pcache1.pFree->pNext;
36057       pcache1.nFreeSlot--;
36058       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36059       assert( pcache1.nFreeSlot>=0 );
36060       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
36061     }
36062     sqlite3_mutex_leave(pcache1.mutex);
36063   }
36064   if( p==0 ){
36065     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
36066     ** it from sqlite3Malloc instead.
36067     */
36068     p = sqlite3Malloc(nByte);
36069     if( p ){
36070       int sz = sqlite3MallocSize(p);
36071       sqlite3_mutex_enter(pcache1.mutex);
36072       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36073       sqlite3_mutex_leave(pcache1.mutex);
36074     }
36075     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36076   }
36077   return p;
36078 }
36079 
36080 /*
36081 ** Free an allocated buffer obtained from pcache1Alloc().
36082 */
36083 static void pcache1Free(void *p){
36084   if( p==0 ) return;
36085   if( p>=pcache1.pStart && p<pcache1.pEnd ){
36086     PgFreeslot *pSlot;
36087     sqlite3_mutex_enter(pcache1.mutex);
36088     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
36089     pSlot = (PgFreeslot*)p;
36090     pSlot->pNext = pcache1.pFree;
36091     pcache1.pFree = pSlot;
36092     pcache1.nFreeSlot++;
36093     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36094     assert( pcache1.nFreeSlot<=pcache1.nSlot );
36095     sqlite3_mutex_leave(pcache1.mutex);
36096   }else{
36097     int iSize;
36098     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36099     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36100     iSize = sqlite3MallocSize(p);
36101     sqlite3_mutex_enter(pcache1.mutex);
36102     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
36103     sqlite3_mutex_leave(pcache1.mutex);
36104     sqlite3_free(p);
36105   }
36106 }
36107 
36108 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36109 /*
36110 ** Return the size of a pcache allocation
36111 */
36112 static int pcache1MemSize(void *p){
36113   if( p>=pcache1.pStart && p<pcache1.pEnd ){
36114     return pcache1.szSlot;
36115   }else{
36116     int iSize;
36117     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36118     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36119     iSize = sqlite3MallocSize(p);
36120     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36121     return iSize;
36122   }
36123 }
36124 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36125 
36126 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
36127 /*
36128 ** The block pBlock belongs to list pList but is not currently linked in.
36129 ** Insert it into the start of the list.
36130 */
36131 static void addBlockToList(PGroupBlockList *pList, PGroupBlock *pBlock){
36132   pBlock->pPrev = 0;
36133   pBlock->pNext = pList->pFirst;
36134   pList->pFirst = pBlock;
36135   if( pBlock->pNext ){
36136     pBlock->pNext->pPrev = pBlock;
36137   }else{
36138     assert( pList->pLast==0 );
36139     pList->pLast = pBlock;
36140   }
36141 }
36142 
36143 /*
36144 ** If there are no blocks in the list headed by pList, remove pList
36145 ** from the pGroup->pBlockList list and free it with sqlite3_free().
36146 */
36147 static void freeListIfEmpty(PGroup *pGroup, PGroupBlockList *pList){
36148   assert( sqlite3_mutex_held(pGroup->mutex) );
36149   if( pList->pFirst==0 ){
36150     PGroupBlockList **pp;
36151     for(pp=&pGroup->pBlockList; *pp!=pList; pp=&(*pp)->pNext);
36152     *pp = (*pp)->pNext;
36153     sqlite3_free(pList);
36154   }
36155 }
36156 #endif /* SQLITE_PAGECACHE_BLOCKALLOC */
36157 
36158 /*
36159 ** Allocate a new page object initially associated with cache pCache.
36160 */
36161 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
36162   int nByte = sizeof(PgHdr1) + pCache->szPage;
36163   void *pPg = 0;
36164   PgHdr1 *p;
36165 
36166 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
36167   PGroup *pGroup = pCache->pGroup;
36168   PGroupBlockList *pList;
36169   PGroupBlock *pBlock;
36170   int i;
36171 
36172   nByte += sizeof(PGroupBlockList *);
36173   nByte = ROUND8(nByte);
36174 
36175   for(pList=pGroup->pBlockList; pList; pList=pList->pNext){
36176     if( pList->nByte==nByte ) break;
36177   }
36178   if( pList==0 ){
36179     PGroupBlockList *pNew;
36180     assert( pGroup->isBusy==0 );
36181     assert( sqlite3_mutex_held(pGroup->mutex) );
36182     pGroup->isBusy = 1;  /* Disable sqlite3PcacheReleaseMemory() */
36183     pNew = (PGroupBlockList *)sqlite3MallocZero(sizeof(PGroupBlockList));
36184     pGroup->isBusy = 0;  /* Reenable sqlite3PcacheReleaseMemory() */
36185     if( pNew==0 ){
36186       /* malloc() failure. Return early. */
36187       return 0;
36188     }
36189 #ifdef SQLITE_DEBUG
36190     for(pList=pGroup->pBlockList; pList; pList=pList->pNext){
36191       assert( pList->nByte!=nByte );
36192     }
36193 #endif
36194     pNew->nByte = nByte;
36195     pNew->pNext = pGroup->pBlockList;
36196     pGroup->pBlockList = pNew;
36197     pList = pNew;
36198   }
36199 
36200   pBlock = pList->pFirst;
36201   if( pBlock==0 || pBlock->mUsed==(((Bitmask)1<<pBlock->nEntry)-1) ){
36202     int sz;
36203 
36204     /* Allocate a new block. Try to allocate enough space for the PGroupBlock
36205     ** structure and MINENTRY allocations of nByte bytes each. If the
36206     ** allocator returns more memory than requested, then more than MINENTRY
36207     ** allocations may fit in it. */
36208     assert( sqlite3_mutex_held(pGroup->mutex) );
36209     pcache1LeaveMutex(pCache->pGroup);
36210     sz = sizeof(PGroupBlock) + PAGECACHE_BLOCKALLOC_MINENTRY * nByte;
36211     pBlock = (PGroupBlock *)sqlite3Malloc(sz);
36212     pcache1EnterMutex(pCache->pGroup);
36213 
36214     if( !pBlock ){
36215       freeListIfEmpty(pGroup, pList);
36216       return 0;
36217     }
36218     pBlock->nEntry = (sqlite3MallocSize(pBlock) - sizeof(PGroupBlock)) / nByte;
36219     if( pBlock->nEntry>=BMS ){
36220       pBlock->nEntry = BMS-1;
36221     }
36222     pBlock->pList = pList;
36223     pBlock->mUsed = 0;
36224     pBlock->aData = (u8 *)&pBlock[1];
36225     addBlockToList(pList, pBlock);
36226 
36227     sz = sqlite3MallocSize(pBlock);
36228     sqlite3_mutex_enter(pcache1.mutex);
36229     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36230     sqlite3_mutex_leave(pcache1.mutex);
36231   }
36232 
36233   for(i=0; pPg==0 && ALWAYS(i<pBlock->nEntry); i++){
36234     if( 0==(pBlock->mUsed & ((Bitmask)1<<i)) ){
36235       pBlock->mUsed |= ((Bitmask)1<<i);
36236       pPg = (void *)&pBlock->aData[pList->nByte * i];
36237     }
36238   }
36239   assert( pPg );
36240   PAGE_SET_BLOCKPTR(pCache, pPg, pBlock);
36241 
36242   /* If the block is now full, shift it to the end of the list */
36243   if( pBlock->mUsed==(((Bitmask)1<<pBlock->nEntry)-1) && pList->pLast!=pBlock ){
36244     assert( pList->pFirst==pBlock );
36245     assert( pBlock->pPrev==0 );
36246     assert( pList->pLast->pNext==0 );
36247     pList->pFirst = pBlock->pNext;
36248     pList->pFirst->pPrev = 0;
36249     pBlock->pPrev = pList->pLast;
36250     pBlock->pNext = 0;
36251     pList->pLast->pNext = pBlock;
36252     pList->pLast = pBlock;
36253   }
36254   p = PAGE_TO_PGHDR1(pCache, pPg);
36255   if( pCache->bPurgeable ){
36256     pCache->pGroup->nCurrentPage++;
36257   }
36258 #else
36259   /* The group mutex must be released before pcache1Alloc() is called. This
36260   ** is because it may call sqlite3_release_memory(), which assumes that
36261   ** this mutex is not held. */
36262   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36263   pcache1LeaveMutex(pCache->pGroup);
36264   pPg = pcache1Alloc(nByte);
36265   pcache1EnterMutex(pCache->pGroup);
36266   if( pPg ){
36267     p = PAGE_TO_PGHDR1(pCache, pPg);
36268     if( pCache->bPurgeable ){
36269       pCache->pGroup->nCurrentPage++;
36270     }
36271   }else{
36272     p = 0;
36273   }
36274 #endif
36275   return p;
36276 }
36277 
36278 /*
36279 ** Free a page object allocated by pcache1AllocPage().
36280 **
36281 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
36282 ** that the current implementation happens to never call this routine
36283 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36284 */
36285 static void pcache1FreePage(PgHdr1 *p){
36286   if( ALWAYS(p) ){
36287     PCache1 *pCache = p->pCache;
36288     void *pPg = PGHDR1_TO_PAGE(p);
36289 
36290 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
36291     PGroupBlock *pBlock = PAGE_GET_BLOCKPTR(pCache, pPg);
36292     PGroupBlockList *pList = pBlock->pList;
36293     int i = ((u8 *)pPg - pBlock->aData) / pList->nByte;
36294 
36295     assert( pPg==(void *)&pBlock->aData[i*pList->nByte] );
36296     assert( pBlock->mUsed & ((Bitmask)1<<i) );
36297     pBlock->mUsed &= ~((Bitmask)1<<i);
36298 
36299     /* Remove the block from the list. If it is completely empty, free it.
36300     ** Or if it is not completely empty, re-insert it at the start of the
36301     ** list. */
36302     if( pList->pFirst==pBlock ){
36303       pList->pFirst = pBlock->pNext;
36304       if( pList->pFirst ) pList->pFirst->pPrev = 0;
36305     }else{
36306       pBlock->pPrev->pNext = pBlock->pNext;
36307     }
36308     if( pList->pLast==pBlock ){
36309       pList->pLast = pBlock->pPrev;
36310       if( pList->pLast ) pList->pLast->pNext = 0;
36311     }else{
36312       pBlock->pNext->pPrev = pBlock->pPrev;
36313     }
36314 
36315     if( pBlock->mUsed==0 ){
36316       PGroup *pGroup = p->pCache->pGroup;
36317 
36318       int sz = sqlite3MallocSize(pBlock);
36319       sqlite3_mutex_enter(pcache1.mutex);
36320       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -sz);
36321       sqlite3_mutex_leave(pcache1.mutex);
36322       freeListIfEmpty(pGroup, pList);
36323       sqlite3_free(pBlock);
36324     }else{
36325       addBlockToList(pList, pBlock);
36326     }
36327 #else
36328     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36329     pcache1Free(pPg);
36330 #endif
36331     if( pCache->bPurgeable ){
36332       pCache->pGroup->nCurrentPage--;
36333     }
36334   }
36335 }
36336 
36337 /*
36338 ** Malloc function used by SQLite to obtain space from the buffer configured
36339 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
36340 ** exists, this function falls back to sqlite3Malloc().
36341 */
36342 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
36343   return pcache1Alloc(sz);
36344 }
36345 
36346 /*
36347 ** Free an allocated buffer obtained from sqlite3PageMalloc().
36348 */
36349 SQLITE_PRIVATE void sqlite3PageFree(void *p){
36350   pcache1Free(p);
36351 }
36352 
36353 
36354 /*
36355 ** Return true if it desirable to avoid allocating a new page cache
36356 ** entry.
36357 **
36358 ** If memory was allocated specifically to the page cache using
36359 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
36360 ** it is desirable to avoid allocating a new page cache entry because
36361 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
36362 ** for all page cache needs and we should not need to spill the
36363 ** allocation onto the heap.
36364 **
36365 ** Or, the heap is used for all page cache memory put the heap is
36366 ** under memory pressure, then again it is desirable to avoid
36367 ** allocating a new page cache entry in order to avoid stressing
36368 ** the heap even further.
36369 */
36370 static int pcache1UnderMemoryPressure(PCache1 *pCache){
36371   if( pcache1.nSlot && pCache->szPage<=pcache1.szSlot ){
36372     return pcache1.bUnderPressure;
36373   }else{
36374     return sqlite3HeapNearlyFull();
36375   }
36376 }
36377 
36378 /******************************************************************************/
36379 /******** General Implementation Functions ************************************/
36380 
36381 /*
36382 ** This function is used to resize the hash table used by the cache passed
36383 ** as the first argument.
36384 **
36385 ** The PCache mutex must be held when this function is called.
36386 */
36387 static int pcache1ResizeHash(PCache1 *p){
36388   PgHdr1 **apNew;
36389   unsigned int nNew;
36390   unsigned int i;
36391 
36392   assert( sqlite3_mutex_held(p->pGroup->mutex) );
36393 
36394   nNew = p->nHash*2;
36395   if( nNew<256 ){
36396     nNew = 256;
36397   }
36398 
36399   pcache1LeaveMutex(p->pGroup);
36400   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
36401   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
36402   if( p->nHash ){ sqlite3EndBenignMalloc(); }
36403   pcache1EnterMutex(p->pGroup);
36404   if( apNew ){
36405     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
36406     for(i=0; i<p->nHash; i++){
36407       PgHdr1 *pPage;
36408       PgHdr1 *pNext = p->apHash[i];
36409       while( (pPage = pNext)!=0 ){
36410         unsigned int h = pPage->iKey % nNew;
36411         pNext = pPage->pNext;
36412         pPage->pNext = apNew[h];
36413         apNew[h] = pPage;
36414       }
36415     }
36416     sqlite3_free(p->apHash);
36417     p->apHash = apNew;
36418     p->nHash = nNew;
36419   }
36420 
36421   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
36422 }
36423 
36424 /*
36425 ** This function is used internally to remove the page pPage from the
36426 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
36427 ** LRU list, then this function is a no-op.
36428 **
36429 ** The PGroup mutex must be held when this function is called.
36430 **
36431 ** If pPage is NULL then this routine is a no-op.
36432 */
36433 static void pcache1PinPage(PgHdr1 *pPage){
36434   PCache1 *pCache;
36435   PGroup *pGroup;
36436 
36437   if( pPage==0 ) return;
36438   pCache = pPage->pCache;
36439   pGroup = pCache->pGroup;
36440   assert( sqlite3_mutex_held(pGroup->mutex) );
36441   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
36442     if( pPage->pLruPrev ){
36443       pPage->pLruPrev->pLruNext = pPage->pLruNext;
36444     }
36445     if( pPage->pLruNext ){
36446       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
36447     }
36448     if( pGroup->pLruHead==pPage ){
36449       pGroup->pLruHead = pPage->pLruNext;
36450     }
36451     if( pGroup->pLruTail==pPage ){
36452       pGroup->pLruTail = pPage->pLruPrev;
36453     }
36454     pPage->pLruNext = 0;
36455     pPage->pLruPrev = 0;
36456     pPage->pCache->nRecyclable--;
36457   }
36458 }
36459 
36460 
36461 /*
36462 ** Remove the page supplied as an argument from the hash table
36463 ** (PCache1.apHash structure) that it is currently stored in.
36464 **
36465 ** The PGroup mutex must be held when this function is called.
36466 */
36467 static void pcache1RemoveFromHash(PgHdr1 *pPage){
36468   unsigned int h;
36469   PCache1 *pCache = pPage->pCache;
36470   PgHdr1 **pp;
36471 
36472   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36473   h = pPage->iKey % pCache->nHash;
36474   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
36475   *pp = (*pp)->pNext;
36476 
36477   pCache->nPage--;
36478 }
36479 
36480 /*
36481 ** If there are currently more than nMaxPage pages allocated, try
36482 ** to recycle pages to reduce the number allocated to nMaxPage.
36483 */
36484 static void pcache1EnforceMaxPage(PGroup *pGroup){
36485   assert( sqlite3_mutex_held(pGroup->mutex) );
36486   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
36487     PgHdr1 *p = pGroup->pLruTail;
36488     assert( p->pCache->pGroup==pGroup );
36489     pcache1PinPage(p);
36490     pcache1RemoveFromHash(p);
36491     pcache1FreePage(p);
36492   }
36493 }
36494 
36495 /*
36496 ** Discard all pages from cache pCache with a page number (key value)
36497 ** greater than or equal to iLimit. Any pinned pages that meet this
36498 ** criteria are unpinned before they are discarded.
36499 **
36500 ** The PCache mutex must be held when this function is called.
36501 */
36502 static void pcache1TruncateUnsafe(
36503   PCache1 *pCache,             /* The cache to truncate */
36504   unsigned int iLimit          /* Drop pages with this pgno or larger */
36505 ){
36506   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
36507   unsigned int h;
36508   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36509   for(h=0; h<pCache->nHash; h++){
36510     PgHdr1 **pp = &pCache->apHash[h];
36511     PgHdr1 *pPage;
36512     while( (pPage = *pp)!=0 ){
36513       if( pPage->iKey>=iLimit ){
36514         pCache->nPage--;
36515         *pp = pPage->pNext;
36516         pcache1PinPage(pPage);
36517         pcache1FreePage(pPage);
36518       }else{
36519         pp = &pPage->pNext;
36520         TESTONLY( nPage++; )
36521       }
36522     }
36523   }
36524   assert( pCache->nPage==nPage );
36525 }
36526 
36527 /******************************************************************************/
36528 /******** sqlite3_pcache Methods **********************************************/
36529 
36530 /*
36531 ** Implementation of the sqlite3_pcache.xInit method.
36532 */
36533 static int pcache1Init(void *NotUsed){
36534   UNUSED_PARAMETER(NotUsed);
36535   assert( pcache1.isInit==0 );
36536   memset(&pcache1, 0, sizeof(pcache1));
36537   if( sqlite3GlobalConfig.bCoreMutex ){
36538     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
36539     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
36540   }
36541   pcache1.grp.mxPinned = 10;
36542   pcache1.isInit = 1;
36543   return SQLITE_OK;
36544 }
36545 
36546 /*
36547 ** Implementation of the sqlite3_pcache.xShutdown method.
36548 ** Note that the static mutex allocated in xInit does
36549 ** not need to be freed.
36550 */
36551 static void pcache1Shutdown(void *NotUsed){
36552   UNUSED_PARAMETER(NotUsed);
36553   assert( pcache1.isInit!=0 );
36554   memset(&pcache1, 0, sizeof(pcache1));
36555 }
36556 
36557 /*
36558 ** Implementation of the sqlite3_pcache.xCreate method.
36559 **
36560 ** Allocate a new cache.
36561 */
36562 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
36563   PCache1 *pCache;      /* The newly created page cache */
36564   PGroup *pGroup;       /* The group the new page cache will belong to */
36565   int sz;               /* Bytes of memory required to allocate the new cache */
36566 
36567   /*
36568   ** The seperateCache variable is true if each PCache has its own private
36569   ** PGroup.  In other words, separateCache is true for mode (1) where no
36570   ** mutexing is required.
36571   **
36572   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
36573   **
36574   **   *  Always use a unified cache in single-threaded applications
36575   **
36576   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
36577   **      use separate caches (mode-1)
36578   */
36579 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
36580   const int separateCache = 0;
36581 #else
36582   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
36583 #endif
36584 
36585   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
36586   pCache = (PCache1 *)sqlite3_malloc(sz);
36587   if( pCache ){
36588     memset(pCache, 0, sz);
36589     if( separateCache ){
36590       pGroup = (PGroup*)&pCache[1];
36591       pGroup->mxPinned = 10;
36592     }else{
36593       pGroup = &pcache1.grp;
36594     }
36595     pCache->pGroup = pGroup;
36596     pCache->szPage = szPage;
36597     pCache->bPurgeable = (bPurgeable ? 1 : 0);
36598     if( bPurgeable ){
36599       pCache->nMin = 10;
36600       pcache1EnterMutex(pGroup);
36601       pGroup->nMinPage += pCache->nMin;
36602       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36603       pcache1LeaveMutex(pGroup);
36604     }
36605   }
36606   return (sqlite3_pcache *)pCache;
36607 }
36608 
36609 /*
36610 ** Implementation of the sqlite3_pcache.xCachesize method.
36611 **
36612 ** Configure the cache_size limit for a cache.
36613 */
36614 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
36615   PCache1 *pCache = (PCache1 *)p;
36616   if( pCache->bPurgeable ){
36617     PGroup *pGroup = pCache->pGroup;
36618     pcache1EnterMutex(pGroup);
36619     pGroup->nMaxPage += (nMax - pCache->nMax);
36620     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36621     pCache->nMax = nMax;
36622     pCache->n90pct = pCache->nMax*9/10;
36623     pcache1EnforceMaxPage(pGroup);
36624     pcache1LeaveMutex(pGroup);
36625   }
36626 }
36627 
36628 /*
36629 ** Implementation of the sqlite3_pcache.xPagecount method.
36630 */
36631 static int pcache1Pagecount(sqlite3_pcache *p){
36632   int n;
36633   PCache1 *pCache = (PCache1*)p;
36634   pcache1EnterMutex(pCache->pGroup);
36635   n = pCache->nPage;
36636   pcache1LeaveMutex(pCache->pGroup);
36637   return n;
36638 }
36639 
36640 /*
36641 ** Implementation of the sqlite3_pcache.xFetch method.
36642 **
36643 ** Fetch a page by key value.
36644 **
36645 ** Whether or not a new page may be allocated by this function depends on
36646 ** the value of the createFlag argument.  0 means do not allocate a new
36647 ** page.  1 means allocate a new page if space is easily available.  2
36648 ** means to try really hard to allocate a new page.
36649 **
36650 ** For a non-purgeable cache (a cache used as the storage for an in-memory
36651 ** database) there is really no difference between createFlag 1 and 2.  So
36652 ** the calling function (pcache.c) will never have a createFlag of 1 on
36653 ** a non-purgable cache.
36654 **
36655 ** There are three different approaches to obtaining space for a page,
36656 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
36657 **
36658 **   1. Regardless of the value of createFlag, the cache is searched for a
36659 **      copy of the requested page. If one is found, it is returned.
36660 **
36661 **   2. If createFlag==0 and the page is not already in the cache, NULL is
36662 **      returned.
36663 **
36664 **   3. If createFlag is 1, and the page is not already in the cache, then
36665 **      return NULL (do not allocate a new page) if any of the following
36666 **      conditions are true:
36667 **
36668 **       (a) the number of pages pinned by the cache is greater than
36669 **           PCache1.nMax, or
36670 **
36671 **       (b) the number of pages pinned by the cache is greater than
36672 **           the sum of nMax for all purgeable caches, less the sum of
36673 **           nMin for all other purgeable caches, or
36674 **
36675 **   4. If none of the first three conditions apply and the cache is marked
36676 **      as purgeable, and if one of the following is true:
36677 **
36678 **       (a) The number of pages allocated for the cache is already
36679 **           PCache1.nMax, or
36680 **
36681 **       (b) The number of pages allocated for all purgeable caches is
36682 **           already equal to or greater than the sum of nMax for all
36683 **           purgeable caches,
36684 **
36685 **       (c) The system is under memory pressure and wants to avoid
36686 **           unnecessary pages cache entry allocations
36687 **
36688 **      then attempt to recycle a page from the LRU list. If it is the right
36689 **      size, return the recycled buffer. Otherwise, free the buffer and
36690 **      proceed to step 5.
36691 **
36692 **   5. Otherwise, allocate and return a new page buffer.
36693 */
36694 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
36695   int nPinned;
36696   PCache1 *pCache = (PCache1 *)p;
36697   PGroup *pGroup;
36698   PgHdr1 *pPage = 0;
36699 
36700   assert( pCache->bPurgeable || createFlag!=1 );
36701   assert( pCache->bPurgeable || pCache->nMin==0 );
36702   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
36703   assert( pCache->nMin==0 || pCache->bPurgeable );
36704   pcache1EnterMutex(pGroup = pCache->pGroup);
36705 
36706   /* Step 1: Search the hash table for an existing entry. */
36707   if( pCache->nHash>0 ){
36708     unsigned int h = iKey % pCache->nHash;
36709     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
36710   }
36711 
36712   /* Step 2: Abort if no existing page is found and createFlag is 0 */
36713   if( pPage || createFlag==0 ){
36714     pcache1PinPage(pPage);
36715     goto fetch_out;
36716   }
36717 
36718   /* The pGroup local variable will normally be initialized by the
36719   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
36720   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
36721   ** local variable here.  Delaying the initialization of pGroup is an
36722   ** optimization:  The common case is to exit the module before reaching
36723   ** this point.
36724   */
36725 #ifdef SQLITE_MUTEX_OMIT
36726   pGroup = pCache->pGroup;
36727 #endif
36728 
36729 
36730   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
36731   nPinned = pCache->nPage - pCache->nRecyclable;
36732   assert( nPinned>=0 );
36733   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
36734   assert( pCache->n90pct == pCache->nMax*9/10 );
36735   if( createFlag==1 && (
36736         nPinned>=pGroup->mxPinned
36737      || nPinned>=(int)pCache->n90pct
36738      || pcache1UnderMemoryPressure(pCache)
36739   )){
36740     goto fetch_out;
36741   }
36742 
36743   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
36744     goto fetch_out;
36745   }
36746 
36747   /* Step 4. Try to recycle a page. */
36748   if( pCache->bPurgeable && pGroup->pLruTail && (
36749          (pCache->nPage+1>=pCache->nMax)
36750       || pGroup->nCurrentPage>=pGroup->nMaxPage
36751       || pcache1UnderMemoryPressure(pCache)
36752   )){
36753     PCache1 *pOtherCache;
36754     pPage = pGroup->pLruTail;
36755     pcache1RemoveFromHash(pPage);
36756     pcache1PinPage(pPage);
36757     if( (pOtherCache = pPage->pCache)->szPage!=pCache->szPage ){
36758       pcache1FreePage(pPage);
36759       pPage = 0;
36760     }else{
36761       pGroup->nCurrentPage -=
36762                (pOtherCache->bPurgeable - pCache->bPurgeable);
36763     }
36764   }
36765 
36766   /* Step 5. If a usable page buffer has still not been found,
36767   ** attempt to allocate a new one.
36768   */
36769   if( !pPage ){
36770     if( createFlag==1 ) sqlite3BeginBenignMalloc();
36771     pPage = pcache1AllocPage(pCache);
36772     if( createFlag==1 ) sqlite3EndBenignMalloc();
36773   }
36774 
36775   if( pPage ){
36776     unsigned int h = iKey % pCache->nHash;
36777     pCache->nPage++;
36778     pPage->iKey = iKey;
36779     pPage->pNext = pCache->apHash[h];
36780     pPage->pCache = pCache;
36781     pPage->pLruPrev = 0;
36782     pPage->pLruNext = 0;
36783     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
36784     pCache->apHash[h] = pPage;
36785   }
36786 
36787 fetch_out:
36788   if( pPage && iKey>pCache->iMaxKey ){
36789     pCache->iMaxKey = iKey;
36790   }
36791   pcache1LeaveMutex(pGroup);
36792   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
36793 }
36794 
36795 
36796 /*
36797 ** Implementation of the sqlite3_pcache.xUnpin method.
36798 **
36799 ** Mark a page as unpinned (eligible for asynchronous recycling).
36800 */
36801 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
36802   PCache1 *pCache = (PCache1 *)p;
36803   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36804   PGroup *pGroup = pCache->pGroup;
36805 
36806   assert( pPage->pCache==pCache );
36807   pcache1EnterMutex(pGroup);
36808 
36809   /* It is an error to call this function if the page is already
36810   ** part of the PGroup LRU list.
36811   */
36812   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
36813   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
36814 
36815   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
36816     pcache1RemoveFromHash(pPage);
36817     pcache1FreePage(pPage);
36818   }else{
36819     /* Add the page to the PGroup LRU list. */
36820     if( pGroup->pLruHead ){
36821       pGroup->pLruHead->pLruPrev = pPage;
36822       pPage->pLruNext = pGroup->pLruHead;
36823       pGroup->pLruHead = pPage;
36824     }else{
36825       pGroup->pLruTail = pPage;
36826       pGroup->pLruHead = pPage;
36827     }
36828     pCache->nRecyclable++;
36829   }
36830 
36831   pcache1LeaveMutex(pCache->pGroup);
36832 }
36833 
36834 /*
36835 ** Implementation of the sqlite3_pcache.xRekey method.
36836 */
36837 static void pcache1Rekey(
36838   sqlite3_pcache *p,
36839   void *pPg,
36840   unsigned int iOld,
36841   unsigned int iNew
36842 ){
36843   PCache1 *pCache = (PCache1 *)p;
36844   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
36845   PgHdr1 **pp;
36846   unsigned int h;
36847   assert( pPage->iKey==iOld );
36848   assert( pPage->pCache==pCache );
36849 
36850   pcache1EnterMutex(pCache->pGroup);
36851 
36852   h = iOld%pCache->nHash;
36853   pp = &pCache->apHash[h];
36854   while( (*pp)!=pPage ){
36855     pp = &(*pp)->pNext;
36856   }
36857   *pp = pPage->pNext;
36858 
36859   h = iNew%pCache->nHash;
36860   pPage->iKey = iNew;
36861   pPage->pNext = pCache->apHash[h];
36862   pCache->apHash[h] = pPage;
36863   if( iNew>pCache->iMaxKey ){
36864     pCache->iMaxKey = iNew;
36865   }
36866 
36867   pcache1LeaveMutex(pCache->pGroup);
36868 }
36869 
36870 /*
36871 ** Implementation of the sqlite3_pcache.xTruncate method.
36872 **
36873 ** Discard all unpinned pages in the cache with a page number equal to
36874 ** or greater than parameter iLimit. Any pinned pages with a page number
36875 ** equal to or greater than iLimit are implicitly unpinned.
36876 */
36877 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
36878   PCache1 *pCache = (PCache1 *)p;
36879   pcache1EnterMutex(pCache->pGroup);
36880   if( iLimit<=pCache->iMaxKey ){
36881     pcache1TruncateUnsafe(pCache, iLimit);
36882     pCache->iMaxKey = iLimit-1;
36883   }
36884   pcache1LeaveMutex(pCache->pGroup);
36885 }
36886 
36887 /*
36888 ** Implementation of the sqlite3_pcache.xDestroy method.
36889 **
36890 ** Destroy a cache allocated using pcache1Create().
36891 */
36892 static void pcache1Destroy(sqlite3_pcache *p){
36893   PCache1 *pCache = (PCache1 *)p;
36894   PGroup *pGroup = pCache->pGroup;
36895   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
36896   pcache1EnterMutex(pGroup);
36897   pcache1TruncateUnsafe(pCache, 0);
36898   pGroup->nMaxPage -= pCache->nMax;
36899   pGroup->nMinPage -= pCache->nMin;
36900   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
36901   pcache1EnforceMaxPage(pGroup);
36902   pcache1LeaveMutex(pGroup);
36903   sqlite3_free(pCache->apHash);
36904   sqlite3_free(pCache);
36905 }
36906 
36907 /*
36908 ** This function is called during initialization (sqlite3_initialize()) to
36909 ** install the default pluggable cache module, assuming the user has not
36910 ** already provided an alternative.
36911 */
36912 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
36913   static const sqlite3_pcache_methods defaultMethods = {
36914     0,                       /* pArg */
36915     pcache1Init,             /* xInit */
36916     pcache1Shutdown,         /* xShutdown */
36917     pcache1Create,           /* xCreate */
36918     pcache1Cachesize,        /* xCachesize */
36919     pcache1Pagecount,        /* xPagecount */
36920     pcache1Fetch,            /* xFetch */
36921     pcache1Unpin,            /* xUnpin */
36922     pcache1Rekey,            /* xRekey */
36923     pcache1Truncate,         /* xTruncate */
36924     pcache1Destroy           /* xDestroy */
36925   };
36926   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
36927 }
36928 
36929 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36930 /*
36931 ** This function is called to free superfluous dynamically allocated memory
36932 ** held by the pager system. Memory in use by any SQLite pager allocated
36933 ** by the current thread may be sqlite3_free()ed.
36934 **
36935 ** nReq is the number of bytes of memory required. Once this much has
36936 ** been released, the function returns. The return value is the total number
36937 ** of bytes of memory released.
36938 */
36939 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
36940   int nFree = 0;
36941 #ifdef SQLITE_PAGECACHE_BLOCKALLOC
36942   if( pcache1.grp.isBusy ) return 0;
36943 #endif
36944   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36945   assert( sqlite3_mutex_notheld(pcache1.mutex) );
36946   if( pcache1.pStart==0 ){
36947     PgHdr1 *p;
36948     pcache1EnterMutex(&pcache1.grp);
36949     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
36950       nFree += pcache1MemSize(PGHDR1_TO_PAGE(p));
36951       pcache1PinPage(p);
36952       pcache1RemoveFromHash(p);
36953       pcache1FreePage(p);
36954     }
36955     pcache1LeaveMutex(&pcache1.grp);
36956   }
36957   return nFree;
36958 }
36959 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36960 
36961 #ifdef SQLITE_TEST
36962 /*
36963 ** This function is used by test procedures to inspect the internal state
36964 ** of the global cache.
36965 */
36966 SQLITE_PRIVATE void sqlite3PcacheStats(
36967   int *pnCurrent,      /* OUT: Total number of pages cached */
36968   int *pnMax,          /* OUT: Global maximum cache size */
36969   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
36970   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
36971 ){
36972   PgHdr1 *p;
36973   int nRecyclable = 0;
36974   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
36975     nRecyclable++;
36976   }
36977   *pnCurrent = pcache1.grp.nCurrentPage;
36978   *pnMax = pcache1.grp.nMaxPage;
36979   *pnMin = pcache1.grp.nMinPage;
36980   *pnRecyclable = nRecyclable;
36981 }
36982 #endif
36983 
36984 /************** End of pcache1.c *********************************************/
36985 /************** Begin file rowset.c ******************************************/
36986 /*
36987 ** 2008 December 3
36988 **
36989 ** The author disclaims copyright to this source code.  In place of
36990 ** a legal notice, here is a blessing:
36991 **
36992 **    May you do good and not evil.
36993 **    May you find forgiveness for yourself and forgive others.
36994 **    May you share freely, never taking more than you give.
36995 **
36996 *************************************************************************
36997 **
36998 ** This module implements an object we call a "RowSet".
36999 **
37000 ** The RowSet object is a collection of rowids.  Rowids
37001 ** are inserted into the RowSet in an arbitrary order.  Inserts
37002 ** can be intermixed with tests to see if a given rowid has been
37003 ** previously inserted into the RowSet.
37004 **
37005 ** After all inserts are finished, it is possible to extract the
37006 ** elements of the RowSet in sorted order.  Once this extraction
37007 ** process has started, no new elements may be inserted.
37008 **
37009 ** Hence, the primitive operations for a RowSet are:
37010 **
37011 **    CREATE
37012 **    INSERT
37013 **    TEST
37014 **    SMALLEST
37015 **    DESTROY
37016 **
37017 ** The CREATE and DESTROY primitives are the constructor and destructor,
37018 ** obviously.  The INSERT primitive adds a new element to the RowSet.
37019 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
37020 ** extracts the least value from the RowSet.
37021 **
37022 ** The INSERT primitive might allocate additional memory.  Memory is
37023 ** allocated in chunks so most INSERTs do no allocation.  There is an
37024 ** upper bound on the size of allocated memory.  No memory is freed
37025 ** until DESTROY.
37026 **
37027 ** The TEST primitive includes a "batch" number.  The TEST primitive
37028 ** will only see elements that were inserted before the last change
37029 ** in the batch number.  In other words, if an INSERT occurs between
37030 ** two TESTs where the TESTs have the same batch nubmer, then the
37031 ** value added by the INSERT will not be visible to the second TEST.
37032 ** The initial batch number is zero, so if the very first TEST contains
37033 ** a non-zero batch number, it will see all prior INSERTs.
37034 **
37035 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
37036 ** that is attempted.
37037 **
37038 ** The cost of an INSERT is roughly constant.  (Sometime new memory
37039 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
37040 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
37041 ** The cost of a TEST using the same batch number is O(logN).  The cost
37042 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
37043 ** primitives are constant time.  The cost of DESTROY is O(N).
37044 **
37045 ** There is an added cost of O(N) when switching between TEST and
37046 ** SMALLEST primitives.
37047 */
37048 
37049 
37050 /*
37051 ** Target size for allocation chunks.
37052 */
37053 #define ROWSET_ALLOCATION_SIZE 1024
37054 
37055 /*
37056 ** The number of rowset entries per allocation chunk.
37057 */
37058 #define ROWSET_ENTRY_PER_CHUNK  \
37059                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37060 
37061 /*
37062 ** Each entry in a RowSet is an instance of the following object.
37063 */
37064 struct RowSetEntry {
37065   i64 v;                        /* ROWID value for this entry */
37066   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
37067   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
37068 };
37069 
37070 /*
37071 ** RowSetEntry objects are allocated in large chunks (instances of the
37072 ** following structure) to reduce memory allocation overhead.  The
37073 ** chunks are kept on a linked list so that they can be deallocated
37074 ** when the RowSet is destroyed.
37075 */
37076 struct RowSetChunk {
37077   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
37078   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37079 };
37080 
37081 /*
37082 ** A RowSet in an instance of the following structure.
37083 **
37084 ** A typedef of this structure if found in sqliteInt.h.
37085 */
37086 struct RowSet {
37087   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
37088   sqlite3 *db;                   /* The database connection */
37089   struct RowSetEntry *pEntry;    /* List of entries using pRight */
37090   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
37091   struct RowSetEntry *pFresh;    /* Source of new entry objects */
37092   struct RowSetEntry *pTree;     /* Binary tree of entries */
37093   u16 nFresh;                    /* Number of objects on pFresh */
37094   u8 isSorted;                   /* True if pEntry is sorted */
37095   u8 iBatch;                     /* Current insert batch */
37096 };
37097 
37098 /*
37099 ** Turn bulk memory into a RowSet object.  N bytes of memory
37100 ** are available at pSpace.  The db pointer is used as a memory context
37101 ** for any subsequent allocations that need to occur.
37102 ** Return a pointer to the new RowSet object.
37103 **
37104 ** It must be the case that N is sufficient to make a Rowset.  If not
37105 ** an assertion fault occurs.
37106 **
37107 ** If N is larger than the minimum, use the surplus as an initial
37108 ** allocation of entries available to be filled.
37109 */
37110 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
37111   RowSet *p;
37112   assert( N >= ROUND8(sizeof(*p)) );
37113   p = pSpace;
37114   p->pChunk = 0;
37115   p->db = db;
37116   p->pEntry = 0;
37117   p->pLast = 0;
37118   p->pTree = 0;
37119   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
37120   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
37121   p->isSorted = 1;
37122   p->iBatch = 0;
37123   return p;
37124 }
37125 
37126 /*
37127 ** Deallocate all chunks from a RowSet.  This frees all memory that
37128 ** the RowSet has allocated over its lifetime.  This routine is
37129 ** the destructor for the RowSet.
37130 */
37131 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
37132   struct RowSetChunk *pChunk, *pNextChunk;
37133   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
37134     pNextChunk = pChunk->pNextChunk;
37135     sqlite3DbFree(p->db, pChunk);
37136   }
37137   p->pChunk = 0;
37138   p->nFresh = 0;
37139   p->pEntry = 0;
37140   p->pLast = 0;
37141   p->pTree = 0;
37142   p->isSorted = 1;
37143 }
37144 
37145 /*
37146 ** Insert a new value into a RowSet.
37147 **
37148 ** The mallocFailed flag of the database connection is set if a
37149 ** memory allocation fails.
37150 */
37151 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
37152   struct RowSetEntry *pEntry;  /* The new entry */
37153   struct RowSetEntry *pLast;   /* The last prior entry */
37154   assert( p!=0 );
37155   if( p->nFresh==0 ){
37156     struct RowSetChunk *pNew;
37157     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
37158     if( pNew==0 ){
37159       return;
37160     }
37161     pNew->pNextChunk = p->pChunk;
37162     p->pChunk = pNew;
37163     p->pFresh = pNew->aEntry;
37164     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
37165   }
37166   pEntry = p->pFresh++;
37167   p->nFresh--;
37168   pEntry->v = rowid;
37169   pEntry->pRight = 0;
37170   pLast = p->pLast;
37171   if( pLast ){
37172     if( p->isSorted && rowid<=pLast->v ){
37173       p->isSorted = 0;
37174     }
37175     pLast->pRight = pEntry;
37176   }else{
37177     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
37178     p->pEntry = pEntry;
37179   }
37180   p->pLast = pEntry;
37181 }
37182 
37183 /*
37184 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
37185 **
37186 ** The input lists are connected via pRight pointers and are
37187 ** assumed to each already be in sorted order.
37188 */
37189 static struct RowSetEntry *rowSetMerge(
37190   struct RowSetEntry *pA,    /* First sorted list to be merged */
37191   struct RowSetEntry *pB     /* Second sorted list to be merged */
37192 ){
37193   struct RowSetEntry head;
37194   struct RowSetEntry *pTail;
37195 
37196   pTail = &head;
37197   while( pA && pB ){
37198     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37199     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
37200     if( pA->v<pB->v ){
37201       pTail->pRight = pA;
37202       pA = pA->pRight;
37203       pTail = pTail->pRight;
37204     }else if( pB->v<pA->v ){
37205       pTail->pRight = pB;
37206       pB = pB->pRight;
37207       pTail = pTail->pRight;
37208     }else{
37209       pA = pA->pRight;
37210     }
37211   }
37212   if( pA ){
37213     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37214     pTail->pRight = pA;
37215   }else{
37216     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
37217     pTail->pRight = pB;
37218   }
37219   return head.pRight;
37220 }
37221 
37222 /*
37223 ** Sort all elements on the pEntry list of the RowSet into ascending order.
37224 */
37225 static void rowSetSort(RowSet *p){
37226   unsigned int i;
37227   struct RowSetEntry *pEntry;
37228   struct RowSetEntry *aBucket[40];
37229 
37230   assert( p->isSorted==0 );
37231   memset(aBucket, 0, sizeof(aBucket));
37232   while( p->pEntry ){
37233     pEntry = p->pEntry;
37234     p->pEntry = pEntry->pRight;
37235     pEntry->pRight = 0;
37236     for(i=0; aBucket[i]; i++){
37237       pEntry = rowSetMerge(aBucket[i], pEntry);
37238       aBucket[i] = 0;
37239     }
37240     aBucket[i] = pEntry;
37241   }
37242   pEntry = 0;
37243   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37244     pEntry = rowSetMerge(pEntry, aBucket[i]);
37245   }
37246   p->pEntry = pEntry;
37247   p->pLast = 0;
37248   p->isSorted = 1;
37249 }
37250 
37251 
37252 /*
37253 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37254 ** Convert this tree into a linked list connected by the pRight pointers
37255 ** and return pointers to the first and last elements of the new list.
37256 */
37257 static void rowSetTreeToList(
37258   struct RowSetEntry *pIn,         /* Root of the input tree */
37259   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
37260   struct RowSetEntry **ppLast      /* Write tail of the output list here */
37261 ){
37262   assert( pIn!=0 );
37263   if( pIn->pLeft ){
37264     struct RowSetEntry *p;
37265     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37266     p->pRight = pIn;
37267   }else{
37268     *ppFirst = pIn;
37269   }
37270   if( pIn->pRight ){
37271     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37272   }else{
37273     *ppLast = pIn;
37274   }
37275   assert( (*ppLast)->pRight==0 );
37276 }
37277 
37278 
37279 /*
37280 ** Convert a sorted list of elements (connected by pRight) into a binary
37281 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
37282 ** node taken from the head of *ppList.  A depth of 2 means a tree with
37283 ** three nodes.  And so forth.
37284 **
37285 ** Use as many entries from the input list as required and update the
37286 ** *ppList to point to the unused elements of the list.  If the input
37287 ** list contains too few elements, then construct an incomplete tree
37288 ** and leave *ppList set to NULL.
37289 **
37290 ** Return a pointer to the root of the constructed binary tree.
37291 */
37292 static struct RowSetEntry *rowSetNDeepTree(
37293   struct RowSetEntry **ppList,
37294   int iDepth
37295 ){
37296   struct RowSetEntry *p;         /* Root of the new tree */
37297   struct RowSetEntry *pLeft;     /* Left subtree */
37298   if( *ppList==0 ){
37299     return 0;
37300   }
37301   if( iDepth==1 ){
37302     p = *ppList;
37303     *ppList = p->pRight;
37304     p->pLeft = p->pRight = 0;
37305     return p;
37306   }
37307   pLeft = rowSetNDeepTree(ppList, iDepth-1);
37308   p = *ppList;
37309   if( p==0 ){
37310     return pLeft;
37311   }
37312   p->pLeft = pLeft;
37313   *ppList = p->pRight;
37314   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
37315   return p;
37316 }
37317 
37318 /*
37319 ** Convert a sorted list of elements into a binary tree. Make the tree
37320 ** as deep as it needs to be in order to contain the entire list.
37321 */
37322 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
37323   int iDepth;           /* Depth of the tree so far */
37324   struct RowSetEntry *p;       /* Current tree root */
37325   struct RowSetEntry *pLeft;   /* Left subtree */
37326 
37327   assert( pList!=0 );
37328   p = pList;
37329   pList = p->pRight;
37330   p->pLeft = p->pRight = 0;
37331   for(iDepth=1; pList; iDepth++){
37332     pLeft = p;
37333     p = pList;
37334     pList = p->pRight;
37335     p->pLeft = pLeft;
37336     p->pRight = rowSetNDeepTree(&pList, iDepth);
37337   }
37338   return p;
37339 }
37340 
37341 /*
37342 ** Convert the list in p->pEntry into a sorted list if it is not
37343 ** sorted already.  If there is a binary tree on p->pTree, then
37344 ** convert it into a list too and merge it into the p->pEntry list.
37345 */
37346 static void rowSetToList(RowSet *p){
37347   if( !p->isSorted ){
37348     rowSetSort(p);
37349   }
37350   if( p->pTree ){
37351     struct RowSetEntry *pHead, *pTail;
37352     rowSetTreeToList(p->pTree, &pHead, &pTail);
37353     p->pTree = 0;
37354     p->pEntry = rowSetMerge(p->pEntry, pHead);
37355   }
37356 }
37357 
37358 /*
37359 ** Extract the smallest element from the RowSet.
37360 ** Write the element into *pRowid.  Return 1 on success.  Return
37361 ** 0 if the RowSet is already empty.
37362 **
37363 ** After this routine has been called, the sqlite3RowSetInsert()
37364 ** routine may not be called again.
37365 */
37366 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
37367   rowSetToList(p);
37368   if( p->pEntry ){
37369     *pRowid = p->pEntry->v;
37370     p->pEntry = p->pEntry->pRight;
37371     if( p->pEntry==0 ){
37372       sqlite3RowSetClear(p);
37373     }
37374     return 1;
37375   }else{
37376     return 0;
37377   }
37378 }
37379 
37380 /*
37381 ** Check to see if element iRowid was inserted into the the rowset as
37382 ** part of any insert batch prior to iBatch.  Return 1 or 0.
37383 */
37384 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
37385   struct RowSetEntry *p;
37386   if( iBatch!=pRowSet->iBatch ){
37387     if( pRowSet->pEntry ){
37388       rowSetToList(pRowSet);
37389       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
37390       pRowSet->pEntry = 0;
37391       pRowSet->pLast = 0;
37392     }
37393     pRowSet->iBatch = iBatch;
37394   }
37395   p = pRowSet->pTree;
37396   while( p ){
37397     if( p->v<iRowid ){
37398       p = p->pRight;
37399     }else if( p->v>iRowid ){
37400       p = p->pLeft;
37401     }else{
37402       return 1;
37403     }
37404   }
37405   return 0;
37406 }
37407 
37408 /************** End of rowset.c **********************************************/
37409 /************** Begin file pager.c *******************************************/
37410 /*
37411 ** 2001 September 15
37412 **
37413 ** The author disclaims copyright to this source code.  In place of
37414 ** a legal notice, here is a blessing:
37415 **
37416 **    May you do good and not evil.
37417 **    May you find forgiveness for yourself and forgive others.
37418 **    May you share freely, never taking more than you give.
37419 **
37420 *************************************************************************
37421 ** This is the implementation of the page cache subsystem or "pager".
37422 **
37423 ** The pager is used to access a database disk file.  It implements
37424 ** atomic commit and rollback through the use of a journal file that
37425 ** is separate from the database file.  The pager also implements file
37426 ** locking to prevent two processes from writing the same database
37427 ** file simultaneously, or one process from reading the database while
37428 ** another is writing.
37429 */
37430 #ifndef SQLITE_OMIT_DISKIO
37431 /************** Include wal.h in the middle of pager.c ***********************/
37432 /************** Begin file wal.h *********************************************/
37433 /*
37434 ** 2010 February 1
37435 **
37436 ** The author disclaims copyright to this source code.  In place of
37437 ** a legal notice, here is a blessing:
37438 **
37439 **    May you do good and not evil.
37440 **    May you find forgiveness for yourself and forgive others.
37441 **    May you share freely, never taking more than you give.
37442 **
37443 *************************************************************************
37444 ** This header file defines the interface to the write-ahead logging
37445 ** system. Refer to the comments below and the header comment attached to
37446 ** the implementation of each function in log.c for further details.
37447 */
37448 
37449 #ifndef _WAL_H_
37450 #define _WAL_H_
37451 
37452 
37453 #ifdef SQLITE_OMIT_WAL
37454 # define sqlite3WalOpen(x,y,z)                   0
37455 # define sqlite3WalLimit(x,y)
37456 # define sqlite3WalClose(w,x,y,z)                0
37457 # define sqlite3WalBeginReadTransaction(y,z)     0
37458 # define sqlite3WalEndReadTransaction(z)
37459 # define sqlite3WalRead(v,w,x,y,z)               0
37460 # define sqlite3WalDbsize(y)                     0
37461 # define sqlite3WalBeginWriteTransaction(y)      0
37462 # define sqlite3WalEndWriteTransaction(x)        0
37463 # define sqlite3WalUndo(x,y,z)                   0
37464 # define sqlite3WalSavepoint(y,z)
37465 # define sqlite3WalSavepointUndo(y,z)            0
37466 # define sqlite3WalFrames(u,v,w,x,y,z)           0
37467 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
37468 # define sqlite3WalCallback(z)                   0
37469 # define sqlite3WalExclusiveMode(y,z)            0
37470 # define sqlite3WalHeapMemory(z)                 0
37471 #else
37472 
37473 #define WAL_SAVEPOINT_NDATA 4
37474 
37475 /* Connection to a write-ahead log (WAL) file.
37476 ** There is one object of this type for each pager.
37477 */
37478 typedef struct Wal Wal;
37479 
37480 /* Open and close a connection to a write-ahead log. */
37481 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
37482 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
37483 
37484 /* Set the limiting size of a WAL file. */
37485 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
37486 
37487 /* Used by readers to open (lock) and close (unlock) a snapshot.  A
37488 ** snapshot is like a read-transaction.  It is the state of the database
37489 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
37490 ** preserves the current state even if the other threads or processes
37491 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
37492 ** transaction and releases the lock.
37493 */
37494 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
37495 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
37496 
37497 /* Read a page from the write-ahead log, if it is present. */
37498 SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
37499 
37500 /* If the WAL is not empty, return the size of the database. */
37501 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
37502 
37503 /* Obtain or release the WRITER lock. */
37504 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
37505 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
37506 
37507 /* Undo any frames written (but not committed) to the log */
37508 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
37509 
37510 /* Return an integer that records the current (uncommitted) write
37511 ** position in the WAL */
37512 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
37513 
37514 /* Move the write position of the WAL back to iFrame.  Called in
37515 ** response to a ROLLBACK TO command. */
37516 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
37517 
37518 /* Write a frame or frames to the log. */
37519 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
37520 
37521 /* Copy pages from the log to the database file */
37522 SQLITE_PRIVATE int sqlite3WalCheckpoint(
37523   Wal *pWal,                      /* Write-ahead log connection */
37524   int eMode,                      /* One of PASSIVE, FULL and RESTART */
37525   int (*xBusy)(void*),            /* Function to call when busy */
37526   void *pBusyArg,                 /* Context argument for xBusyHandler */
37527   int sync_flags,                 /* Flags to sync db file with (or 0) */
37528   int nBuf,                       /* Size of buffer nBuf */
37529   u8 *zBuf,                       /* Temporary buffer to use */
37530   int *pnLog,                     /* OUT: Number of frames in WAL */
37531   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
37532 );
37533 
37534 /* Return the value to pass to a sqlite3_wal_hook callback, the
37535 ** number of frames in the WAL at the point of the last commit since
37536 ** sqlite3WalCallback() was called.  If no commits have occurred since
37537 ** the last call, then return 0.
37538 */
37539 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
37540 
37541 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
37542 ** by the pager layer on the database file.
37543 */
37544 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
37545 
37546 /* Return true if the argument is non-NULL and the WAL module is using
37547 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
37548 ** WAL module is using shared-memory, return false.
37549 */
37550 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
37551 
37552 #endif /* ifndef SQLITE_OMIT_WAL */
37553 #endif /* _WAL_H_ */
37554 
37555 /************** End of wal.h *************************************************/
37556 /************** Continuing where we left off in pager.c **********************/
37557 
37558 
37559 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
37560 **
37561 ** This comment block describes invariants that hold when using a rollback
37562 ** journal.  These invariants do not apply for journal_mode=WAL,
37563 ** journal_mode=MEMORY, or journal_mode=OFF.
37564 **
37565 ** Within this comment block, a page is deemed to have been synced
37566 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
37567 ** Otherwise, the page is not synced until the xSync method of the VFS
37568 ** is called successfully on the file containing the page.
37569 **
37570 ** Definition:  A page of the database file is said to be "overwriteable" if
37571 ** one or more of the following are true about the page:
37572 **
37573 **     (a)  The original content of the page as it was at the beginning of
37574 **          the transaction has been written into the rollback journal and
37575 **          synced.
37576 **
37577 **     (b)  The page was a freelist leaf page at the start of the transaction.
37578 **
37579 **     (c)  The page number is greater than the largest page that existed in
37580 **          the database file at the start of the transaction.
37581 **
37582 ** (1) A page of the database file is never overwritten unless one of the
37583 **     following are true:
37584 **
37585 **     (a) The page and all other pages on the same sector are overwriteable.
37586 **
37587 **     (b) The atomic page write optimization is enabled, and the entire
37588 **         transaction other than the update of the transaction sequence
37589 **         number consists of a single page change.
37590 **
37591 ** (2) The content of a page written into the rollback journal exactly matches
37592 **     both the content in the database when the rollback journal was written
37593 **     and the content in the database at the beginning of the current
37594 **     transaction.
37595 **
37596 ** (3) Writes to the database file are an integer multiple of the page size
37597 **     in length and are aligned on a page boundary.
37598 **
37599 ** (4) Reads from the database file are either aligned on a page boundary and
37600 **     an integer multiple of the page size in length or are taken from the
37601 **     first 100 bytes of the database file.
37602 **
37603 ** (5) All writes to the database file are synced prior to the rollback journal
37604 **     being deleted, truncated, or zeroed.
37605 **
37606 ** (6) If a master journal file is used, then all writes to the database file
37607 **     are synced prior to the master journal being deleted.
37608 **
37609 ** Definition: Two databases (or the same database at two points it time)
37610 ** are said to be "logically equivalent" if they give the same answer to
37611 ** all queries.  Note in particular the the content of freelist leaf
37612 ** pages can be changed arbitarily without effecting the logical equivalence
37613 ** of the database.
37614 **
37615 ** (7) At any time, if any subset, including the empty set and the total set,
37616 **     of the unsynced changes to a rollback journal are removed and the
37617 **     journal is rolled back, the resulting database file will be logical
37618 **     equivalent to the database file at the beginning of the transaction.
37619 **
37620 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
37621 **     is called to restore the database file to the same size it was at
37622 **     the beginning of the transaction.  (In some VFSes, the xTruncate
37623 **     method is a no-op, but that does not change the fact the SQLite will
37624 **     invoke it.)
37625 **
37626 ** (9) Whenever the database file is modified, at least one bit in the range
37627 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
37628 **     the EXCLUSIVE lock, thus signaling other connections on the same
37629 **     database to flush their caches.
37630 **
37631 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
37632 **      than one billion transactions.
37633 **
37634 ** (11) A database file is well-formed at the beginning and at the conclusion
37635 **      of every transaction.
37636 **
37637 ** (12) An EXCLUSIVE lock is held on the database file when writing to
37638 **      the database file.
37639 **
37640 ** (13) A SHARED lock is held on the database file while reading any
37641 **      content out of the database file.
37642 **
37643 ******************************************************************************/
37644 
37645 /*
37646 ** Macros for troubleshooting.  Normally turned off
37647 */
37648 #if 0
37649 int sqlite3PagerTrace=1;  /* True to enable tracing */
37650 #define sqlite3DebugPrintf printf
37651 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
37652 #else
37653 #define PAGERTRACE(X)
37654 #endif
37655 
37656 /*
37657 ** The following two macros are used within the PAGERTRACE() macros above
37658 ** to print out file-descriptors.
37659 **
37660 ** PAGERID() takes a pointer to a Pager struct as its argument. The
37661 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
37662 ** struct as its argument.
37663 */
37664 #define PAGERID(p) ((int)(p->fd))
37665 #define FILEHANDLEID(fd) ((int)fd)
37666 
37667 /*
37668 ** The Pager.eState variable stores the current 'state' of a pager. A
37669 ** pager may be in any one of the seven states shown in the following
37670 ** state diagram.
37671 **
37672 **                            OPEN <------+------+
37673 **                              |         |      |
37674 **                              V         |      |
37675 **               +---------> READER-------+      |
37676 **               |              |                |
37677 **               |              V                |
37678 **               |<-------WRITER_LOCKED------> ERROR
37679 **               |              |                ^
37680 **               |              V                |
37681 **               |<------WRITER_CACHEMOD-------->|
37682 **               |              |                |
37683 **               |              V                |
37684 **               |<-------WRITER_DBMOD---------->|
37685 **               |              |                |
37686 **               |              V                |
37687 **               +<------WRITER_FINISHED-------->+
37688 **
37689 **
37690 ** List of state transitions and the C [function] that performs each:
37691 **
37692 **   OPEN              -> READER              [sqlite3PagerSharedLock]
37693 **   READER            -> OPEN                [pager_unlock]
37694 **
37695 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
37696 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
37697 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
37698 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
37699 **   WRITER_***        -> READER              [pager_end_transaction]
37700 **
37701 **   WRITER_***        -> ERROR               [pager_error]
37702 **   ERROR             -> OPEN                [pager_unlock]
37703 **
37704 **
37705 **  OPEN:
37706 **
37707 **    The pager starts up in this state. Nothing is guaranteed in this
37708 **    state - the file may or may not be locked and the database size is
37709 **    unknown. The database may not be read or written.
37710 **
37711 **    * No read or write transaction is active.
37712 **    * Any lock, or no lock at all, may be held on the database file.
37713 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
37714 **
37715 **  READER:
37716 **
37717 **    In this state all the requirements for reading the database in
37718 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
37719 **    was) in exclusive-locking mode, a user-level read transaction is
37720 **    open. The database size is known in this state.
37721 **
37722 **    A connection running with locking_mode=normal enters this state when
37723 **    it opens a read-transaction on the database and returns to state
37724 **    OPEN after the read-transaction is completed. However a connection
37725 **    running in locking_mode=exclusive (including temp databases) remains in
37726 **    this state even after the read-transaction is closed. The only way
37727 **    a locking_mode=exclusive connection can transition from READER to OPEN
37728 **    is via the ERROR state (see below).
37729 **
37730 **    * A read transaction may be active (but a write-transaction cannot).
37731 **    * A SHARED or greater lock is held on the database file.
37732 **    * The dbSize variable may be trusted (even if a user-level read
37733 **      transaction is not active). The dbOrigSize and dbFileSize variables
37734 **      may not be trusted at this point.
37735 **    * If the database is a WAL database, then the WAL connection is open.
37736 **    * Even if a read-transaction is not open, it is guaranteed that
37737 **      there is no hot-journal in the file-system.
37738 **
37739 **  WRITER_LOCKED:
37740 **
37741 **    The pager moves to this state from READER when a write-transaction
37742 **    is first opened on the database. In WRITER_LOCKED state, all locks
37743 **    required to start a write-transaction are held, but no actual
37744 **    modifications to the cache or database have taken place.
37745 **
37746 **    In rollback mode, a RESERVED or (if the transaction was opened with
37747 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
37748 **    moving to this state, but the journal file is not written to or opened
37749 **    to in this state. If the transaction is committed or rolled back while
37750 **    in WRITER_LOCKED state, all that is required is to unlock the database
37751 **    file.
37752 **
37753 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
37754 **    If the connection is running with locking_mode=exclusive, an attempt
37755 **    is made to obtain an EXCLUSIVE lock on the database file.
37756 **
37757 **    * A write transaction is active.
37758 **    * If the connection is open in rollback-mode, a RESERVED or greater
37759 **      lock is held on the database file.
37760 **    * If the connection is open in WAL-mode, a WAL write transaction
37761 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
37762 **      called).
37763 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
37764 **    * The contents of the pager cache have not been modified.
37765 **    * The journal file may or may not be open.
37766 **    * Nothing (not even the first header) has been written to the journal.
37767 **
37768 **  WRITER_CACHEMOD:
37769 **
37770 **    A pager moves from WRITER_LOCKED state to this state when a page is
37771 **    first modified by the upper layer. In rollback mode the journal file
37772 **    is opened (if it is not already open) and a header written to the
37773 **    start of it. The database file on disk has not been modified.
37774 **
37775 **    * A write transaction is active.
37776 **    * A RESERVED or greater lock is held on the database file.
37777 **    * The journal file is open and the first header has been written
37778 **      to it, but the header has not been synced to disk.
37779 **    * The contents of the page cache have been modified.
37780 **
37781 **  WRITER_DBMOD:
37782 **
37783 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
37784 **    when it modifies the contents of the database file. WAL connections
37785 **    never enter this state (since they do not modify the database file,
37786 **    just the log file).
37787 **
37788 **    * A write transaction is active.
37789 **    * An EXCLUSIVE or greater lock is held on the database file.
37790 **    * The journal file is open and the first header has been written
37791 **      and synced to disk.
37792 **    * The contents of the page cache have been modified (and possibly
37793 **      written to disk).
37794 **
37795 **  WRITER_FINISHED:
37796 **
37797 **    It is not possible for a WAL connection to enter this state.
37798 **
37799 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
37800 **    state after the entire transaction has been successfully written into the
37801 **    database file. In this state the transaction may be committed simply
37802 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is
37803 **    not possible to modify the database further. At this point, the upper
37804 **    layer must either commit or rollback the transaction.
37805 **
37806 **    * A write transaction is active.
37807 **    * An EXCLUSIVE or greater lock is held on the database file.
37808 **    * All writing and syncing of journal and database data has finished.
37809 **      If no error occured, all that remains is to finalize the journal to
37810 **      commit the transaction. If an error did occur, the caller will need
37811 **      to rollback the transaction.
37812 **
37813 **  ERROR:
37814 **
37815 **    The ERROR state is entered when an IO or disk-full error (including
37816 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
37817 **    difficult to be sure that the in-memory pager state (cache contents,
37818 **    db size etc.) are consistent with the contents of the file-system.
37819 **
37820 **    Temporary pager files may enter the ERROR state, but in-memory pagers
37821 **    cannot.
37822 **
37823 **    For example, if an IO error occurs while performing a rollback,
37824 **    the contents of the page-cache may be left in an inconsistent state.
37825 **    At this point it would be dangerous to change back to READER state
37826 **    (as usually happens after a rollback). Any subsequent readers might
37827 **    report database corruption (due to the inconsistent cache), and if
37828 **    they upgrade to writers, they may inadvertently corrupt the database
37829 **    file. To avoid this hazard, the pager switches into the ERROR state
37830 **    instead of READER following such an error.
37831 **
37832 **    Once it has entered the ERROR state, any attempt to use the pager
37833 **    to read or write data returns an error. Eventually, once all
37834 **    outstanding transactions have been abandoned, the pager is able to
37835 **    transition back to OPEN state, discarding the contents of the
37836 **    page-cache and any other in-memory state at the same time. Everything
37837 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
37838 **    when a read-transaction is next opened on the pager (transitioning
37839 **    the pager into READER state). At that point the system has recovered
37840 **    from the error.
37841 **
37842 **    Specifically, the pager jumps into the ERROR state if:
37843 **
37844 **      1. An error occurs while attempting a rollback. This happens in
37845 **         function sqlite3PagerRollback().
37846 **
37847 **      2. An error occurs while attempting to finalize a journal file
37848 **         following a commit in function sqlite3PagerCommitPhaseTwo().
37849 **
37850 **      3. An error occurs while attempting to write to the journal or
37851 **         database file in function pagerStress() in order to free up
37852 **         memory.
37853 **
37854 **    In other cases, the error is returned to the b-tree layer. The b-tree
37855 **    layer then attempts a rollback operation. If the error condition
37856 **    persists, the pager enters the ERROR state via condition (1) above.
37857 **
37858 **    Condition (3) is necessary because it can be triggered by a read-only
37859 **    statement executed within a transaction. In this case, if the error
37860 **    code were simply returned to the user, the b-tree layer would not
37861 **    automatically attempt a rollback, as it assumes that an error in a
37862 **    read-only statement cannot leave the pager in an internally inconsistent
37863 **    state.
37864 **
37865 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
37866 **    * There are one or more outstanding references to pages (after the
37867 **      last reference is dropped the pager should move back to OPEN state).
37868 **    * The pager is not an in-memory pager.
37869 **
37870 **
37871 ** Notes:
37872 **
37873 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
37874 **     connection is open in WAL mode. A WAL connection is always in one
37875 **     of the first four states.
37876 **
37877 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
37878 **     state. There are two exceptions: immediately after exclusive-mode has
37879 **     been turned on (and before any read or write transactions are
37880 **     executed), and when the pager is leaving the "error state".
37881 **
37882 **   * See also: assert_pager_state().
37883 */
37884 #define PAGER_OPEN                  0
37885 #define PAGER_READER                1
37886 #define PAGER_WRITER_LOCKED         2
37887 #define PAGER_WRITER_CACHEMOD       3
37888 #define PAGER_WRITER_DBMOD          4
37889 #define PAGER_WRITER_FINISHED       5
37890 #define PAGER_ERROR                 6
37891 
37892 /*
37893 ** The Pager.eLock variable is almost always set to one of the
37894 ** following locking-states, according to the lock currently held on
37895 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
37896 ** This variable is kept up to date as locks are taken and released by
37897 ** the pagerLockDb() and pagerUnlockDb() wrappers.
37898 **
37899 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
37900 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
37901 ** the operation was successful. In these circumstances pagerLockDb() and
37902 ** pagerUnlockDb() take a conservative approach - eLock is always updated
37903 ** when unlocking the file, and only updated when locking the file if the
37904 ** VFS call is successful. This way, the Pager.eLock variable may be set
37905 ** to a less exclusive (lower) value than the lock that is actually held
37906 ** at the system level, but it is never set to a more exclusive value.
37907 **
37908 ** This is usually safe. If an xUnlock fails or appears to fail, there may
37909 ** be a few redundant xLock() calls or a lock may be held for longer than
37910 ** required, but nothing really goes wrong.
37911 **
37912 ** The exception is when the database file is unlocked as the pager moves
37913 ** from ERROR to OPEN state. At this point there may be a hot-journal file
37914 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
37915 ** transition, by the same pager or any other). If the call to xUnlock()
37916 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
37917 ** can confuse the call to xCheckReservedLock() call made later as part
37918 ** of hot-journal detection.
37919 **
37920 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
37921 ** lock held by this process or any others". So xCheckReservedLock may
37922 ** return true because the caller itself is holding an EXCLUSIVE lock (but
37923 ** doesn't know it because of a previous error in xUnlock). If this happens
37924 ** a hot-journal may be mistaken for a journal being created by an active
37925 ** transaction in another process, causing SQLite to read from the database
37926 ** without rolling it back.
37927 **
37928 ** To work around this, if a call to xUnlock() fails when unlocking the
37929 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
37930 ** is only changed back to a real locking state after a successful call
37931 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
37932 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
37933 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
37934 ** lock on the database file before attempting to roll it back. See function
37935 ** PagerSharedLock() for more detail.
37936 **
37937 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
37938 ** PAGER_OPEN state.
37939 */
37940 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
37941 
37942 /*
37943 ** A macro used for invoking the codec if there is one
37944 */
37945 #ifdef SQLITE_HAS_CODEC
37946 # define CODEC1(P,D,N,X,E) \
37947     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
37948 # define CODEC2(P,D,N,X,E,O) \
37949     if( P->xCodec==0 ){ O=(char*)D; }else \
37950     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
37951 #else
37952 # define CODEC1(P,D,N,X,E)   /* NO-OP */
37953 # define CODEC2(P,D,N,X,E,O) O=(char*)D
37954 #endif
37955 
37956 /*
37957 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
37958 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
37959 ** This could conceivably cause corruption following a power failure on
37960 ** such a system. This is currently an undocumented limit.
37961 */
37962 #define MAX_SECTOR_SIZE 0x10000
37963 
37964 /*
37965 ** An instance of the following structure is allocated for each active
37966 ** savepoint and statement transaction in the system. All such structures
37967 ** are stored in the Pager.aSavepoint[] array, which is allocated and
37968 ** resized using sqlite3Realloc().
37969 **
37970 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
37971 ** set to 0. If a journal-header is written into the main journal while
37972 ** the savepoint is active, then iHdrOffset is set to the byte offset
37973 ** immediately following the last journal record written into the main
37974 ** journal before the journal-header. This is required during savepoint
37975 ** rollback (see pagerPlaybackSavepoint()).
37976 */
37977 typedef struct PagerSavepoint PagerSavepoint;
37978 struct PagerSavepoint {
37979   i64 iOffset;                 /* Starting offset in main journal */
37980   i64 iHdrOffset;              /* See above */
37981   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
37982   Pgno nOrig;                  /* Original number of pages in file */
37983   Pgno iSubRec;                /* Index of first record in sub-journal */
37984 #ifndef SQLITE_OMIT_WAL
37985   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
37986 #endif
37987 };
37988 
37989 /*
37990 ** A open page cache is an instance of struct Pager. A description of
37991 ** some of the more important member variables follows:
37992 **
37993 ** eState
37994 **
37995 **   The current 'state' of the pager object. See the comment and state
37996 **   diagram above for a description of the pager state.
37997 **
37998 ** eLock
37999 **
38000 **   For a real on-disk database, the current lock held on the database file -
38001 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38002 **
38003 **   For a temporary or in-memory database (neither of which require any
38004 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38005 **   databases always have Pager.exclusiveMode==1, this tricks the pager
38006 **   logic into thinking that it already has all the locks it will ever
38007 **   need (and no reason to release them).
38008 **
38009 **   In some (obscure) circumstances, this variable may also be set to
38010 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38011 **   details.
38012 **
38013 ** changeCountDone
38014 **
38015 **   This boolean variable is used to make sure that the change-counter
38016 **   (the 4-byte header field at byte offset 24 of the database file) is
38017 **   not updated more often than necessary.
38018 **
38019 **   It is set to true when the change-counter field is updated, which
38020 **   can only happen if an exclusive lock is held on the database file.
38021 **   It is cleared (set to false) whenever an exclusive lock is
38022 **   relinquished on the database file. Each time a transaction is committed,
38023 **   The changeCountDone flag is inspected. If it is true, the work of
38024 **   updating the change-counter is omitted for the current transaction.
38025 **
38026 **   This mechanism means that when running in exclusive mode, a connection
38027 **   need only update the change-counter once, for the first transaction
38028 **   committed.
38029 **
38030 ** setMaster
38031 **
38032 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
38033 **   (or may not) specify a master-journal name to be written into the
38034 **   journal file before it is synced to disk.
38035 **
38036 **   Whether or not a journal file contains a master-journal pointer affects
38037 **   the way in which the journal file is finalized after the transaction is
38038 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
38039 **   If a journal file does not contain a master-journal pointer, it is
38040 **   finalized by overwriting the first journal header with zeroes. If
38041 **   it does contain a master-journal pointer the journal file is finalized
38042 **   by truncating it to zero bytes, just as if the connection were
38043 **   running in "journal_mode=truncate" mode.
38044 **
38045 **   Journal files that contain master journal pointers cannot be finalized
38046 **   simply by overwriting the first journal-header with zeroes, as the
38047 **   master journal pointer could interfere with hot-journal rollback of any
38048 **   subsequently interrupted transaction that reuses the journal file.
38049 **
38050 **   The flag is cleared as soon as the journal file is finalized (either
38051 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38052 **   journal file from being successfully finalized, the setMaster flag
38053 **   is cleared anyway (and the pager will move to ERROR state).
38054 **
38055 ** doNotSpill, doNotSyncSpill
38056 **
38057 **   These two boolean variables control the behaviour of cache-spills
38058 **   (calls made by the pcache module to the pagerStress() routine to
38059 **   write cached data to the file-system in order to free up memory).
38060 **
38061 **   When doNotSpill is non-zero, writing to the database from pagerStress()
38062 **   is disabled altogether. This is done in a very obscure case that
38063 **   comes up during savepoint rollback that requires the pcache module
38064 **   to allocate a new page to prevent the journal file from being written
38065 **   while it is being traversed by code in pager_playback().
38066 **
38067 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
38068 **   is permitted, but syncing the journal file is not. This flag is set
38069 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
38070 **   the database page-size in order to prevent a journal sync from happening
38071 **   in between the journalling of two pages on the same sector.
38072 **
38073 ** subjInMemory
38074 **
38075 **   This is a boolean variable. If true, then any required sub-journal
38076 **   is opened as an in-memory journal file. If false, then in-memory
38077 **   sub-journals are only used for in-memory pager files.
38078 **
38079 **   This variable is updated by the upper layer each time a new
38080 **   write-transaction is opened.
38081 **
38082 ** dbSize, dbOrigSize, dbFileSize
38083 **
38084 **   Variable dbSize is set to the number of pages in the database file.
38085 **   It is valid in PAGER_READER and higher states (all states except for
38086 **   OPEN and ERROR).
38087 **
38088 **   dbSize is set based on the size of the database file, which may be
38089 **   larger than the size of the database (the value stored at offset
38090 **   28 of the database header by the btree). If the size of the file
38091 **   is not an integer multiple of the page-size, the value stored in
38092 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38093 **   Except, any file that is greater than 0 bytes in size is considered
38094 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
38095 **   to dbSize==1).
38096 **
38097 **   During a write-transaction, if pages with page-numbers greater than
38098 **   dbSize are modified in the cache, dbSize is updated accordingly.
38099 **   Similarly, if the database is truncated using PagerTruncateImage(),
38100 **   dbSize is updated.
38101 **
38102 **   Variables dbOrigSize and dbFileSize are valid in states
38103 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
38104 **   variable at the start of the transaction. It is used during rollback,
38105 **   and to determine whether or not pages need to be journalled before
38106 **   being modified.
38107 **
38108 **   Throughout a write-transaction, dbFileSize contains the size of
38109 **   the file on disk in pages. It is set to a copy of dbSize when the
38110 **   write-transaction is first opened, and updated when VFS calls are made
38111 **   to write or truncate the database file on disk.
38112 **
38113 **   The only reason the dbFileSize variable is required is to suppress
38114 **   unnecessary calls to xTruncate() after committing a transaction. If,
38115 **   when a transaction is committed, the dbFileSize variable indicates
38116 **   that the database file is larger than the database image (Pager.dbSize),
38117 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
38118 **   to measure the database file on disk, and then truncates it if required.
38119 **   dbFileSize is not used when rolling back a transaction. In this case
38120 **   pager_truncate() is called unconditionally (which means there may be
38121 **   a call to xFilesize() that is not strictly required). In either case,
38122 **   pager_truncate() may cause the file to become smaller or larger.
38123 **
38124 ** dbHintSize
38125 **
38126 **   The dbHintSize variable is used to limit the number of calls made to
38127 **   the VFS xFileControl(FCNTL_SIZE_HINT) method.
38128 **
38129 **   dbHintSize is set to a copy of the dbSize variable when a
38130 **   write-transaction is opened (at the same time as dbFileSize and
38131 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
38132 **   dbHintSize is increased to the number of pages that correspond to the
38133 **   size-hint passed to the method call. See pager_write_pagelist() for
38134 **   details.
38135 **
38136 ** errCode
38137 **
38138 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
38139 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
38140 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
38141 **   sub-codes.
38142 */
38143 struct Pager {
38144   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
38145   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
38146   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
38147   u8 useJournal;              /* Use a rollback journal on this file */
38148   u8 noReadlock;              /* Do not bother to obtain readlocks */
38149   u8 noSync;                  /* Do not sync the journal if true */
38150   u8 fullSync;                /* Do extra syncs of the journal for robustness */
38151   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38152   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
38153   u8 tempFile;                /* zFilename is a temporary file */
38154   u8 readOnly;                /* True for a read-only database */
38155   u8 memDb;                   /* True to inhibit all file I/O */
38156 
38157   /**************************************************************************
38158   ** The following block contains those class members that change during
38159   ** routine opertion.  Class members not in this block are either fixed
38160   ** when the pager is first created or else only change when there is a
38161   ** significant mode change (such as changing the page_size, locking_mode,
38162   ** or the journal_mode).  From another view, these class members describe
38163   ** the "state" of the pager, while other class members describe the
38164   ** "configuration" of the pager.
38165   */
38166   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38167   u8 eLock;                   /* Current lock held on database file */
38168   u8 changeCountDone;         /* Set after incrementing the change-counter */
38169   u8 setMaster;               /* True if a m-j name has been written to jrnl */
38170   u8 doNotSpill;              /* Do not spill the cache when non-zero */
38171   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
38172   u8 subjInMemory;            /* True to use in-memory sub-journals */
38173   Pgno dbSize;                /* Number of pages in the database */
38174   Pgno dbOrigSize;            /* dbSize before the current transaction */
38175   Pgno dbFileSize;            /* Number of pages in the database file */
38176   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
38177   int errCode;                /* One of several kinds of errors */
38178   int nRec;                   /* Pages journalled since last j-header written */
38179   u32 cksumInit;              /* Quasi-random value added to every checksum */
38180   u32 nSubRec;                /* Number of records written to sub-journal */
38181   Bitvec *pInJournal;         /* One bit for each page in the database file */
38182   sqlite3_file *fd;           /* File descriptor for database */
38183   sqlite3_file *jfd;          /* File descriptor for main journal */
38184   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
38185   i64 journalOff;             /* Current write offset in the journal file */
38186   i64 journalHdr;             /* Byte offset to previous journal header */
38187   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
38188   PagerSavepoint *aSavepoint; /* Array of active savepoints */
38189   int nSavepoint;             /* Number of elements in aSavepoint[] */
38190   char dbFileVers[16];        /* Changes whenever database file changes */
38191   /*
38192   ** End of the routinely-changing class members
38193   ***************************************************************************/
38194 
38195   u16 nExtra;                 /* Add this many bytes to each in-memory page */
38196   i16 nReserve;               /* Number of unused bytes at end of each page */
38197   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
38198   u32 sectorSize;             /* Assumed sector size during rollback */
38199   int pageSize;               /* Number of bytes in a page */
38200   Pgno mxPgno;                /* Maximum allowed size of the database */
38201   i64 journalSizeLimit;       /* Size limit for persistent journal files */
38202   char *zFilename;            /* Name of the database file */
38203   char *zJournal;             /* Name of the journal file */
38204   int (*xBusyHandler)(void*); /* Function to call when busy */
38205   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
38206 #ifdef SQLITE_TEST
38207   int nHit, nMiss;            /* Cache hits and missing */
38208   int nRead, nWrite;          /* Database pages read/written */
38209 #endif
38210   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
38211 #ifdef SQLITE_HAS_CODEC
38212   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
38213   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
38214   void (*xCodecFree)(void*);             /* Destructor for the codec */
38215   void *pCodec;               /* First argument to xCodec... methods */
38216 #endif
38217   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
38218   PCache *pPCache;            /* Pointer to page cache object */
38219 #ifndef SQLITE_OMIT_WAL
38220   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
38221   char *zWal;                 /* File name for write-ahead log */
38222 #endif
38223 };
38224 
38225 /*
38226 ** The following global variables hold counters used for
38227 ** testing purposes only.  These variables do not exist in
38228 ** a non-testing build.  These variables are not thread-safe.
38229 */
38230 #ifdef SQLITE_TEST
38231 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
38232 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
38233 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
38234 # define PAGER_INCR(v)  v++
38235 #else
38236 # define PAGER_INCR(v)
38237 #endif
38238 
38239 
38240 
38241 /*
38242 ** Journal files begin with the following magic string.  The data
38243 ** was obtained from /dev/random.  It is used only as a sanity check.
38244 **
38245 ** Since version 2.8.0, the journal format contains additional sanity
38246 ** checking information.  If the power fails while the journal is being
38247 ** written, semi-random garbage data might appear in the journal
38248 ** file after power is restored.  If an attempt is then made
38249 ** to roll the journal back, the database could be corrupted.  The additional
38250 ** sanity checking data is an attempt to discover the garbage in the
38251 ** journal and ignore it.
38252 **
38253 ** The sanity checking information for the new journal format consists
38254 ** of a 32-bit checksum on each page of data.  The checksum covers both
38255 ** the page number and the pPager->pageSize bytes of data for the page.
38256 ** This cksum is initialized to a 32-bit random value that appears in the
38257 ** journal file right after the header.  The random initializer is important,
38258 ** because garbage data that appears at the end of a journal is likely
38259 ** data that was once in other files that have now been deleted.  If the
38260 ** garbage data came from an obsolete journal file, the checksums might
38261 ** be correct.  But by initializing the checksum to random value which
38262 ** is different for every journal, we minimize that risk.
38263 */
38264 static const unsigned char aJournalMagic[] = {
38265   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
38266 };
38267 
38268 /*
38269 ** The size of the of each page record in the journal is given by
38270 ** the following macro.
38271 */
38272 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
38273 
38274 /*
38275 ** The journal header size for this pager. This is usually the same
38276 ** size as a single disk sector. See also setSectorSize().
38277 */
38278 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
38279 
38280 /*
38281 ** The macro MEMDB is true if we are dealing with an in-memory database.
38282 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
38283 ** the value of MEMDB will be a constant and the compiler will optimize
38284 ** out code that would never execute.
38285 */
38286 #ifdef SQLITE_OMIT_MEMORYDB
38287 # define MEMDB 0
38288 #else
38289 # define MEMDB pPager->memDb
38290 #endif
38291 
38292 /*
38293 ** The maximum legal page number is (2^31 - 1).
38294 */
38295 #define PAGER_MAX_PGNO 2147483647
38296 
38297 /*
38298 ** The argument to this macro is a file descriptor (type sqlite3_file*).
38299 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
38300 **
38301 ** This is so that expressions can be written as:
38302 **
38303 **   if( isOpen(pPager->jfd) ){ ...
38304 **
38305 ** instead of
38306 **
38307 **   if( pPager->jfd->pMethods ){ ...
38308 */
38309 #define isOpen(pFd) ((pFd)->pMethods)
38310 
38311 /*
38312 ** Return true if this pager uses a write-ahead log instead of the usual
38313 ** rollback journal. Otherwise false.
38314 */
38315 #ifndef SQLITE_OMIT_WAL
38316 static int pagerUseWal(Pager *pPager){
38317   return (pPager->pWal!=0);
38318 }
38319 #else
38320 # define pagerUseWal(x) 0
38321 # define pagerRollbackWal(x) 0
38322 # define pagerWalFrames(v,w,x,y,z) 0
38323 # define pagerOpenWalIfPresent(z) SQLITE_OK
38324 # define pagerBeginReadTransaction(z) SQLITE_OK
38325 #endif
38326 
38327 #ifndef NDEBUG
38328 /*
38329 ** Usage:
38330 **
38331 **   assert( assert_pager_state(pPager) );
38332 **
38333 ** This function runs many asserts to try to find inconsistencies in
38334 ** the internal state of the Pager object.
38335 */
38336 static int assert_pager_state(Pager *p){
38337   Pager *pPager = p;
38338 
38339   /* State must be valid. */
38340   assert( p->eState==PAGER_OPEN
38341        || p->eState==PAGER_READER
38342        || p->eState==PAGER_WRITER_LOCKED
38343        || p->eState==PAGER_WRITER_CACHEMOD
38344        || p->eState==PAGER_WRITER_DBMOD
38345        || p->eState==PAGER_WRITER_FINISHED
38346        || p->eState==PAGER_ERROR
38347   );
38348 
38349   /* Regardless of the current state, a temp-file connection always behaves
38350   ** as if it has an exclusive lock on the database file. It never updates
38351   ** the change-counter field, so the changeCountDone flag is always set.
38352   */
38353   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
38354   assert( p->tempFile==0 || pPager->changeCountDone );
38355 
38356   /* If the useJournal flag is clear, the journal-mode must be "OFF".
38357   ** And if the journal-mode is "OFF", the journal file must not be open.
38358   */
38359   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
38360   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
38361 
38362   /* Check that MEMDB implies noSync. And an in-memory journal. Since
38363   ** this means an in-memory pager performs no IO at all, it cannot encounter
38364   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
38365   ** a journal file. (although the in-memory journal implementation may
38366   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
38367   ** is therefore not possible for an in-memory pager to enter the ERROR
38368   ** state.
38369   */
38370   if( MEMDB ){
38371     assert( p->noSync );
38372     assert( p->journalMode==PAGER_JOURNALMODE_OFF
38373          || p->journalMode==PAGER_JOURNALMODE_MEMORY
38374     );
38375     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
38376     assert( pagerUseWal(p)==0 );
38377   }
38378 
38379   /* If changeCountDone is set, a RESERVED lock or greater must be held
38380   ** on the file.
38381   */
38382   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
38383   assert( p->eLock!=PENDING_LOCK );
38384 
38385   switch( p->eState ){
38386     case PAGER_OPEN:
38387       assert( !MEMDB );
38388       assert( pPager->errCode==SQLITE_OK );
38389       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
38390       break;
38391 
38392     case PAGER_READER:
38393       assert( pPager->errCode==SQLITE_OK );
38394       assert( p->eLock!=UNKNOWN_LOCK );
38395       assert( p->eLock>=SHARED_LOCK || p->noReadlock );
38396       break;
38397 
38398     case PAGER_WRITER_LOCKED:
38399       assert( p->eLock!=UNKNOWN_LOCK );
38400       assert( pPager->errCode==SQLITE_OK );
38401       if( !pagerUseWal(pPager) ){
38402         assert( p->eLock>=RESERVED_LOCK );
38403       }
38404       assert( pPager->dbSize==pPager->dbOrigSize );
38405       assert( pPager->dbOrigSize==pPager->dbFileSize );
38406       assert( pPager->dbOrigSize==pPager->dbHintSize );
38407       assert( pPager->setMaster==0 );
38408       break;
38409 
38410     case PAGER_WRITER_CACHEMOD:
38411       assert( p->eLock!=UNKNOWN_LOCK );
38412       assert( pPager->errCode==SQLITE_OK );
38413       if( !pagerUseWal(pPager) ){
38414         /* It is possible that if journal_mode=wal here that neither the
38415         ** journal file nor the WAL file are open. This happens during
38416         ** a rollback transaction that switches from journal_mode=off
38417         ** to journal_mode=wal.
38418         */
38419         assert( p->eLock>=RESERVED_LOCK );
38420         assert( isOpen(p->jfd)
38421              || p->journalMode==PAGER_JOURNALMODE_OFF
38422              || p->journalMode==PAGER_JOURNALMODE_WAL
38423         );
38424       }
38425       assert( pPager->dbOrigSize==pPager->dbFileSize );
38426       assert( pPager->dbOrigSize==pPager->dbHintSize );
38427       break;
38428 
38429     case PAGER_WRITER_DBMOD:
38430       assert( p->eLock==EXCLUSIVE_LOCK );
38431       assert( pPager->errCode==SQLITE_OK );
38432       assert( !pagerUseWal(pPager) );
38433       assert( p->eLock>=EXCLUSIVE_LOCK );
38434       assert( isOpen(p->jfd)
38435            || p->journalMode==PAGER_JOURNALMODE_OFF
38436            || p->journalMode==PAGER_JOURNALMODE_WAL
38437       );
38438       assert( pPager->dbOrigSize<=pPager->dbHintSize );
38439       break;
38440 
38441     case PAGER_WRITER_FINISHED:
38442       assert( p->eLock==EXCLUSIVE_LOCK );
38443       assert( pPager->errCode==SQLITE_OK );
38444       assert( !pagerUseWal(pPager) );
38445       assert( isOpen(p->jfd)
38446            || p->journalMode==PAGER_JOURNALMODE_OFF
38447            || p->journalMode==PAGER_JOURNALMODE_WAL
38448       );
38449       break;
38450 
38451     case PAGER_ERROR:
38452       /* There must be at least one outstanding reference to the pager if
38453       ** in ERROR state. Otherwise the pager should have already dropped
38454       ** back to OPEN state.
38455       */
38456       assert( pPager->errCode!=SQLITE_OK );
38457       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
38458       break;
38459   }
38460 
38461   return 1;
38462 }
38463 #endif /* ifndef NDEBUG */
38464 
38465 #ifdef SQLITE_DEBUG
38466 /*
38467 ** Return a pointer to a human readable string in a static buffer
38468 ** containing the state of the Pager object passed as an argument. This
38469 ** is intended to be used within debuggers. For example, as an alternative
38470 ** to "print *pPager" in gdb:
38471 **
38472 ** (gdb) printf "%s", print_pager_state(pPager)
38473 */
38474 static char *print_pager_state(Pager *p){
38475   static char zRet[1024];
38476 
38477   sqlite3_snprintf(1024, zRet,
38478       "Filename:      %s\n"
38479       "State:         %s errCode=%d\n"
38480       "Lock:          %s\n"
38481       "Locking mode:  locking_mode=%s\n"
38482       "Journal mode:  journal_mode=%s\n"
38483       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
38484       "Journal:       journalOff=%lld journalHdr=%lld\n"
38485       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
38486       , p->zFilename
38487       , p->eState==PAGER_OPEN            ? "OPEN" :
38488         p->eState==PAGER_READER          ? "READER" :
38489         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
38490         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
38491         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
38492         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
38493         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
38494       , (int)p->errCode
38495       , p->eLock==NO_LOCK         ? "NO_LOCK" :
38496         p->eLock==RESERVED_LOCK   ? "RESERVED" :
38497         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
38498         p->eLock==SHARED_LOCK     ? "SHARED" :
38499         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
38500       , p->exclusiveMode ? "exclusive" : "normal"
38501       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
38502         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
38503         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
38504         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
38505         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
38506         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
38507       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
38508       , p->journalOff, p->journalHdr
38509       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
38510   );
38511 
38512   return zRet;
38513 }
38514 #endif
38515 
38516 /*
38517 ** Return true if it is necessary to write page *pPg into the sub-journal.
38518 ** A page needs to be written into the sub-journal if there exists one
38519 ** or more open savepoints for which:
38520 **
38521 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
38522 **   * The bit corresponding to the page-number is not set in
38523 **     PagerSavepoint.pInSavepoint.
38524 */
38525 static int subjRequiresPage(PgHdr *pPg){
38526   Pgno pgno = pPg->pgno;
38527   Pager *pPager = pPg->pPager;
38528   int i;
38529   for(i=0; i<pPager->nSavepoint; i++){
38530     PagerSavepoint *p = &pPager->aSavepoint[i];
38531     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
38532       return 1;
38533     }
38534   }
38535   return 0;
38536 }
38537 
38538 /*
38539 ** Return true if the page is already in the journal file.
38540 */
38541 static int pageInJournal(PgHdr *pPg){
38542   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
38543 }
38544 
38545 /*
38546 ** Read a 32-bit integer from the given file descriptor.  Store the integer
38547 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
38548 ** error code is something goes wrong.
38549 **
38550 ** All values are stored on disk as big-endian.
38551 */
38552 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
38553   unsigned char ac[4];
38554   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
38555   if( rc==SQLITE_OK ){
38556     *pRes = sqlite3Get4byte(ac);
38557   }
38558   return rc;
38559 }
38560 
38561 /*
38562 ** Write a 32-bit integer into a string buffer in big-endian byte order.
38563 */
38564 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
38565 
38566 
38567 /*
38568 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
38569 ** on success or an error code is something goes wrong.
38570 */
38571 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
38572   char ac[4];
38573   put32bits(ac, val);
38574   return sqlite3OsWrite(fd, ac, 4, offset);
38575 }
38576 
38577 /*
38578 ** Unlock the database file to level eLock, which must be either NO_LOCK
38579 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
38580 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
38581 **
38582 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38583 ** called, do not modify it. See the comment above the #define of
38584 ** UNKNOWN_LOCK for an explanation of this.
38585 */
38586 static int pagerUnlockDb(Pager *pPager, int eLock){
38587   int rc = SQLITE_OK;
38588 
38589   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
38590   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
38591   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
38592   if( isOpen(pPager->fd) ){
38593     assert( pPager->eLock>=eLock );
38594     rc = sqlite3OsUnlock(pPager->fd, eLock);
38595     if( pPager->eLock!=UNKNOWN_LOCK ){
38596       pPager->eLock = (u8)eLock;
38597     }
38598     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
38599   }
38600   return rc;
38601 }
38602 
38603 /*
38604 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
38605 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
38606 ** Pager.eLock variable to the new locking state.
38607 **
38608 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
38609 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
38610 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
38611 ** of this.
38612 */
38613 static int pagerLockDb(Pager *pPager, int eLock){
38614   int rc = SQLITE_OK;
38615 
38616   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
38617   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
38618     rc = sqlite3OsLock(pPager->fd, eLock);
38619     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
38620       pPager->eLock = (u8)eLock;
38621       IOTRACE(("LOCK %p %d\n", pPager, eLock))
38622     }
38623   }
38624   return rc;
38625 }
38626 
38627 /*
38628 ** This function determines whether or not the atomic-write optimization
38629 ** can be used with this pager. The optimization can be used if:
38630 **
38631 **  (a) the value returned by OsDeviceCharacteristics() indicates that
38632 **      a database page may be written atomically, and
38633 **  (b) the value returned by OsSectorSize() is less than or equal
38634 **      to the page size.
38635 **
38636 ** The optimization is also always enabled for temporary files. It is
38637 ** an error to call this function if pPager is opened on an in-memory
38638 ** database.
38639 **
38640 ** If the optimization cannot be used, 0 is returned. If it can be used,
38641 ** then the value returned is the size of the journal file when it
38642 ** contains rollback data for exactly one page.
38643 */
38644 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
38645 static int jrnlBufferSize(Pager *pPager){
38646   assert( !MEMDB );
38647   if( !pPager->tempFile ){
38648     int dc;                           /* Device characteristics */
38649     int nSector;                      /* Sector size */
38650     int szPage;                       /* Page size */
38651 
38652     assert( isOpen(pPager->fd) );
38653     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
38654     nSector = pPager->sectorSize;
38655     szPage = pPager->pageSize;
38656 
38657     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
38658     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
38659     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
38660       return 0;
38661     }
38662   }
38663 
38664   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
38665 }
38666 #endif
38667 
38668 /*
38669 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
38670 ** on the cache using a hash function.  This is used for testing
38671 ** and debugging only.
38672 */
38673 #ifdef SQLITE_CHECK_PAGES
38674 /*
38675 ** Return a 32-bit hash of the page data for pPage.
38676 */
38677 static u32 pager_datahash(int nByte, unsigned char *pData){
38678   u32 hash = 0;
38679   int i;
38680   for(i=0; i<nByte; i++){
38681     hash = (hash*1039) + pData[i];
38682   }
38683   return hash;
38684 }
38685 static u32 pager_pagehash(PgHdr *pPage){
38686   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
38687 }
38688 static void pager_set_pagehash(PgHdr *pPage){
38689   pPage->pageHash = pager_pagehash(pPage);
38690 }
38691 
38692 /*
38693 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
38694 ** is defined, and NDEBUG is not defined, an assert() statement checks
38695 ** that the page is either dirty or still matches the calculated page-hash.
38696 */
38697 #define CHECK_PAGE(x) checkPage(x)
38698 static void checkPage(PgHdr *pPg){
38699   Pager *pPager = pPg->pPager;
38700   assert( pPager->eState!=PAGER_ERROR );
38701   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
38702 }
38703 
38704 #else
38705 #define pager_datahash(X,Y)  0
38706 #define pager_pagehash(X)  0
38707 #define pager_set_pagehash(X)
38708 #define CHECK_PAGE(x)
38709 #endif  /* SQLITE_CHECK_PAGES */
38710 
38711 /*
38712 ** When this is called the journal file for pager pPager must be open.
38713 ** This function attempts to read a master journal file name from the
38714 ** end of the file and, if successful, copies it into memory supplied
38715 ** by the caller. See comments above writeMasterJournal() for the format
38716 ** used to store a master journal file name at the end of a journal file.
38717 **
38718 ** zMaster must point to a buffer of at least nMaster bytes allocated by
38719 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
38720 ** enough space to write the master journal name). If the master journal
38721 ** name in the journal is longer than nMaster bytes (including a
38722 ** nul-terminator), then this is handled as if no master journal name
38723 ** were present in the journal.
38724 **
38725 ** If a master journal file name is present at the end of the journal
38726 ** file, then it is copied into the buffer pointed to by zMaster. A
38727 ** nul-terminator byte is appended to the buffer following the master
38728 ** journal file name.
38729 **
38730 ** If it is determined that no master journal file name is present
38731 ** zMaster[0] is set to 0 and SQLITE_OK returned.
38732 **
38733 ** If an error occurs while reading from the journal file, an SQLite
38734 ** error code is returned.
38735 */
38736 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
38737   int rc;                    /* Return code */
38738   u32 len;                   /* Length in bytes of master journal name */
38739   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
38740   u32 cksum;                 /* MJ checksum value read from journal */
38741   u32 u;                     /* Unsigned loop counter */
38742   unsigned char aMagic[8];   /* A buffer to hold the magic header */
38743   zMaster[0] = '\0';
38744 
38745   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
38746    || szJ<16
38747    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
38748    || len>=nMaster
38749    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
38750    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
38751    || memcmp(aMagic, aJournalMagic, 8)
38752    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
38753   ){
38754     return rc;
38755   }
38756 
38757   /* See if the checksum matches the master journal name */
38758   for(u=0; u<len; u++){
38759     cksum -= zMaster[u];
38760   }
38761   if( cksum ){
38762     /* If the checksum doesn't add up, then one or more of the disk sectors
38763     ** containing the master journal filename is corrupted. This means
38764     ** definitely roll back, so just return SQLITE_OK and report a (nul)
38765     ** master-journal filename.
38766     */
38767     len = 0;
38768   }
38769   zMaster[len] = '\0';
38770 
38771   return SQLITE_OK;
38772 }
38773 
38774 /*
38775 ** Return the offset of the sector boundary at or immediately
38776 ** following the value in pPager->journalOff, assuming a sector
38777 ** size of pPager->sectorSize bytes.
38778 **
38779 ** i.e for a sector size of 512:
38780 **
38781 **   Pager.journalOff          Return value
38782 **   ---------------------------------------
38783 **   0                         0
38784 **   512                       512
38785 **   100                       512
38786 **   2000                      2048
38787 **
38788 */
38789 static i64 journalHdrOffset(Pager *pPager){
38790   i64 offset = 0;
38791   i64 c = pPager->journalOff;
38792   if( c ){
38793     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
38794   }
38795   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
38796   assert( offset>=c );
38797   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
38798   return offset;
38799 }
38800 
38801 /*
38802 ** The journal file must be open when this function is called.
38803 **
38804 ** This function is a no-op if the journal file has not been written to
38805 ** within the current transaction (i.e. if Pager.journalOff==0).
38806 **
38807 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
38808 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
38809 ** zero the 28-byte header at the start of the journal file. In either case,
38810 ** if the pager is not in no-sync mode, sync the journal file immediately
38811 ** after writing or truncating it.
38812 **
38813 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
38814 ** following the truncation or zeroing described above the size of the
38815 ** journal file in bytes is larger than this value, then truncate the
38816 ** journal file to Pager.journalSizeLimit bytes. The journal file does
38817 ** not need to be synced following this operation.
38818 **
38819 ** If an IO error occurs, abandon processing and return the IO error code.
38820 ** Otherwise, return SQLITE_OK.
38821 */
38822 static int zeroJournalHdr(Pager *pPager, int doTruncate){
38823   int rc = SQLITE_OK;                               /* Return code */
38824   assert( isOpen(pPager->jfd) );
38825   if( pPager->journalOff ){
38826     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
38827 
38828     IOTRACE(("JZEROHDR %p\n", pPager))
38829     if( doTruncate || iLimit==0 ){
38830       rc = sqlite3OsTruncate(pPager->jfd, 0);
38831     }else{
38832       static const char zeroHdr[28] = {0};
38833       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
38834     }
38835     if( rc==SQLITE_OK && !pPager->noSync ){
38836       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
38837     }
38838 
38839     /* At this point the transaction is committed but the write lock
38840     ** is still held on the file. If there is a size limit configured for
38841     ** the persistent journal and the journal file currently consumes more
38842     ** space than that limit allows for, truncate it now. There is no need
38843     ** to sync the file following this operation.
38844     */
38845     if( rc==SQLITE_OK && iLimit>0 ){
38846       i64 sz;
38847       rc = sqlite3OsFileSize(pPager->jfd, &sz);
38848       if( rc==SQLITE_OK && sz>iLimit ){
38849         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
38850       }
38851     }
38852   }
38853   return rc;
38854 }
38855 
38856 /*
38857 ** The journal file must be open when this routine is called. A journal
38858 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
38859 ** current location.
38860 **
38861 ** The format for the journal header is as follows:
38862 ** - 8 bytes: Magic identifying journal format.
38863 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
38864 ** - 4 bytes: Random number used for page hash.
38865 ** - 4 bytes: Initial database page count.
38866 ** - 4 bytes: Sector size used by the process that wrote this journal.
38867 ** - 4 bytes: Database page size.
38868 **
38869 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
38870 */
38871 static int writeJournalHdr(Pager *pPager){
38872   int rc = SQLITE_OK;                 /* Return code */
38873   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
38874   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
38875   u32 nWrite;                         /* Bytes of header sector written */
38876   int ii;                             /* Loop counter */
38877 
38878   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
38879 
38880   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
38881     nHeader = JOURNAL_HDR_SZ(pPager);
38882   }
38883 
38884   /* If there are active savepoints and any of them were created
38885   ** since the most recent journal header was written, update the
38886   ** PagerSavepoint.iHdrOffset fields now.
38887   */
38888   for(ii=0; ii<pPager->nSavepoint; ii++){
38889     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
38890       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
38891     }
38892   }
38893 
38894   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
38895 
38896   /*
38897   ** Write the nRec Field - the number of page records that follow this
38898   ** journal header. Normally, zero is written to this value at this time.
38899   ** After the records are added to the journal (and the journal synced,
38900   ** if in full-sync mode), the zero is overwritten with the true number
38901   ** of records (see syncJournal()).
38902   **
38903   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
38904   ** reading the journal this value tells SQLite to assume that the
38905   ** rest of the journal file contains valid page records. This assumption
38906   ** is dangerous, as if a failure occurred whilst writing to the journal
38907   ** file it may contain some garbage data. There are two scenarios
38908   ** where this risk can be ignored:
38909   **
38910   **   * When the pager is in no-sync mode. Corruption can follow a
38911   **     power failure in this case anyway.
38912   **
38913   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
38914   **     that garbage data is never appended to the journal file.
38915   */
38916   assert( isOpen(pPager->fd) || pPager->noSync );
38917   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
38918    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
38919   ){
38920     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
38921     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
38922   }else{
38923     memset(zHeader, 0, sizeof(aJournalMagic)+4);
38924   }
38925 
38926   /* The random check-hash initialiser */
38927   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
38928   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
38929   /* The initial database size */
38930   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
38931   /* The assumed sector size for this process */
38932   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
38933 
38934   /* The page size */
38935   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
38936 
38937   /* Initializing the tail of the buffer is not necessary.  Everything
38938   ** works find if the following memset() is omitted.  But initializing
38939   ** the memory prevents valgrind from complaining, so we are willing to
38940   ** take the performance hit.
38941   */
38942   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
38943          nHeader-(sizeof(aJournalMagic)+20));
38944 
38945   /* In theory, it is only necessary to write the 28 bytes that the
38946   ** journal header consumes to the journal file here. Then increment the
38947   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
38948   ** record is written to the following sector (leaving a gap in the file
38949   ** that will be implicitly filled in by the OS).
38950   **
38951   ** However it has been discovered that on some systems this pattern can
38952   ** be significantly slower than contiguously writing data to the file,
38953   ** even if that means explicitly writing data to the block of
38954   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
38955   ** is done.
38956   **
38957   ** The loop is required here in case the sector-size is larger than the
38958   ** database page size. Since the zHeader buffer is only Pager.pageSize
38959   ** bytes in size, more than one call to sqlite3OsWrite() may be required
38960   ** to populate the entire journal header sector.
38961   */
38962   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
38963     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
38964     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
38965     assert( pPager->journalHdr <= pPager->journalOff );
38966     pPager->journalOff += nHeader;
38967   }
38968 
38969   return rc;
38970 }
38971 
38972 /*
38973 ** The journal file must be open when this is called. A journal header file
38974 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
38975 ** file. The current location in the journal file is given by
38976 ** pPager->journalOff. See comments above function writeJournalHdr() for
38977 ** a description of the journal header format.
38978 **
38979 ** If the header is read successfully, *pNRec is set to the number of
38980 ** page records following this header and *pDbSize is set to the size of the
38981 ** database before the transaction began, in pages. Also, pPager->cksumInit
38982 ** is set to the value read from the journal header. SQLITE_OK is returned
38983 ** in this case.
38984 **
38985 ** If the journal header file appears to be corrupted, SQLITE_DONE is
38986 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
38987 ** cannot be read from the journal file an error code is returned.
38988 */
38989 static int readJournalHdr(
38990   Pager *pPager,               /* Pager object */
38991   int isHot,
38992   i64 journalSize,             /* Size of the open journal file in bytes */
38993   u32 *pNRec,                  /* OUT: Value read from the nRec field */
38994   u32 *pDbSize                 /* OUT: Value of original database size field */
38995 ){
38996   int rc;                      /* Return code */
38997   unsigned char aMagic[8];     /* A buffer to hold the magic header */
38998   i64 iHdrOff;                 /* Offset of journal header being read */
38999 
39000   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39001 
39002   /* Advance Pager.journalOff to the start of the next sector. If the
39003   ** journal file is too small for there to be a header stored at this
39004   ** point, return SQLITE_DONE.
39005   */
39006   pPager->journalOff = journalHdrOffset(pPager);
39007   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39008     return SQLITE_DONE;
39009   }
39010   iHdrOff = pPager->journalOff;
39011 
39012   /* Read in the first 8 bytes of the journal header. If they do not match
39013   ** the  magic string found at the start of each journal header, return
39014   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39015   ** proceed.
39016   */
39017   if( isHot || iHdrOff!=pPager->journalHdr ){
39018     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39019     if( rc ){
39020       return rc;
39021     }
39022     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39023       return SQLITE_DONE;
39024     }
39025   }
39026 
39027   /* Read the first three 32-bit fields of the journal header: The nRec
39028   ** field, the checksum-initializer and the database size at the start
39029   ** of the transaction. Return an error code if anything goes wrong.
39030   */
39031   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39032    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39033    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39034   ){
39035     return rc;
39036   }
39037 
39038   if( pPager->journalOff==0 ){
39039     u32 iPageSize;               /* Page-size field of journal header */
39040     u32 iSectorSize;             /* Sector-size field of journal header */
39041 
39042     /* Read the page-size and sector-size journal header fields. */
39043     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39044      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39045     ){
39046       return rc;
39047     }
39048 
39049     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39050     ** journal header to zero. In this case, assume that the Pager.pageSize
39051     ** variable is already set to the correct page size.
39052     */
39053     if( iPageSize==0 ){
39054       iPageSize = pPager->pageSize;
39055     }
39056 
39057     /* Check that the values read from the page-size and sector-size fields
39058     ** are within range. To be 'in range', both values need to be a power
39059     ** of two greater than or equal to 512 or 32, and not greater than their
39060     ** respective compile time maximum limits.
39061     */
39062     if( iPageSize<512                  || iSectorSize<32
39063      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39064      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
39065     ){
39066       /* If the either the page-size or sector-size in the journal-header is
39067       ** invalid, then the process that wrote the journal-header must have
39068       ** crashed before the header was synced. In this case stop reading
39069       ** the journal file here.
39070       */
39071       return SQLITE_DONE;
39072     }
39073 
39074     /* Update the page-size to match the value read from the journal.
39075     ** Use a testcase() macro to make sure that malloc failure within
39076     ** PagerSetPagesize() is tested.
39077     */
39078     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39079     testcase( rc!=SQLITE_OK );
39080 
39081     /* Update the assumed sector-size to match the value used by
39082     ** the process that created this journal. If this journal was
39083     ** created by a process other than this one, then this routine
39084     ** is being called from within pager_playback(). The local value
39085     ** of Pager.sectorSize is restored at the end of that routine.
39086     */
39087     pPager->sectorSize = iSectorSize;
39088   }
39089 
39090   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39091   return rc;
39092 }
39093 
39094 
39095 /*
39096 ** Write the supplied master journal name into the journal file for pager
39097 ** pPager at the current location. The master journal name must be the last
39098 ** thing written to a journal file. If the pager is in full-sync mode, the
39099 ** journal file descriptor is advanced to the next sector boundary before
39100 ** anything is written. The format is:
39101 **
39102 **   + 4 bytes: PAGER_MJ_PGNO.
39103 **   + N bytes: Master journal filename in utf-8.
39104 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
39105 **   + 4 bytes: Master journal name checksum.
39106 **   + 8 bytes: aJournalMagic[].
39107 **
39108 ** The master journal page checksum is the sum of the bytes in the master
39109 ** journal name, where each byte is interpreted as a signed 8-bit integer.
39110 **
39111 ** If zMaster is a NULL pointer (occurs for a single database transaction),
39112 ** this call is a no-op.
39113 */
39114 static int writeMasterJournal(Pager *pPager, const char *zMaster){
39115   int rc;                          /* Return code */
39116   int nMaster;                     /* Length of string zMaster */
39117   i64 iHdrOff;                     /* Offset of header in journal file */
39118   i64 jrnlSize;                    /* Size of journal file on disk */
39119   u32 cksum = 0;                   /* Checksum of string zMaster */
39120 
39121   assert( pPager->setMaster==0 );
39122   assert( !pagerUseWal(pPager) );
39123 
39124   if( !zMaster
39125    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39126    || pPager->journalMode==PAGER_JOURNALMODE_OFF
39127   ){
39128     return SQLITE_OK;
39129   }
39130   pPager->setMaster = 1;
39131   assert( isOpen(pPager->jfd) );
39132   assert( pPager->journalHdr <= pPager->journalOff );
39133 
39134   /* Calculate the length in bytes and the checksum of zMaster */
39135   for(nMaster=0; zMaster[nMaster]; nMaster++){
39136     cksum += zMaster[nMaster];
39137   }
39138 
39139   /* If in full-sync mode, advance to the next disk sector before writing
39140   ** the master journal name. This is in case the previous page written to
39141   ** the journal has already been synced.
39142   */
39143   if( pPager->fullSync ){
39144     pPager->journalOff = journalHdrOffset(pPager);
39145   }
39146   iHdrOff = pPager->journalOff;
39147 
39148   /* Write the master journal data to the end of the journal file. If
39149   ** an error occurs, return the error code to the caller.
39150   */
39151   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39152    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39153    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39154    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39155    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39156   ){
39157     return rc;
39158   }
39159   pPager->journalOff += (nMaster+20);
39160 
39161   /* If the pager is in peristent-journal mode, then the physical
39162   ** journal-file may extend past the end of the master-journal name
39163   ** and 8 bytes of magic data just written to the file. This is
39164   ** dangerous because the code to rollback a hot-journal file
39165   ** will not be able to find the master-journal name to determine
39166   ** whether or not the journal is hot.
39167   **
39168   ** Easiest thing to do in this scenario is to truncate the journal
39169   ** file to the required size.
39170   */
39171   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
39172    && jrnlSize>pPager->journalOff
39173   ){
39174     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
39175   }
39176   return rc;
39177 }
39178 
39179 /*
39180 ** Find a page in the hash table given its page number. Return
39181 ** a pointer to the page or NULL if the requested page is not
39182 ** already in memory.
39183 */
39184 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
39185   PgHdr *p;                         /* Return value */
39186 
39187   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
39188   ** fail, since no attempt to allocate dynamic memory will be made.
39189   */
39190   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
39191   return p;
39192 }
39193 
39194 /*
39195 ** Discard the entire contents of the in-memory page-cache.
39196 */
39197 static void pager_reset(Pager *pPager){
39198   sqlite3BackupRestart(pPager->pBackup);
39199   sqlite3PcacheClear(pPager->pPCache);
39200 }
39201 
39202 /*
39203 ** Free all structures in the Pager.aSavepoint[] array and set both
39204 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
39205 ** if it is open and the pager is not in exclusive mode.
39206 */
39207 static void releaseAllSavepoints(Pager *pPager){
39208   int ii;               /* Iterator for looping through Pager.aSavepoint */
39209   for(ii=0; ii<pPager->nSavepoint; ii++){
39210     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
39211   }
39212   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
39213     sqlite3OsClose(pPager->sjfd);
39214   }
39215   sqlite3_free(pPager->aSavepoint);
39216   pPager->aSavepoint = 0;
39217   pPager->nSavepoint = 0;
39218   pPager->nSubRec = 0;
39219 }
39220 
39221 /*
39222 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
39223 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
39224 ** or SQLITE_NOMEM if a malloc failure occurs.
39225 */
39226 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
39227   int ii;                   /* Loop counter */
39228   int rc = SQLITE_OK;       /* Result code */
39229 
39230   for(ii=0; ii<pPager->nSavepoint; ii++){
39231     PagerSavepoint *p = &pPager->aSavepoint[ii];
39232     if( pgno<=p->nOrig ){
39233       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
39234       testcase( rc==SQLITE_NOMEM );
39235       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
39236     }
39237   }
39238   return rc;
39239 }
39240 
39241 /*
39242 ** This function is a no-op if the pager is in exclusive mode and not
39243 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
39244 ** state.
39245 **
39246 ** If the pager is not in exclusive-access mode, the database file is
39247 ** completely unlocked. If the file is unlocked and the file-system does
39248 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
39249 ** closed (if it is open).
39250 **
39251 ** If the pager is in ERROR state when this function is called, the
39252 ** contents of the pager cache are discarded before switching back to
39253 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
39254 ** or not, any journal file left in the file-system will be treated
39255 ** as a hot-journal and rolled back the next time a read-transaction
39256 ** is opened (by this or by any other connection).
39257 */
39258 static void pager_unlock(Pager *pPager){
39259 
39260   assert( pPager->eState==PAGER_READER
39261        || pPager->eState==PAGER_OPEN
39262        || pPager->eState==PAGER_ERROR
39263   );
39264 
39265   sqlite3BitvecDestroy(pPager->pInJournal);
39266   pPager->pInJournal = 0;
39267   releaseAllSavepoints(pPager);
39268 
39269   if( pagerUseWal(pPager) ){
39270     assert( !isOpen(pPager->jfd) );
39271     sqlite3WalEndReadTransaction(pPager->pWal);
39272     pPager->eState = PAGER_OPEN;
39273   }else if( !pPager->exclusiveMode ){
39274     int rc;                       /* Error code returned by pagerUnlockDb() */
39275     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
39276 
39277     /* If the operating system support deletion of open files, then
39278     ** close the journal file when dropping the database lock.  Otherwise
39279     ** another connection with journal_mode=delete might delete the file
39280     ** out from under us.
39281     */
39282     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
39283     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
39284     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
39285     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
39286     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
39287     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
39288     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
39289      || 1!=(pPager->journalMode & 5)
39290     ){
39291       sqlite3OsClose(pPager->jfd);
39292     }
39293 
39294     /* If the pager is in the ERROR state and the call to unlock the database
39295     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
39296     ** above the #define for UNKNOWN_LOCK for an explanation of why this
39297     ** is necessary.
39298     */
39299     rc = pagerUnlockDb(pPager, NO_LOCK);
39300     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
39301       pPager->eLock = UNKNOWN_LOCK;
39302     }
39303 
39304     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
39305     ** without clearing the error code. This is intentional - the error
39306     ** code is cleared and the cache reset in the block below.
39307     */
39308     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
39309     pPager->changeCountDone = 0;
39310     pPager->eState = PAGER_OPEN;
39311   }
39312 
39313   /* If Pager.errCode is set, the contents of the pager cache cannot be
39314   ** trusted. Now that there are no outstanding references to the pager,
39315   ** it can safely move back to PAGER_OPEN state. This happens in both
39316   ** normal and exclusive-locking mode.
39317   */
39318   if( pPager->errCode ){
39319     assert( !MEMDB );
39320     pager_reset(pPager);
39321     pPager->changeCountDone = pPager->tempFile;
39322     pPager->eState = PAGER_OPEN;
39323     pPager->errCode = SQLITE_OK;
39324   }
39325 
39326   pPager->journalOff = 0;
39327   pPager->journalHdr = 0;
39328   pPager->setMaster = 0;
39329 }
39330 
39331 /*
39332 ** This function is called whenever an IOERR or FULL error that requires
39333 ** the pager to transition into the ERROR state may ahve occurred.
39334 ** The first argument is a pointer to the pager structure, the second
39335 ** the error-code about to be returned by a pager API function. The
39336 ** value returned is a copy of the second argument to this function.
39337 **
39338 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
39339 ** IOERR sub-codes, the pager enters the ERROR state and the error code
39340 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
39341 ** all major API calls on the Pager will immediately return Pager.errCode.
39342 **
39343 ** The ERROR state indicates that the contents of the pager-cache
39344 ** cannot be trusted. This state can be cleared by completely discarding
39345 ** the contents of the pager-cache. If a transaction was active when
39346 ** the persistent error occurred, then the rollback journal may need
39347 ** to be replayed to restore the contents of the database file (as if
39348 ** it were a hot-journal).
39349 */
39350 static int pager_error(Pager *pPager, int rc){
39351   int rc2 = rc & 0xff;
39352   assert( rc==SQLITE_OK || !MEMDB );
39353   assert(
39354        pPager->errCode==SQLITE_FULL ||
39355        pPager->errCode==SQLITE_OK ||
39356        (pPager->errCode & 0xff)==SQLITE_IOERR
39357   );
39358   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
39359     pPager->errCode = rc;
39360     pPager->eState = PAGER_ERROR;
39361   }
39362   return rc;
39363 }
39364 
39365 /*
39366 ** This routine ends a transaction. A transaction is usually ended by
39367 ** either a COMMIT or a ROLLBACK operation. This routine may be called
39368 ** after rollback of a hot-journal, or if an error occurs while opening
39369 ** the journal file or writing the very first journal-header of a
39370 ** database transaction.
39371 **
39372 ** This routine is never called in PAGER_ERROR state. If it is called
39373 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
39374 ** exclusive than a RESERVED lock, it is a no-op.
39375 **
39376 ** Otherwise, any active savepoints are released.
39377 **
39378 ** If the journal file is open, then it is "finalized". Once a journal
39379 ** file has been finalized it is not possible to use it to roll back a
39380 ** transaction. Nor will it be considered to be a hot-journal by this
39381 ** or any other database connection. Exactly how a journal is finalized
39382 ** depends on whether or not the pager is running in exclusive mode and
39383 ** the current journal-mode (Pager.journalMode value), as follows:
39384 **
39385 **   journalMode==MEMORY
39386 **     Journal file descriptor is simply closed. This destroys an
39387 **     in-memory journal.
39388 **
39389 **   journalMode==TRUNCATE
39390 **     Journal file is truncated to zero bytes in size.
39391 **
39392 **   journalMode==PERSIST
39393 **     The first 28 bytes of the journal file are zeroed. This invalidates
39394 **     the first journal header in the file, and hence the entire journal
39395 **     file. An invalid journal file cannot be rolled back.
39396 **
39397 **   journalMode==DELETE
39398 **     The journal file is closed and deleted using sqlite3OsDelete().
39399 **
39400 **     If the pager is running in exclusive mode, this method of finalizing
39401 **     the journal file is never used. Instead, if the journalMode is
39402 **     DELETE and the pager is in exclusive mode, the method described under
39403 **     journalMode==PERSIST is used instead.
39404 **
39405 ** After the journal is finalized, the pager moves to PAGER_READER state.
39406 ** If running in non-exclusive rollback mode, the lock on the file is
39407 ** downgraded to a SHARED_LOCK.
39408 **
39409 ** SQLITE_OK is returned if no error occurs. If an error occurs during
39410 ** any of the IO operations to finalize the journal file or unlock the
39411 ** database then the IO error code is returned to the user. If the
39412 ** operation to finalize the journal file fails, then the code still
39413 ** tries to unlock the database file if not in exclusive mode. If the
39414 ** unlock operation fails as well, then the first error code related
39415 ** to the first error encountered (the journal finalization one) is
39416 ** returned.
39417 */
39418 static int pager_end_transaction(Pager *pPager, int hasMaster){
39419   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
39420   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
39421 
39422   /* Do nothing if the pager does not have an open write transaction
39423   ** or at least a RESERVED lock. This function may be called when there
39424   ** is no write-transaction active but a RESERVED or greater lock is
39425   ** held under two circumstances:
39426   **
39427   **   1. After a successful hot-journal rollback, it is called with
39428   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
39429   **
39430   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
39431   **      lock switches back to locking_mode=normal and then executes a
39432   **      read-transaction, this function is called with eState==PAGER_READER
39433   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
39434   */
39435   assert( assert_pager_state(pPager) );
39436   assert( pPager->eState!=PAGER_ERROR );
39437   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
39438     return SQLITE_OK;
39439   }
39440 
39441   releaseAllSavepoints(pPager);
39442   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
39443   if( isOpen(pPager->jfd) ){
39444     assert( !pagerUseWal(pPager) );
39445 
39446     /* Finalize the journal file. */
39447     if( sqlite3IsMemJournal(pPager->jfd) ){
39448       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
39449       sqlite3OsClose(pPager->jfd);
39450     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
39451       if( pPager->journalOff==0 ){
39452         rc = SQLITE_OK;
39453       }else{
39454         rc = sqlite3OsTruncate(pPager->jfd, 0);
39455       }
39456       pPager->journalOff = 0;
39457     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
39458       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
39459     ){
39460       rc = zeroJournalHdr(pPager, hasMaster);
39461       pPager->journalOff = 0;
39462     }else{
39463       /* This branch may be executed with Pager.journalMode==MEMORY if
39464       ** a hot-journal was just rolled back. In this case the journal
39465       ** file should be closed and deleted. If this connection writes to
39466       ** the database file, it will do so using an in-memory journal.
39467       */
39468       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
39469            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
39470            || pPager->journalMode==PAGER_JOURNALMODE_WAL
39471       );
39472       sqlite3OsClose(pPager->jfd);
39473       if( !pPager->tempFile ){
39474         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
39475       }
39476     }
39477   }
39478 
39479 #ifdef SQLITE_CHECK_PAGES
39480   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
39481   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
39482     PgHdr *p = pager_lookup(pPager, 1);
39483     if( p ){
39484       p->pageHash = 0;
39485       sqlite3PagerUnref(p);
39486     }
39487   }
39488 #endif
39489 
39490   sqlite3BitvecDestroy(pPager->pInJournal);
39491   pPager->pInJournal = 0;
39492   pPager->nRec = 0;
39493   sqlite3PcacheCleanAll(pPager->pPCache);
39494   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
39495 
39496   if( pagerUseWal(pPager) ){
39497     /* Drop the WAL write-lock, if any. Also, if the connection was in
39498     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
39499     ** lock held on the database file.
39500     */
39501     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
39502     assert( rc2==SQLITE_OK );
39503   }
39504   if( !pPager->exclusiveMode
39505    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
39506   ){
39507     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
39508     pPager->changeCountDone = 0;
39509   }
39510   pPager->eState = PAGER_READER;
39511   pPager->setMaster = 0;
39512 
39513   return (rc==SQLITE_OK?rc2:rc);
39514 }
39515 
39516 /*
39517 ** Execute a rollback if a transaction is active and unlock the
39518 ** database file.
39519 **
39520 ** If the pager has already entered the ERROR state, do not attempt
39521 ** the rollback at this time. Instead, pager_unlock() is called. The
39522 ** call to pager_unlock() will discard all in-memory pages, unlock
39523 ** the database file and move the pager back to OPEN state. If this
39524 ** means that there is a hot-journal left in the file-system, the next
39525 ** connection to obtain a shared lock on the pager (which may be this one)
39526 ** will roll it back.
39527 **
39528 ** If the pager has not already entered the ERROR state, but an IO or
39529 ** malloc error occurs during a rollback, then this will itself cause
39530 ** the pager to enter the ERROR state. Which will be cleared by the
39531 ** call to pager_unlock(), as described above.
39532 */
39533 static void pagerUnlockAndRollback(Pager *pPager){
39534   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
39535     assert( assert_pager_state(pPager) );
39536     if( pPager->eState>=PAGER_WRITER_LOCKED ){
39537       sqlite3BeginBenignMalloc();
39538       sqlite3PagerRollback(pPager);
39539       sqlite3EndBenignMalloc();
39540     }else if( !pPager->exclusiveMode ){
39541       assert( pPager->eState==PAGER_READER );
39542       pager_end_transaction(pPager, 0);
39543     }
39544   }
39545   pager_unlock(pPager);
39546 }
39547 
39548 /*
39549 ** Parameter aData must point to a buffer of pPager->pageSize bytes
39550 ** of data. Compute and return a checksum based ont the contents of the
39551 ** page of data and the current value of pPager->cksumInit.
39552 **
39553 ** This is not a real checksum. It is really just the sum of the
39554 ** random initial value (pPager->cksumInit) and every 200th byte
39555 ** of the page data, starting with byte offset (pPager->pageSize%200).
39556 ** Each byte is interpreted as an 8-bit unsigned integer.
39557 **
39558 ** Changing the formula used to compute this checksum results in an
39559 ** incompatible journal file format.
39560 **
39561 ** If journal corruption occurs due to a power failure, the most likely
39562 ** scenario is that one end or the other of the record will be changed.
39563 ** It is much less likely that the two ends of the journal record will be
39564 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
39565 ** though fast and simple, catches the mostly likely kind of corruption.
39566 */
39567 static u32 pager_cksum(Pager *pPager, const u8 *aData){
39568   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
39569   int i = pPager->pageSize-200;          /* Loop counter */
39570   while( i>0 ){
39571     cksum += aData[i];
39572     i -= 200;
39573   }
39574   return cksum;
39575 }
39576 
39577 /*
39578 ** Report the current page size and number of reserved bytes back
39579 ** to the codec.
39580 */
39581 #ifdef SQLITE_HAS_CODEC
39582 static void pagerReportSize(Pager *pPager){
39583   if( pPager->xCodecSizeChng ){
39584     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
39585                            (int)pPager->nReserve);
39586   }
39587 }
39588 #else
39589 # define pagerReportSize(X)     /* No-op if we do not support a codec */
39590 #endif
39591 
39592 /*
39593 ** Read a single page from either the journal file (if isMainJrnl==1) or
39594 ** from the sub-journal (if isMainJrnl==0) and playback that page.
39595 ** The page begins at offset *pOffset into the file. The *pOffset
39596 ** value is increased to the start of the next page in the journal.
39597 **
39598 ** The main rollback journal uses checksums - the statement journal does
39599 ** not.
39600 **
39601 ** If the page number of the page record read from the (sub-)journal file
39602 ** is greater than the current value of Pager.dbSize, then playback is
39603 ** skipped and SQLITE_OK is returned.
39604 **
39605 ** If pDone is not NULL, then it is a record of pages that have already
39606 ** been played back.  If the page at *pOffset has already been played back
39607 ** (if the corresponding pDone bit is set) then skip the playback.
39608 ** Make sure the pDone bit corresponding to the *pOffset page is set
39609 ** prior to returning.
39610 **
39611 ** If the page record is successfully read from the (sub-)journal file
39612 ** and played back, then SQLITE_OK is returned. If an IO error occurs
39613 ** while reading the record from the (sub-)journal file or while writing
39614 ** to the database file, then the IO error code is returned. If data
39615 ** is successfully read from the (sub-)journal file but appears to be
39616 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
39617 ** two circumstances:
39618 **
39619 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
39620 **   * If the record is being rolled back from the main journal file
39621 **     and the checksum field does not match the record content.
39622 **
39623 ** Neither of these two scenarios are possible during a savepoint rollback.
39624 **
39625 ** If this is a savepoint rollback, then memory may have to be dynamically
39626 ** allocated by this function. If this is the case and an allocation fails,
39627 ** SQLITE_NOMEM is returned.
39628 */
39629 static int pager_playback_one_page(
39630   Pager *pPager,                /* The pager being played back */
39631   i64 *pOffset,                 /* Offset of record to playback */
39632   Bitvec *pDone,                /* Bitvec of pages already played back */
39633   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
39634   int isSavepnt                 /* True for a savepoint rollback */
39635 ){
39636   int rc;
39637   PgHdr *pPg;                   /* An existing page in the cache */
39638   Pgno pgno;                    /* The page number of a page in journal */
39639   u32 cksum;                    /* Checksum used for sanity checking */
39640   char *aData;                  /* Temporary storage for the page */
39641   sqlite3_file *jfd;            /* The file descriptor for the journal file */
39642   int isSynced;                 /* True if journal page is synced */
39643 
39644   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
39645   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
39646   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
39647   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
39648 
39649   aData = pPager->pTmpSpace;
39650   assert( aData );         /* Temp storage must have already been allocated */
39651   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
39652 
39653   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
39654   ** or savepoint rollback done at the request of the caller) or this is
39655   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
39656   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
39657   ** only reads from the main journal, not the sub-journal.
39658   */
39659   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
39660        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
39661   );
39662   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
39663 
39664   /* Read the page number and page data from the journal or sub-journal
39665   ** file. Return an error code to the caller if an IO error occurs.
39666   */
39667   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
39668   rc = read32bits(jfd, *pOffset, &pgno);
39669   if( rc!=SQLITE_OK ) return rc;
39670   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
39671   if( rc!=SQLITE_OK ) return rc;
39672   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
39673 
39674   /* Sanity checking on the page.  This is more important that I originally
39675   ** thought.  If a power failure occurs while the journal is being written,
39676   ** it could cause invalid data to be written into the journal.  We need to
39677   ** detect this invalid data (with high probability) and ignore it.
39678   */
39679   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
39680     assert( !isSavepnt );
39681     return SQLITE_DONE;
39682   }
39683   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
39684     return SQLITE_OK;
39685   }
39686   if( isMainJrnl ){
39687     rc = read32bits(jfd, (*pOffset)-4, &cksum);
39688     if( rc ) return rc;
39689     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
39690       return SQLITE_DONE;
39691     }
39692   }
39693 
39694   /* If this page has already been played by before during the current
39695   ** rollback, then don't bother to play it back again.
39696   */
39697   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
39698     return rc;
39699   }
39700 
39701   /* When playing back page 1, restore the nReserve setting
39702   */
39703   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
39704     pPager->nReserve = ((u8*)aData)[20];
39705     pagerReportSize(pPager);
39706   }
39707 
39708   /* If the pager is in CACHEMOD state, then there must be a copy of this
39709   ** page in the pager cache. In this case just update the pager cache,
39710   ** not the database file. The page is left marked dirty in this case.
39711   **
39712   ** An exception to the above rule: If the database is in no-sync mode
39713   ** and a page is moved during an incremental vacuum then the page may
39714   ** not be in the pager cache. Later: if a malloc() or IO error occurs
39715   ** during a Movepage() call, then the page may not be in the cache
39716   ** either. So the condition described in the above paragraph is not
39717   ** assert()able.
39718   **
39719   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
39720   ** pager cache if it exists and the main file. The page is then marked
39721   ** not dirty. Since this code is only executed in PAGER_OPEN state for
39722   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
39723   ** if the pager is in OPEN state.
39724   **
39725   ** Ticket #1171:  The statement journal might contain page content that is
39726   ** different from the page content at the start of the transaction.
39727   ** This occurs when a page is changed prior to the start of a statement
39728   ** then changed again within the statement.  When rolling back such a
39729   ** statement we must not write to the original database unless we know
39730   ** for certain that original page contents are synced into the main rollback
39731   ** journal.  Otherwise, a power loss might leave modified data in the
39732   ** database file without an entry in the rollback journal that can
39733   ** restore the database to its original form.  Two conditions must be
39734   ** met before writing to the database files. (1) the database must be
39735   ** locked.  (2) we know that the original page content is fully synced
39736   ** in the main journal either because the page is not in cache or else
39737   ** the page is marked as needSync==0.
39738   **
39739   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
39740   ** is possible to fail a statement on a database that does not yet exist.
39741   ** Do not attempt to write if database file has never been opened.
39742   */
39743   if( pagerUseWal(pPager) ){
39744     pPg = 0;
39745   }else{
39746     pPg = pager_lookup(pPager, pgno);
39747   }
39748   assert( pPg || !MEMDB );
39749   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
39750   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
39751            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
39752            (isMainJrnl?"main-journal":"sub-journal")
39753   ));
39754   if( isMainJrnl ){
39755     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
39756   }else{
39757     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
39758   }
39759   if( isOpen(pPager->fd)
39760    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
39761    && isSynced
39762   ){
39763     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
39764     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
39765     assert( !pagerUseWal(pPager) );
39766     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
39767     if( pgno>pPager->dbFileSize ){
39768       pPager->dbFileSize = pgno;
39769     }
39770     if( pPager->pBackup ){
39771       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
39772       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
39773       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
39774     }
39775   }else if( !isMainJrnl && pPg==0 ){
39776     /* If this is a rollback of a savepoint and data was not written to
39777     ** the database and the page is not in-memory, there is a potential
39778     ** problem. When the page is next fetched by the b-tree layer, it
39779     ** will be read from the database file, which may or may not be
39780     ** current.
39781     **
39782     ** There are a couple of different ways this can happen. All are quite
39783     ** obscure. When running in synchronous mode, this can only happen
39784     ** if the page is on the free-list at the start of the transaction, then
39785     ** populated, then moved using sqlite3PagerMovepage().
39786     **
39787     ** The solution is to add an in-memory page to the cache containing
39788     ** the data just read from the sub-journal. Mark the page as dirty
39789     ** and if the pager requires a journal-sync, then mark the page as
39790     ** requiring a journal-sync before it is written.
39791     */
39792     assert( isSavepnt );
39793     assert( pPager->doNotSpill==0 );
39794     pPager->doNotSpill++;
39795     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
39796     assert( pPager->doNotSpill==1 );
39797     pPager->doNotSpill--;
39798     if( rc!=SQLITE_OK ) return rc;
39799     pPg->flags &= ~PGHDR_NEED_READ;
39800     sqlite3PcacheMakeDirty(pPg);
39801   }
39802   if( pPg ){
39803     /* No page should ever be explicitly rolled back that is in use, except
39804     ** for page 1 which is held in use in order to keep the lock on the
39805     ** database active. However such a page may be rolled back as a result
39806     ** of an internal error resulting in an automatic call to
39807     ** sqlite3PagerRollback().
39808     */
39809     void *pData;
39810     pData = pPg->pData;
39811     memcpy(pData, (u8*)aData, pPager->pageSize);
39812     pPager->xReiniter(pPg);
39813     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
39814       /* If the contents of this page were just restored from the main
39815       ** journal file, then its content must be as they were when the
39816       ** transaction was first opened. In this case we can mark the page
39817       ** as clean, since there will be no need to write it out to the
39818       ** database.
39819       **
39820       ** There is one exception to this rule. If the page is being rolled
39821       ** back as part of a savepoint (or statement) rollback from an
39822       ** unsynced portion of the main journal file, then it is not safe
39823       ** to mark the page as clean. This is because marking the page as
39824       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
39825       ** already in the journal file (recorded in Pager.pInJournal) and
39826       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
39827       ** again within this transaction, it will be marked as dirty but
39828       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
39829       ** be written out into the database file before its journal file
39830       ** segment is synced. If a crash occurs during or following this,
39831       ** database corruption may ensue.
39832       */
39833       assert( !pagerUseWal(pPager) );
39834       sqlite3PcacheMakeClean(pPg);
39835     }
39836     pager_set_pagehash(pPg);
39837 
39838     /* If this was page 1, then restore the value of Pager.dbFileVers.
39839     ** Do this before any decoding. */
39840     if( pgno==1 ){
39841       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
39842     }
39843 
39844     /* Decode the page just read from disk */
39845     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
39846     sqlite3PcacheRelease(pPg);
39847   }
39848   return rc;
39849 }
39850 
39851 /*
39852 ** Parameter zMaster is the name of a master journal file. A single journal
39853 ** file that referred to the master journal file has just been rolled back.
39854 ** This routine checks if it is possible to delete the master journal file,
39855 ** and does so if it is.
39856 **
39857 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
39858 ** available for use within this function.
39859 **
39860 ** When a master journal file is created, it is populated with the names
39861 ** of all of its child journals, one after another, formatted as utf-8
39862 ** encoded text. The end of each child journal file is marked with a
39863 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
39864 ** file for a transaction involving two databases might be:
39865 **
39866 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
39867 **
39868 ** A master journal file may only be deleted once all of its child
39869 ** journals have been rolled back.
39870 **
39871 ** This function reads the contents of the master-journal file into
39872 ** memory and loops through each of the child journal names. For
39873 ** each child journal, it checks if:
39874 **
39875 **   * if the child journal exists, and if so
39876 **   * if the child journal contains a reference to master journal
39877 **     file zMaster
39878 **
39879 ** If a child journal can be found that matches both of the criteria
39880 ** above, this function returns without doing anything. Otherwise, if
39881 ** no such child journal can be found, file zMaster is deleted from
39882 ** the file-system using sqlite3OsDelete().
39883 **
39884 ** If an IO error within this function, an error code is returned. This
39885 ** function allocates memory by calling sqlite3Malloc(). If an allocation
39886 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
39887 ** occur, SQLITE_OK is returned.
39888 **
39889 ** TODO: This function allocates a single block of memory to load
39890 ** the entire contents of the master journal file. This could be
39891 ** a couple of kilobytes or so - potentially larger than the page
39892 ** size.
39893 */
39894 static int pager_delmaster(Pager *pPager, const char *zMaster){
39895   sqlite3_vfs *pVfs = pPager->pVfs;
39896   int rc;                   /* Return code */
39897   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
39898   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
39899   char *zMasterJournal = 0; /* Contents of master journal file */
39900   i64 nMasterJournal;       /* Size of master journal file */
39901   char *zJournal;           /* Pointer to one journal within MJ file */
39902   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
39903   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
39904 
39905   /* Allocate space for both the pJournal and pMaster file descriptors.
39906   ** If successful, open the master journal file for reading.
39907   */
39908   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
39909   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
39910   if( !pMaster ){
39911     rc = SQLITE_NOMEM;
39912   }else{
39913     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
39914     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
39915   }
39916   if( rc!=SQLITE_OK ) goto delmaster_out;
39917 
39918   /* Load the entire master journal file into space obtained from
39919   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
39920   ** sufficient space (in zMasterPtr) to hold the names of master
39921   ** journal files extracted from regular rollback-journals.
39922   */
39923   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
39924   if( rc!=SQLITE_OK ) goto delmaster_out;
39925   nMasterPtr = pVfs->mxPathname+1;
39926   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
39927   if( !zMasterJournal ){
39928     rc = SQLITE_NOMEM;
39929     goto delmaster_out;
39930   }
39931   zMasterPtr = &zMasterJournal[nMasterJournal+1];
39932   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
39933   if( rc!=SQLITE_OK ) goto delmaster_out;
39934   zMasterJournal[nMasterJournal] = 0;
39935 
39936   zJournal = zMasterJournal;
39937   while( (zJournal-zMasterJournal)<nMasterJournal ){
39938     int exists;
39939     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
39940     if( rc!=SQLITE_OK ){
39941       goto delmaster_out;
39942     }
39943     if( exists ){
39944       /* One of the journals pointed to by the master journal exists.
39945       ** Open it and check if it points at the master journal. If
39946       ** so, return without deleting the master journal file.
39947       */
39948       int c;
39949       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
39950       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
39951       if( rc!=SQLITE_OK ){
39952         goto delmaster_out;
39953       }
39954 
39955       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
39956       sqlite3OsClose(pJournal);
39957       if( rc!=SQLITE_OK ){
39958         goto delmaster_out;
39959       }
39960 
39961       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
39962       if( c ){
39963         /* We have a match. Do not delete the master journal file. */
39964         goto delmaster_out;
39965       }
39966     }
39967     zJournal += (sqlite3Strlen30(zJournal)+1);
39968   }
39969 
39970   sqlite3OsClose(pMaster);
39971   rc = sqlite3OsDelete(pVfs, zMaster, 0);
39972 
39973 delmaster_out:
39974   sqlite3_free(zMasterJournal);
39975   if( pMaster ){
39976     sqlite3OsClose(pMaster);
39977     assert( !isOpen(pJournal) );
39978     sqlite3_free(pMaster);
39979   }
39980   return rc;
39981 }
39982 
39983 
39984 /*
39985 ** This function is used to change the actual size of the database
39986 ** file in the file-system. This only happens when committing a transaction,
39987 ** or rolling back a transaction (including rolling back a hot-journal).
39988 **
39989 ** If the main database file is not open, or the pager is not in either
39990 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
39991 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
39992 ** If the file on disk is currently larger than nPage pages, then use the VFS
39993 ** xTruncate() method to truncate it.
39994 **
39995 ** Or, it might might be the case that the file on disk is smaller than
39996 ** nPage pages. Some operating system implementations can get confused if
39997 ** you try to truncate a file to some size that is larger than it
39998 ** currently is, so detect this case and write a single zero byte to
39999 ** the end of the new file instead.
40000 **
40001 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
40002 ** the database file, return the error code to the caller.
40003 */
40004 static int pager_truncate(Pager *pPager, Pgno nPage){
40005   int rc = SQLITE_OK;
40006   assert( pPager->eState!=PAGER_ERROR );
40007   assert( pPager->eState!=PAGER_READER );
40008 
40009   if( isOpen(pPager->fd)
40010    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40011   ){
40012     i64 currentSize, newSize;
40013     int szPage = pPager->pageSize;
40014     assert( pPager->eLock==EXCLUSIVE_LOCK );
40015     /* TODO: Is it safe to use Pager.dbFileSize here? */
40016     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40017     newSize = szPage*(i64)nPage;
40018     if( rc==SQLITE_OK && currentSize!=newSize ){
40019       if( currentSize>newSize ){
40020         rc = sqlite3OsTruncate(pPager->fd, newSize);
40021       }else{
40022         char *pTmp = pPager->pTmpSpace;
40023         memset(pTmp, 0, szPage);
40024         testcase( (newSize-szPage) <  currentSize );
40025         testcase( (newSize-szPage) == currentSize );
40026         testcase( (newSize-szPage) >  currentSize );
40027         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40028       }
40029       if( rc==SQLITE_OK ){
40030         pPager->dbFileSize = nPage;
40031       }
40032     }
40033   }
40034   return rc;
40035 }
40036 
40037 /*
40038 ** Set the value of the Pager.sectorSize variable for the given
40039 ** pager based on the value returned by the xSectorSize method
40040 ** of the open database file. The sector size will be used used
40041 ** to determine the size and alignment of journal header and
40042 ** master journal pointers within created journal files.
40043 **
40044 ** For temporary files the effective sector size is always 512 bytes.
40045 **
40046 ** Otherwise, for non-temporary files, the effective sector size is
40047 ** the value returned by the xSectorSize() method rounded up to 32 if
40048 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40049 ** is greater than MAX_SECTOR_SIZE.
40050 */
40051 static void setSectorSize(Pager *pPager){
40052   assert( isOpen(pPager->fd) || pPager->tempFile );
40053 
40054   if( !pPager->tempFile ){
40055     /* Sector size doesn't matter for temporary files. Also, the file
40056     ** may not have been opened yet, in which case the OsSectorSize()
40057     ** call will segfault.
40058     */
40059     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
40060   }
40061   if( pPager->sectorSize<32 ){
40062     pPager->sectorSize = 512;
40063   }
40064   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
40065     assert( MAX_SECTOR_SIZE>=512 );
40066     pPager->sectorSize = MAX_SECTOR_SIZE;
40067   }
40068 }
40069 
40070 /*
40071 ** Playback the journal and thus restore the database file to
40072 ** the state it was in before we started making changes.
40073 **
40074 ** The journal file format is as follows:
40075 **
40076 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
40077 **  (2)  4 byte big-endian integer which is the number of valid page records
40078 **       in the journal.  If this value is 0xffffffff, then compute the
40079 **       number of page records from the journal size.
40080 **  (3)  4 byte big-endian integer which is the initial value for the
40081 **       sanity checksum.
40082 **  (4)  4 byte integer which is the number of pages to truncate the
40083 **       database to during a rollback.
40084 **  (5)  4 byte big-endian integer which is the sector size.  The header
40085 **       is this many bytes in size.
40086 **  (6)  4 byte big-endian integer which is the page size.
40087 **  (7)  zero padding out to the next sector size.
40088 **  (8)  Zero or more pages instances, each as follows:
40089 **        +  4 byte page number.
40090 **        +  pPager->pageSize bytes of data.
40091 **        +  4 byte checksum
40092 **
40093 ** When we speak of the journal header, we mean the first 7 items above.
40094 ** Each entry in the journal is an instance of the 8th item.
40095 **
40096 ** Call the value from the second bullet "nRec".  nRec is the number of
40097 ** valid page entries in the journal.  In most cases, you can compute the
40098 ** value of nRec from the size of the journal file.  But if a power
40099 ** failure occurred while the journal was being written, it could be the
40100 ** case that the size of the journal file had already been increased but
40101 ** the extra entries had not yet made it safely to disk.  In such a case,
40102 ** the value of nRec computed from the file size would be too large.  For
40103 ** that reason, we always use the nRec value in the header.
40104 **
40105 ** If the nRec value is 0xffffffff it means that nRec should be computed
40106 ** from the file size.  This value is used when the user selects the
40107 ** no-sync option for the journal.  A power failure could lead to corruption
40108 ** in this case.  But for things like temporary table (which will be
40109 ** deleted when the power is restored) we don't care.
40110 **
40111 ** If the file opened as the journal file is not a well-formed
40112 ** journal file then all pages up to the first corrupted page are rolled
40113 ** back (or no pages if the journal header is corrupted). The journal file
40114 ** is then deleted and SQLITE_OK returned, just as if no corruption had
40115 ** been encountered.
40116 **
40117 ** If an I/O or malloc() error occurs, the journal-file is not deleted
40118 ** and an error code is returned.
40119 **
40120 ** The isHot parameter indicates that we are trying to rollback a journal
40121 ** that might be a hot journal.  Or, it could be that the journal is
40122 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40123 ** If the journal really is hot, reset the pager cache prior rolling
40124 ** back any content.  If the journal is merely persistent, no reset is
40125 ** needed.
40126 */
40127 static int pager_playback(Pager *pPager, int isHot){
40128   sqlite3_vfs *pVfs = pPager->pVfs;
40129   i64 szJ;                 /* Size of the journal file in bytes */
40130   u32 nRec;                /* Number of Records in the journal */
40131   u32 u;                   /* Unsigned loop counter */
40132   Pgno mxPg = 0;           /* Size of the original file in pages */
40133   int rc;                  /* Result code of a subroutine */
40134   int res = 1;             /* Value returned by sqlite3OsAccess() */
40135   char *zMaster = 0;       /* Name of master journal file if any */
40136   int needPagerReset;      /* True to reset page prior to first page rollback */
40137 
40138   /* Figure out how many records are in the journal.  Abort early if
40139   ** the journal is empty.
40140   */
40141   assert( isOpen(pPager->jfd) );
40142   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
40143   if( rc!=SQLITE_OK ){
40144     goto end_playback;
40145   }
40146 
40147   /* Read the master journal name from the journal, if it is present.
40148   ** If a master journal file name is specified, but the file is not
40149   ** present on disk, then the journal is not hot and does not need to be
40150   ** played back.
40151   **
40152   ** TODO: Technically the following is an error because it assumes that
40153   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
40154   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
40155   **  mxPathname is 512, which is the same as the minimum allowable value
40156   ** for pageSize.
40157   */
40158   zMaster = pPager->pTmpSpace;
40159   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40160   if( rc==SQLITE_OK && zMaster[0] ){
40161     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
40162   }
40163   zMaster = 0;
40164   if( rc!=SQLITE_OK || !res ){
40165     goto end_playback;
40166   }
40167   pPager->journalOff = 0;
40168   needPagerReset = isHot;
40169 
40170   /* This loop terminates either when a readJournalHdr() or
40171   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
40172   ** occurs.
40173   */
40174   while( 1 ){
40175     /* Read the next journal header from the journal file.  If there are
40176     ** not enough bytes left in the journal file for a complete header, or
40177     ** it is corrupted, then a process must have failed while writing it.
40178     ** This indicates nothing more needs to be rolled back.
40179     */
40180     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
40181     if( rc!=SQLITE_OK ){
40182       if( rc==SQLITE_DONE ){
40183         rc = SQLITE_OK;
40184       }
40185       goto end_playback;
40186     }
40187 
40188     /* If nRec is 0xffffffff, then this journal was created by a process
40189     ** working in no-sync mode. This means that the rest of the journal
40190     ** file consists of pages, there are no more journal headers. Compute
40191     ** the value of nRec based on this assumption.
40192     */
40193     if( nRec==0xffffffff ){
40194       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
40195       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
40196     }
40197 
40198     /* If nRec is 0 and this rollback is of a transaction created by this
40199     ** process and if this is the final header in the journal, then it means
40200     ** that this part of the journal was being filled but has not yet been
40201     ** synced to disk.  Compute the number of pages based on the remaining
40202     ** size of the file.
40203     **
40204     ** The third term of the test was added to fix ticket #2565.
40205     ** When rolling back a hot journal, nRec==0 always means that the next
40206     ** chunk of the journal contains zero pages to be rolled back.  But
40207     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
40208     ** the journal, it means that the journal might contain additional
40209     ** pages that need to be rolled back and that the number of pages
40210     ** should be computed based on the journal file size.
40211     */
40212     if( nRec==0 && !isHot &&
40213         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
40214       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
40215     }
40216 
40217     /* If this is the first header read from the journal, truncate the
40218     ** database file back to its original size.
40219     */
40220     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
40221       rc = pager_truncate(pPager, mxPg);
40222       if( rc!=SQLITE_OK ){
40223         goto end_playback;
40224       }
40225       pPager->dbSize = mxPg;
40226     }
40227 
40228     /* Copy original pages out of the journal and back into the
40229     ** database file and/or page cache.
40230     */
40231     for(u=0; u<nRec; u++){
40232       if( needPagerReset ){
40233         pager_reset(pPager);
40234         needPagerReset = 0;
40235       }
40236       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
40237       if( rc!=SQLITE_OK ){
40238         if( rc==SQLITE_DONE ){
40239           rc = SQLITE_OK;
40240           pPager->journalOff = szJ;
40241           break;
40242         }else if( rc==SQLITE_IOERR_SHORT_READ ){
40243           /* If the journal has been truncated, simply stop reading and
40244           ** processing the journal. This might happen if the journal was
40245           ** not completely written and synced prior to a crash.  In that
40246           ** case, the database should have never been written in the
40247           ** first place so it is OK to simply abandon the rollback. */
40248           rc = SQLITE_OK;
40249           goto end_playback;
40250         }else{
40251           /* If we are unable to rollback, quit and return the error
40252           ** code.  This will cause the pager to enter the error state
40253           ** so that no further harm will be done.  Perhaps the next
40254           ** process to come along will be able to rollback the database.
40255           */
40256           goto end_playback;
40257         }
40258       }
40259     }
40260   }
40261   /*NOTREACHED*/
40262   assert( 0 );
40263 
40264 end_playback:
40265   /* Following a rollback, the database file should be back in its original
40266   ** state prior to the start of the transaction, so invoke the
40267   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
40268   ** assertion that the transaction counter was modified.
40269   */
40270   assert(
40271     pPager->fd->pMethods==0 ||
40272     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
40273   );
40274 
40275   /* If this playback is happening automatically as a result of an IO or
40276   ** malloc error that occurred after the change-counter was updated but
40277   ** before the transaction was committed, then the change-counter
40278   ** modification may just have been reverted. If this happens in exclusive
40279   ** mode, then subsequent transactions performed by the connection will not
40280   ** update the change-counter at all. This may lead to cache inconsistency
40281   ** problems for other processes at some point in the future. So, just
40282   ** in case this has happened, clear the changeCountDone flag now.
40283   */
40284   pPager->changeCountDone = pPager->tempFile;
40285 
40286   if( rc==SQLITE_OK ){
40287     zMaster = pPager->pTmpSpace;
40288     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
40289     testcase( rc!=SQLITE_OK );
40290   }
40291   if( rc==SQLITE_OK
40292    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40293   ){
40294     rc = sqlite3PagerSync(pPager);
40295   }
40296   if( rc==SQLITE_OK ){
40297     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
40298     testcase( rc!=SQLITE_OK );
40299   }
40300   if( rc==SQLITE_OK && zMaster[0] && res ){
40301     /* If there was a master journal and this routine will return success,
40302     ** see if it is possible to delete the master journal.
40303     */
40304     rc = pager_delmaster(pPager, zMaster);
40305     testcase( rc!=SQLITE_OK );
40306   }
40307 
40308   /* The Pager.sectorSize variable may have been updated while rolling
40309   ** back a journal created by a process with a different sector size
40310   ** value. Reset it to the correct value for this process.
40311   */
40312   setSectorSize(pPager);
40313   return rc;
40314 }
40315 
40316 
40317 /*
40318 ** Read the content for page pPg out of the database file and into
40319 ** pPg->pData. A shared lock or greater must be held on the database
40320 ** file before this function is called.
40321 **
40322 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
40323 ** the value read from the database file.
40324 **
40325 ** If an IO error occurs, then the IO error is returned to the caller.
40326 ** Otherwise, SQLITE_OK is returned.
40327 */
40328 static int readDbPage(PgHdr *pPg){
40329   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
40330   Pgno pgno = pPg->pgno;       /* Page number to read */
40331   int rc = SQLITE_OK;          /* Return code */
40332   int isInWal = 0;             /* True if page is in log file */
40333   int pgsz = pPager->pageSize; /* Number of bytes to read */
40334 
40335   assert( pPager->eState>=PAGER_READER && !MEMDB );
40336   assert( isOpen(pPager->fd) );
40337 
40338   if( NEVER(!isOpen(pPager->fd)) ){
40339     assert( pPager->tempFile );
40340     memset(pPg->pData, 0, pPager->pageSize);
40341     return SQLITE_OK;
40342   }
40343 
40344   if( pagerUseWal(pPager) ){
40345     /* Try to pull the page from the write-ahead log. */
40346     rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
40347   }
40348   if( rc==SQLITE_OK && !isInWal ){
40349     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
40350     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
40351     if( rc==SQLITE_IOERR_SHORT_READ ){
40352       rc = SQLITE_OK;
40353     }
40354   }
40355 
40356   if( pgno==1 ){
40357     if( rc ){
40358       /* If the read is unsuccessful, set the dbFileVers[] to something
40359       ** that will never be a valid file version.  dbFileVers[] is a copy
40360       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
40361       ** zero or the size of the database in page. Bytes 32..35 and 35..39
40362       ** should be page numbers which are never 0xffffffff.  So filling
40363       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
40364       **
40365       ** For an encrypted database, the situation is more complex:  bytes
40366       ** 24..39 of the database are white noise.  But the probability of
40367       ** white noising equaling 16 bytes of 0xff is vanishingly small so
40368       ** we should still be ok.
40369       */
40370       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
40371     }else{
40372       u8 *dbFileVers = &((u8*)pPg->pData)[24];
40373       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
40374     }
40375   }
40376   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
40377 
40378   PAGER_INCR(sqlite3_pager_readdb_count);
40379   PAGER_INCR(pPager->nRead);
40380   IOTRACE(("PGIN %p %d\n", pPager, pgno));
40381   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
40382                PAGERID(pPager), pgno, pager_pagehash(pPg)));
40383 
40384   return rc;
40385 }
40386 
40387 /*
40388 ** Update the value of the change-counter at offsets 24 and 92 in
40389 ** the header and the sqlite version number at offset 96.
40390 **
40391 ** This is an unconditional update.  See also the pager_incr_changecounter()
40392 ** routine which only updates the change-counter if the update is actually
40393 ** needed, as determined by the pPager->changeCountDone state variable.
40394 */
40395 static void pager_write_changecounter(PgHdr *pPg){
40396   u32 change_counter;
40397 
40398   /* Increment the value just read and write it back to byte 24. */
40399   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
40400   put32bits(((char*)pPg->pData)+24, change_counter);
40401 
40402   /* Also store the SQLite version number in bytes 96..99 and in
40403   ** bytes 92..95 store the change counter for which the version number
40404   ** is valid. */
40405   put32bits(((char*)pPg->pData)+92, change_counter);
40406   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
40407 }
40408 
40409 #ifndef SQLITE_OMIT_WAL
40410 /*
40411 ** This function is invoked once for each page that has already been
40412 ** written into the log file when a WAL transaction is rolled back.
40413 ** Parameter iPg is the page number of said page. The pCtx argument
40414 ** is actually a pointer to the Pager structure.
40415 **
40416 ** If page iPg is present in the cache, and has no outstanding references,
40417 ** it is discarded. Otherwise, if there are one or more outstanding
40418 ** references, the page content is reloaded from the database. If the
40419 ** attempt to reload content from the database is required and fails,
40420 ** return an SQLite error code. Otherwise, SQLITE_OK.
40421 */
40422 static int pagerUndoCallback(void *pCtx, Pgno iPg){
40423   int rc = SQLITE_OK;
40424   Pager *pPager = (Pager *)pCtx;
40425   PgHdr *pPg;
40426 
40427   pPg = sqlite3PagerLookup(pPager, iPg);
40428   if( pPg ){
40429     if( sqlite3PcachePageRefcount(pPg)==1 ){
40430       sqlite3PcacheDrop(pPg);
40431     }else{
40432       rc = readDbPage(pPg);
40433       if( rc==SQLITE_OK ){
40434         pPager->xReiniter(pPg);
40435       }
40436       sqlite3PagerUnref(pPg);
40437     }
40438   }
40439 
40440   /* Normally, if a transaction is rolled back, any backup processes are
40441   ** updated as data is copied out of the rollback journal and into the
40442   ** database. This is not generally possible with a WAL database, as
40443   ** rollback involves simply truncating the log file. Therefore, if one
40444   ** or more frames have already been written to the log (and therefore
40445   ** also copied into the backup databases) as part of this transaction,
40446   ** the backups must be restarted.
40447   */
40448   sqlite3BackupRestart(pPager->pBackup);
40449 
40450   return rc;
40451 }
40452 
40453 /*
40454 ** This function is called to rollback a transaction on a WAL database.
40455 */
40456 static int pagerRollbackWal(Pager *pPager){
40457   int rc;                         /* Return Code */
40458   PgHdr *pList;                   /* List of dirty pages to revert */
40459 
40460   /* For all pages in the cache that are currently dirty or have already
40461   ** been written (but not committed) to the log file, do one of the
40462   ** following:
40463   **
40464   **   + Discard the cached page (if refcount==0), or
40465   **   + Reload page content from the database (if refcount>0).
40466   */
40467   pPager->dbSize = pPager->dbOrigSize;
40468   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
40469   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40470   while( pList && rc==SQLITE_OK ){
40471     PgHdr *pNext = pList->pDirty;
40472     rc = pagerUndoCallback((void *)pPager, pList->pgno);
40473     pList = pNext;
40474   }
40475 
40476   return rc;
40477 }
40478 
40479 /*
40480 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
40481 ** the contents of the list of pages headed by pList (connected by pDirty),
40482 ** this function notifies any active backup processes that the pages have
40483 ** changed.
40484 **
40485 ** The list of pages passed into this routine is always sorted by page number.
40486 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
40487 */
40488 static int pagerWalFrames(
40489   Pager *pPager,                  /* Pager object */
40490   PgHdr *pList,                   /* List of frames to log */
40491   Pgno nTruncate,                 /* Database size after this commit */
40492   int isCommit,                   /* True if this is a commit */
40493   int syncFlags                   /* Flags to pass to OsSync() (or 0) */
40494 ){
40495   int rc;                         /* Return code */
40496 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
40497   PgHdr *p;                       /* For looping over pages */
40498 #endif
40499 
40500   assert( pPager->pWal );
40501 #ifdef SQLITE_DEBUG
40502   /* Verify that the page list is in accending order */
40503   for(p=pList; p && p->pDirty; p=p->pDirty){
40504     assert( p->pgno < p->pDirty->pgno );
40505   }
40506 #endif
40507 
40508   if( isCommit ){
40509     /* If a WAL transaction is being committed, there is no point in writing
40510     ** any pages with page numbers greater than nTruncate into the WAL file.
40511     ** They will never be read by any client. So remove them from the pDirty
40512     ** list here. */
40513     PgHdr *p;
40514     PgHdr **ppNext = &pList;
40515     for(p=pList; (*ppNext = p); p=p->pDirty){
40516       if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
40517     }
40518     assert( pList );
40519   }
40520 
40521   if( pList->pgno==1 ) pager_write_changecounter(pList);
40522   rc = sqlite3WalFrames(pPager->pWal,
40523       pPager->pageSize, pList, nTruncate, isCommit, syncFlags
40524   );
40525   if( rc==SQLITE_OK && pPager->pBackup ){
40526     PgHdr *p;
40527     for(p=pList; p; p=p->pDirty){
40528       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
40529     }
40530   }
40531 
40532 #ifdef SQLITE_CHECK_PAGES
40533   pList = sqlite3PcacheDirtyList(pPager->pPCache);
40534   for(p=pList; p; p=p->pDirty){
40535     pager_set_pagehash(p);
40536   }
40537 #endif
40538 
40539   return rc;
40540 }
40541 
40542 /*
40543 ** Begin a read transaction on the WAL.
40544 **
40545 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
40546 ** makes a snapshot of the database at the current point in time and preserves
40547 ** that snapshot for use by the reader in spite of concurrently changes by
40548 ** other writers or checkpointers.
40549 */
40550 static int pagerBeginReadTransaction(Pager *pPager){
40551   int rc;                         /* Return code */
40552   int changed = 0;                /* True if cache must be reset */
40553 
40554   assert( pagerUseWal(pPager) );
40555   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
40556 
40557   /* sqlite3WalEndReadTransaction() was not called for the previous
40558   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
40559   ** are in locking_mode=NORMAL and EndRead() was previously called,
40560   ** the duplicate call is harmless.
40561   */
40562   sqlite3WalEndReadTransaction(pPager->pWal);
40563 
40564   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
40565   if( rc!=SQLITE_OK || changed ){
40566     pager_reset(pPager);
40567   }
40568 
40569   return rc;
40570 }
40571 #endif
40572 
40573 /*
40574 ** This function is called as part of the transition from PAGER_OPEN
40575 ** to PAGER_READER state to determine the size of the database file
40576 ** in pages (assuming the page size currently stored in Pager.pageSize).
40577 **
40578 ** If no error occurs, SQLITE_OK is returned and the size of the database
40579 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
40580 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
40581 */
40582 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
40583   Pgno nPage;                     /* Value to return via *pnPage */
40584 
40585   /* Query the WAL sub-system for the database size. The WalDbsize()
40586   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
40587   ** if the database size is not available. The database size is not
40588   ** available from the WAL sub-system if the log file is empty or
40589   ** contains no valid committed transactions.
40590   */
40591   assert( pPager->eState==PAGER_OPEN );
40592   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
40593   nPage = sqlite3WalDbsize(pPager->pWal);
40594 
40595   /* If the database size was not available from the WAL sub-system,
40596   ** determine it based on the size of the database file. If the size
40597   ** of the database file is not an integer multiple of the page-size,
40598   ** round down to the nearest page. Except, any file larger than 0
40599   ** bytes in size is considered to contain at least one page.
40600   */
40601   if( nPage==0 ){
40602     i64 n = 0;                    /* Size of db file in bytes */
40603     assert( isOpen(pPager->fd) || pPager->tempFile );
40604     if( isOpen(pPager->fd) ){
40605       int rc = sqlite3OsFileSize(pPager->fd, &n);
40606       if( rc!=SQLITE_OK ){
40607         return rc;
40608       }
40609     }
40610     nPage = (Pgno)(n / pPager->pageSize);
40611     if( nPage==0 && n>0 ){
40612       nPage = 1;
40613     }
40614   }
40615 
40616   /* If the current number of pages in the file is greater than the
40617   ** configured maximum pager number, increase the allowed limit so
40618   ** that the file can be read.
40619   */
40620   if( nPage>pPager->mxPgno ){
40621     pPager->mxPgno = (Pgno)nPage;
40622   }
40623 
40624   *pnPage = nPage;
40625   return SQLITE_OK;
40626 }
40627 
40628 #ifndef SQLITE_OMIT_WAL
40629 /*
40630 ** Check if the *-wal file that corresponds to the database opened by pPager
40631 ** exists if the database is not empy, or verify that the *-wal file does
40632 ** not exist (by deleting it) if the database file is empty.
40633 **
40634 ** If the database is not empty and the *-wal file exists, open the pager
40635 ** in WAL mode.  If the database is empty or if no *-wal file exists and
40636 ** if no error occurs, make sure Pager.journalMode is not set to
40637 ** PAGER_JOURNALMODE_WAL.
40638 **
40639 ** Return SQLITE_OK or an error code.
40640 **
40641 ** The caller must hold a SHARED lock on the database file to call this
40642 ** function. Because an EXCLUSIVE lock on the db file is required to delete
40643 ** a WAL on a none-empty database, this ensures there is no race condition
40644 ** between the xAccess() below and an xDelete() being executed by some
40645 ** other connection.
40646 */
40647 static int pagerOpenWalIfPresent(Pager *pPager){
40648   int rc = SQLITE_OK;
40649   assert( pPager->eState==PAGER_OPEN );
40650   assert( pPager->eLock>=SHARED_LOCK || pPager->noReadlock );
40651 
40652   if( !pPager->tempFile ){
40653     int isWal;                    /* True if WAL file exists */
40654     Pgno nPage;                   /* Size of the database file */
40655 
40656     rc = pagerPagecount(pPager, &nPage);
40657     if( rc ) return rc;
40658     if( nPage==0 ){
40659       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
40660       isWal = 0;
40661     }else{
40662       rc = sqlite3OsAccess(
40663           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
40664       );
40665     }
40666     if( rc==SQLITE_OK ){
40667       if( isWal ){
40668         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
40669         rc = sqlite3PagerOpenWal(pPager, 0);
40670       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
40671         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
40672       }
40673     }
40674   }
40675   return rc;
40676 }
40677 #endif
40678 
40679 /*
40680 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
40681 ** the entire master journal file. The case pSavepoint==NULL occurs when
40682 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
40683 ** savepoint.
40684 **
40685 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
40686 ** being rolled back), then the rollback consists of up to three stages,
40687 ** performed in the order specified:
40688 **
40689 **   * Pages are played back from the main journal starting at byte
40690 **     offset PagerSavepoint.iOffset and continuing to
40691 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
40692 **     file if PagerSavepoint.iHdrOffset is zero.
40693 **
40694 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
40695 **     back starting from the journal header immediately following
40696 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
40697 **
40698 **   * Pages are then played back from the sub-journal file, starting
40699 **     with the PagerSavepoint.iSubRec and continuing to the end of
40700 **     the journal file.
40701 **
40702 ** Throughout the rollback process, each time a page is rolled back, the
40703 ** corresponding bit is set in a bitvec structure (variable pDone in the
40704 ** implementation below). This is used to ensure that a page is only
40705 ** rolled back the first time it is encountered in either journal.
40706 **
40707 ** If pSavepoint is NULL, then pages are only played back from the main
40708 ** journal file. There is no need for a bitvec in this case.
40709 **
40710 ** In either case, before playback commences the Pager.dbSize variable
40711 ** is reset to the value that it held at the start of the savepoint
40712 ** (or transaction). No page with a page-number greater than this value
40713 ** is played back. If one is encountered it is simply skipped.
40714 */
40715 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
40716   i64 szJ;                 /* Effective size of the main journal */
40717   i64 iHdrOff;             /* End of first segment of main-journal records */
40718   int rc = SQLITE_OK;      /* Return code */
40719   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
40720 
40721   assert( pPager->eState!=PAGER_ERROR );
40722   assert( pPager->eState>=PAGER_WRITER_LOCKED );
40723 
40724   /* Allocate a bitvec to use to store the set of pages rolled back */
40725   if( pSavepoint ){
40726     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
40727     if( !pDone ){
40728       return SQLITE_NOMEM;
40729     }
40730   }
40731 
40732   /* Set the database size back to the value it was before the savepoint
40733   ** being reverted was opened.
40734   */
40735   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
40736   pPager->changeCountDone = pPager->tempFile;
40737 
40738   if( !pSavepoint && pagerUseWal(pPager) ){
40739     return pagerRollbackWal(pPager);
40740   }
40741 
40742   /* Use pPager->journalOff as the effective size of the main rollback
40743   ** journal.  The actual file might be larger than this in
40744   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
40745   ** past pPager->journalOff is off-limits to us.
40746   */
40747   szJ = pPager->journalOff;
40748   assert( pagerUseWal(pPager)==0 || szJ==0 );
40749 
40750   /* Begin by rolling back records from the main journal starting at
40751   ** PagerSavepoint.iOffset and continuing to the next journal header.
40752   ** There might be records in the main journal that have a page number
40753   ** greater than the current database size (pPager->dbSize) but those
40754   ** will be skipped automatically.  Pages are added to pDone as they
40755   ** are played back.
40756   */
40757   if( pSavepoint && !pagerUseWal(pPager) ){
40758     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
40759     pPager->journalOff = pSavepoint->iOffset;
40760     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
40761       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40762     }
40763     assert( rc!=SQLITE_DONE );
40764   }else{
40765     pPager->journalOff = 0;
40766   }
40767 
40768   /* Continue rolling back records out of the main journal starting at
40769   ** the first journal header seen and continuing until the effective end
40770   ** of the main journal file.  Continue to skip out-of-range pages and
40771   ** continue adding pages rolled back to pDone.
40772   */
40773   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
40774     u32 ii;            /* Loop counter */
40775     u32 nJRec = 0;     /* Number of Journal Records */
40776     u32 dummy;
40777     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
40778     assert( rc!=SQLITE_DONE );
40779 
40780     /*
40781     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
40782     ** test is related to ticket #2565.  See the discussion in the
40783     ** pager_playback() function for additional information.
40784     */
40785     if( nJRec==0
40786      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
40787     ){
40788       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
40789     }
40790     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
40791       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
40792     }
40793     assert( rc!=SQLITE_DONE );
40794   }
40795   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
40796 
40797   /* Finally,  rollback pages from the sub-journal.  Page that were
40798   ** previously rolled back out of the main journal (and are hence in pDone)
40799   ** will be skipped.  Out-of-range pages are also skipped.
40800   */
40801   if( pSavepoint ){
40802     u32 ii;            /* Loop counter */
40803     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
40804 
40805     if( pagerUseWal(pPager) ){
40806       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
40807     }
40808     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
40809       assert( offset==ii*(4+pPager->pageSize) );
40810       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
40811     }
40812     assert( rc!=SQLITE_DONE );
40813   }
40814 
40815   sqlite3BitvecDestroy(pDone);
40816   if( rc==SQLITE_OK ){
40817     pPager->journalOff = szJ;
40818   }
40819 
40820   return rc;
40821 }
40822 
40823 /*
40824 ** Change the maximum number of in-memory pages that are allowed.
40825 */
40826 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
40827   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
40828 }
40829 
40830 /*
40831 ** Adjust the robustness of the database to damage due to OS crashes
40832 ** or power failures by changing the number of syncs()s when writing
40833 ** the rollback journal.  There are three levels:
40834 **
40835 **    OFF       sqlite3OsSync() is never called.  This is the default
40836 **              for temporary and transient files.
40837 **
40838 **    NORMAL    The journal is synced once before writes begin on the
40839 **              database.  This is normally adequate protection, but
40840 **              it is theoretically possible, though very unlikely,
40841 **              that an inopertune power failure could leave the journal
40842 **              in a state which would cause damage to the database
40843 **              when it is rolled back.
40844 **
40845 **    FULL      The journal is synced twice before writes begin on the
40846 **              database (with some additional information - the nRec field
40847 **              of the journal header - being written in between the two
40848 **              syncs).  If we assume that writing a
40849 **              single disk sector is atomic, then this mode provides
40850 **              assurance that the journal will not be corrupted to the
40851 **              point of causing damage to the database during rollback.
40852 **
40853 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
40854 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
40855 ** prior to the start of checkpoint and that the database file is synced
40856 ** at the conclusion of the checkpoint if the entire content of the WAL
40857 ** was written back into the database.  But no sync operations occur for
40858 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
40859 ** file is synced following each commit operation, in addition to the
40860 ** syncs associated with NORMAL.
40861 **
40862 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
40863 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
40864 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
40865 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
40866 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
40867 ** synchronous=FULL versus synchronous=NORMAL setting determines when
40868 ** the xSync primitive is called and is relevant to all platforms.
40869 **
40870 ** Numeric values associated with these states are OFF==1, NORMAL=2,
40871 ** and FULL=3.
40872 */
40873 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40874 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
40875   Pager *pPager,        /* The pager to set safety level for */
40876   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
40877   int bFullFsync,       /* PRAGMA fullfsync */
40878   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
40879 ){
40880   assert( level>=1 && level<=3 );
40881   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
40882   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
40883   if( pPager->noSync ){
40884     pPager->syncFlags = 0;
40885     pPager->ckptSyncFlags = 0;
40886   }else if( bFullFsync ){
40887     pPager->syncFlags = SQLITE_SYNC_FULL;
40888     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40889   }else if( bCkptFullFsync ){
40890     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40891     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
40892   }else{
40893     pPager->syncFlags = SQLITE_SYNC_NORMAL;
40894     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
40895   }
40896 }
40897 #endif
40898 
40899 /*
40900 ** The following global variable is incremented whenever the library
40901 ** attempts to open a temporary file.  This information is used for
40902 ** testing and analysis only.
40903 */
40904 #ifdef SQLITE_TEST
40905 SQLITE_API int sqlite3_opentemp_count = 0;
40906 #endif
40907 
40908 /*
40909 ** Open a temporary file.
40910 **
40911 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
40912 ** or some other error code if we fail. The OS will automatically
40913 ** delete the temporary file when it is closed.
40914 **
40915 ** The flags passed to the VFS layer xOpen() call are those specified
40916 ** by parameter vfsFlags ORed with the following:
40917 **
40918 **     SQLITE_OPEN_READWRITE
40919 **     SQLITE_OPEN_CREATE
40920 **     SQLITE_OPEN_EXCLUSIVE
40921 **     SQLITE_OPEN_DELETEONCLOSE
40922 */
40923 static int pagerOpentemp(
40924   Pager *pPager,        /* The pager object */
40925   sqlite3_file *pFile,  /* Write the file descriptor here */
40926   int vfsFlags          /* Flags passed through to the VFS */
40927 ){
40928   int rc;               /* Return code */
40929 
40930 #ifdef SQLITE_TEST
40931   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
40932 #endif
40933 
40934   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
40935             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
40936   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
40937   assert( rc!=SQLITE_OK || isOpen(pFile) );
40938   return rc;
40939 }
40940 
40941 /*
40942 ** Set the busy handler function.
40943 **
40944 ** The pager invokes the busy-handler if sqlite3OsLock() returns
40945 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
40946 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
40947 ** lock. It does *not* invoke the busy handler when upgrading from
40948 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
40949 ** (which occurs during hot-journal rollback). Summary:
40950 **
40951 **   Transition                        | Invokes xBusyHandler
40952 **   --------------------------------------------------------
40953 **   NO_LOCK       -> SHARED_LOCK      | Yes
40954 **   SHARED_LOCK   -> RESERVED_LOCK    | No
40955 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
40956 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
40957 **
40958 ** If the busy-handler callback returns non-zero, the lock is
40959 ** retried. If it returns zero, then the SQLITE_BUSY error is
40960 ** returned to the caller of the pager API function.
40961 */
40962 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
40963   Pager *pPager,                       /* Pager object */
40964   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
40965   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
40966 ){
40967   pPager->xBusyHandler = xBusyHandler;
40968   pPager->pBusyHandlerArg = pBusyHandlerArg;
40969 }
40970 
40971 /*
40972 ** Change the page size used by the Pager object. The new page size
40973 ** is passed in *pPageSize.
40974 **
40975 ** If the pager is in the error state when this function is called, it
40976 ** is a no-op. The value returned is the error state error code (i.e.
40977 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
40978 **
40979 ** Otherwise, if all of the following are true:
40980 **
40981 **   * the new page size (value of *pPageSize) is valid (a power
40982 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
40983 **
40984 **   * there are no outstanding page references, and
40985 **
40986 **   * the database is either not an in-memory database or it is
40987 **     an in-memory database that currently consists of zero pages.
40988 **
40989 ** then the pager object page size is set to *pPageSize.
40990 **
40991 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
40992 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
40993 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
40994 ** In all other cases, SQLITE_OK is returned.
40995 **
40996 ** If the page size is not changed, either because one of the enumerated
40997 ** conditions above is not true, the pager was in error state when this
40998 ** function was called, or because the memory allocation attempt failed,
40999 ** then *pPageSize is set to the old, retained page size before returning.
41000 */
41001 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41002   int rc = SQLITE_OK;
41003 
41004   /* It is not possible to do a full assert_pager_state() here, as this
41005   ** function may be called from within PagerOpen(), before the state
41006   ** of the Pager object is internally consistent.
41007   **
41008   ** At one point this function returned an error if the pager was in
41009   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41010   ** there is at least one outstanding page reference, this function
41011   ** is a no-op for that case anyhow.
41012   */
41013 
41014   u32 pageSize = *pPageSize;
41015   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41016   if( (pPager->memDb==0 || pPager->dbSize==0)
41017    && sqlite3PcacheRefCount(pPager->pPCache)==0
41018    && pageSize && pageSize!=(u32)pPager->pageSize
41019   ){
41020     char *pNew = NULL;             /* New temp space */
41021     i64 nByte = 0;
41022 
41023     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41024       rc = sqlite3OsFileSize(pPager->fd, &nByte);
41025     }
41026     if( rc==SQLITE_OK ){
41027       pNew = (char *)sqlite3PageMalloc(pageSize);
41028       if( !pNew ) rc = SQLITE_NOMEM;
41029     }
41030 
41031     if( rc==SQLITE_OK ){
41032       pager_reset(pPager);
41033       pPager->dbSize = (Pgno)(nByte/pageSize);
41034       pPager->pageSize = pageSize;
41035       sqlite3PageFree(pPager->pTmpSpace);
41036       pPager->pTmpSpace = pNew;
41037       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41038     }
41039   }
41040 
41041   *pPageSize = pPager->pageSize;
41042   if( rc==SQLITE_OK ){
41043     if( nReserve<0 ) nReserve = pPager->nReserve;
41044     assert( nReserve>=0 && nReserve<1000 );
41045     pPager->nReserve = (i16)nReserve;
41046     pagerReportSize(pPager);
41047   }
41048   return rc;
41049 }
41050 
41051 /*
41052 ** Return a pointer to the "temporary page" buffer held internally
41053 ** by the pager.  This is a buffer that is big enough to hold the
41054 ** entire content of a database page.  This buffer is used internally
41055 ** during rollback and will be overwritten whenever a rollback
41056 ** occurs.  But other modules are free to use it too, as long as
41057 ** no rollbacks are happening.
41058 */
41059 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41060   return pPager->pTmpSpace;
41061 }
41062 
41063 /*
41064 ** Attempt to set the maximum database page count if mxPage is positive.
41065 ** Make no changes if mxPage is zero or negative.  And never reduce the
41066 ** maximum page count below the current size of the database.
41067 **
41068 ** Regardless of mxPage, return the current maximum page count.
41069 */
41070 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
41071   if( mxPage>0 ){
41072     pPager->mxPgno = mxPage;
41073   }
41074   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
41075   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
41076   return pPager->mxPgno;
41077 }
41078 
41079 /*
41080 ** The following set of routines are used to disable the simulated
41081 ** I/O error mechanism.  These routines are used to avoid simulated
41082 ** errors in places where we do not care about errors.
41083 **
41084 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
41085 ** and generate no code.
41086 */
41087 #ifdef SQLITE_TEST
41088 SQLITE_API extern int sqlite3_io_error_pending;
41089 SQLITE_API extern int sqlite3_io_error_hit;
41090 static int saved_cnt;
41091 void disable_simulated_io_errors(void){
41092   saved_cnt = sqlite3_io_error_pending;
41093   sqlite3_io_error_pending = -1;
41094 }
41095 void enable_simulated_io_errors(void){
41096   sqlite3_io_error_pending = saved_cnt;
41097 }
41098 #else
41099 # define disable_simulated_io_errors()
41100 # define enable_simulated_io_errors()
41101 #endif
41102 
41103 /*
41104 ** Read the first N bytes from the beginning of the file into memory
41105 ** that pDest points to.
41106 **
41107 ** If the pager was opened on a transient file (zFilename==""), or
41108 ** opened on a file less than N bytes in size, the output buffer is
41109 ** zeroed and SQLITE_OK returned. The rationale for this is that this
41110 ** function is used to read database headers, and a new transient or
41111 ** zero sized database has a header than consists entirely of zeroes.
41112 **
41113 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
41114 ** the error code is returned to the caller and the contents of the
41115 ** output buffer undefined.
41116 */
41117 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
41118   int rc = SQLITE_OK;
41119   memset(pDest, 0, N);
41120   assert( isOpen(pPager->fd) || pPager->tempFile );
41121 
41122   /* This routine is only called by btree immediately after creating
41123   ** the Pager object.  There has not been an opportunity to transition
41124   ** to WAL mode yet.
41125   */
41126   assert( !pagerUseWal(pPager) );
41127 
41128   if( isOpen(pPager->fd) ){
41129     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
41130     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
41131     if( rc==SQLITE_IOERR_SHORT_READ ){
41132       rc = SQLITE_OK;
41133     }
41134   }
41135   return rc;
41136 }
41137 
41138 /*
41139 ** This function may only be called when a read-transaction is open on
41140 ** the pager. It returns the total number of pages in the database.
41141 **
41142 ** However, if the file is between 1 and <page-size> bytes in size, then
41143 ** this is considered a 1 page file.
41144 */
41145 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
41146   assert( pPager->eState>=PAGER_READER );
41147   assert( pPager->eState!=PAGER_WRITER_FINISHED );
41148   *pnPage = (int)pPager->dbSize;
41149 }
41150 
41151 
41152 /*
41153 ** Try to obtain a lock of type locktype on the database file. If
41154 ** a similar or greater lock is already held, this function is a no-op
41155 ** (returning SQLITE_OK immediately).
41156 **
41157 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
41158 ** the busy callback if the lock is currently not available. Repeat
41159 ** until the busy callback returns false or until the attempt to
41160 ** obtain the lock succeeds.
41161 **
41162 ** Return SQLITE_OK on success and an error code if we cannot obtain
41163 ** the lock. If the lock is obtained successfully, set the Pager.state
41164 ** variable to locktype before returning.
41165 */
41166 static int pager_wait_on_lock(Pager *pPager, int locktype){
41167   int rc;                              /* Return code */
41168 
41169   /* Check that this is either a no-op (because the requested lock is
41170   ** already held, or one of the transistions that the busy-handler
41171   ** may be invoked during, according to the comment above
41172   ** sqlite3PagerSetBusyhandler().
41173   */
41174   assert( (pPager->eLock>=locktype)
41175        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
41176        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
41177   );
41178 
41179   do {
41180     rc = pagerLockDb(pPager, locktype);
41181   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
41182   return rc;
41183 }
41184 
41185 /*
41186 ** Function assertTruncateConstraint(pPager) checks that one of the
41187 ** following is true for all dirty pages currently in the page-cache:
41188 **
41189 **   a) The page number is less than or equal to the size of the
41190 **      current database image, in pages, OR
41191 **
41192 **   b) if the page content were written at this time, it would not
41193 **      be necessary to write the current content out to the sub-journal
41194 **      (as determined by function subjRequiresPage()).
41195 **
41196 ** If the condition asserted by this function were not true, and the
41197 ** dirty page were to be discarded from the cache via the pagerStress()
41198 ** routine, pagerStress() would not write the current page content to
41199 ** the database file. If a savepoint transaction were rolled back after
41200 ** this happened, the correct behaviour would be to restore the current
41201 ** content of the page. However, since this content is not present in either
41202 ** the database file or the portion of the rollback journal and
41203 ** sub-journal rolled back the content could not be restored and the
41204 ** database image would become corrupt. It is therefore fortunate that
41205 ** this circumstance cannot arise.
41206 */
41207 #if defined(SQLITE_DEBUG)
41208 static void assertTruncateConstraintCb(PgHdr *pPg){
41209   assert( pPg->flags&PGHDR_DIRTY );
41210   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
41211 }
41212 static void assertTruncateConstraint(Pager *pPager){
41213   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
41214 }
41215 #else
41216 # define assertTruncateConstraint(pPager)
41217 #endif
41218 
41219 /*
41220 ** Truncate the in-memory database file image to nPage pages. This
41221 ** function does not actually modify the database file on disk. It
41222 ** just sets the internal state of the pager object so that the
41223 ** truncation will be done when the current transaction is committed.
41224 */
41225 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
41226   assert( pPager->dbSize>=nPage );
41227   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
41228   pPager->dbSize = nPage;
41229   assertTruncateConstraint(pPager);
41230 }
41231 
41232 
41233 /*
41234 ** This function is called before attempting a hot-journal rollback. It
41235 ** syncs the journal file to disk, then sets pPager->journalHdr to the
41236 ** size of the journal file so that the pager_playback() routine knows
41237 ** that the entire journal file has been synced.
41238 **
41239 ** Syncing a hot-journal to disk before attempting to roll it back ensures
41240 ** that if a power-failure occurs during the rollback, the process that
41241 ** attempts rollback following system recovery sees the same journal
41242 ** content as this process.
41243 **
41244 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
41245 ** an SQLite error code.
41246 */
41247 static int pagerSyncHotJournal(Pager *pPager){
41248   int rc = SQLITE_OK;
41249   if( !pPager->noSync ){
41250     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
41251   }
41252   if( rc==SQLITE_OK ){
41253     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
41254   }
41255   return rc;
41256 }
41257 
41258 /*
41259 ** Shutdown the page cache.  Free all memory and close all files.
41260 **
41261 ** If a transaction was in progress when this routine is called, that
41262 ** transaction is rolled back.  All outstanding pages are invalidated
41263 ** and their memory is freed.  Any attempt to use a page associated
41264 ** with this page cache after this function returns will likely
41265 ** result in a coredump.
41266 **
41267 ** This function always succeeds. If a transaction is active an attempt
41268 ** is made to roll it back. If an error occurs during the rollback
41269 ** a hot journal may be left in the filesystem but no error is returned
41270 ** to the caller.
41271 */
41272 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
41273   u8 *pTmp = (u8 *)pPager->pTmpSpace;
41274 
41275   assert( assert_pager_state(pPager) );
41276   disable_simulated_io_errors();
41277   sqlite3BeginBenignMalloc();
41278   /* pPager->errCode = 0; */
41279   pPager->exclusiveMode = 0;
41280 #ifndef SQLITE_OMIT_WAL
41281   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
41282   pPager->pWal = 0;
41283 #endif
41284   pager_reset(pPager);
41285   if( MEMDB ){
41286     pager_unlock(pPager);
41287   }else{
41288     /* If it is open, sync the journal file before calling UnlockAndRollback.
41289     ** If this is not done, then an unsynced portion of the open journal
41290     ** file may be played back into the database. If a power failure occurs
41291     ** while this is happening, the database could become corrupt.
41292     **
41293     ** If an error occurs while trying to sync the journal, shift the pager
41294     ** into the ERROR state. This causes UnlockAndRollback to unlock the
41295     ** database and close the journal file without attempting to roll it
41296     ** back or finalize it. The next database user will have to do hot-journal
41297     ** rollback before accessing the database file.
41298     */
41299     if( isOpen(pPager->jfd) ){
41300       pager_error(pPager, pagerSyncHotJournal(pPager));
41301     }
41302     pagerUnlockAndRollback(pPager);
41303   }
41304   sqlite3EndBenignMalloc();
41305   enable_simulated_io_errors();
41306   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
41307   IOTRACE(("CLOSE %p\n", pPager))
41308   sqlite3OsClose(pPager->jfd);
41309   sqlite3OsClose(pPager->fd);
41310   sqlite3PageFree(pTmp);
41311   sqlite3PcacheClose(pPager->pPCache);
41312 
41313 #ifdef SQLITE_HAS_CODEC
41314   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
41315 #endif
41316 
41317   assert( !pPager->aSavepoint && !pPager->pInJournal );
41318   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
41319 
41320   sqlite3_free(pPager);
41321   return SQLITE_OK;
41322 }
41323 
41324 #if !defined(NDEBUG) || defined(SQLITE_TEST)
41325 /*
41326 ** Return the page number for page pPg.
41327 */
41328 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
41329   return pPg->pgno;
41330 }
41331 #endif
41332 
41333 /*
41334 ** Increment the reference count for page pPg.
41335 */
41336 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
41337   sqlite3PcacheRef(pPg);
41338 }
41339 
41340 /*
41341 ** Sync the journal. In other words, make sure all the pages that have
41342 ** been written to the journal have actually reached the surface of the
41343 ** disk and can be restored in the event of a hot-journal rollback.
41344 **
41345 ** If the Pager.noSync flag is set, then this function is a no-op.
41346 ** Otherwise, the actions required depend on the journal-mode and the
41347 ** device characteristics of the the file-system, as follows:
41348 **
41349 **   * If the journal file is an in-memory journal file, no action need
41350 **     be taken.
41351 **
41352 **   * Otherwise, if the device does not support the SAFE_APPEND property,
41353 **     then the nRec field of the most recently written journal header
41354 **     is updated to contain the number of journal records that have
41355 **     been written following it. If the pager is operating in full-sync
41356 **     mode, then the journal file is synced before this field is updated.
41357 **
41358 **   * If the device does not support the SEQUENTIAL property, then
41359 **     journal file is synced.
41360 **
41361 ** Or, in pseudo-code:
41362 **
41363 **   if( NOT <in-memory journal> ){
41364 **     if( NOT SAFE_APPEND ){
41365 **       if( <full-sync mode> ) xSync(<journal file>);
41366 **       <update nRec field>
41367 **     }
41368 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
41369 **   }
41370 **
41371 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
41372 ** page currently held in memory before returning SQLITE_OK. If an IO
41373 ** error is encountered, then the IO error code is returned to the caller.
41374 */
41375 static int syncJournal(Pager *pPager, int newHdr){
41376   int rc;                         /* Return code */
41377 
41378   assert( pPager->eState==PAGER_WRITER_CACHEMOD
41379        || pPager->eState==PAGER_WRITER_DBMOD
41380   );
41381   assert( assert_pager_state(pPager) );
41382   assert( !pagerUseWal(pPager) );
41383 
41384   rc = sqlite3PagerExclusiveLock(pPager);
41385   if( rc!=SQLITE_OK ) return rc;
41386 
41387   if( !pPager->noSync ){
41388     assert( !pPager->tempFile );
41389     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
41390       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41391       assert( isOpen(pPager->jfd) );
41392 
41393       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41394         /* This block deals with an obscure problem. If the last connection
41395         ** that wrote to this database was operating in persistent-journal
41396         ** mode, then the journal file may at this point actually be larger
41397         ** than Pager.journalOff bytes. If the next thing in the journal
41398         ** file happens to be a journal-header (written as part of the
41399         ** previous connection's transaction), and a crash or power-failure
41400         ** occurs after nRec is updated but before this connection writes
41401         ** anything else to the journal file (or commits/rolls back its
41402         ** transaction), then SQLite may become confused when doing the
41403         ** hot-journal rollback following recovery. It may roll back all
41404         ** of this connections data, then proceed to rolling back the old,
41405         ** out-of-date data that follows it. Database corruption.
41406         **
41407         ** To work around this, if the journal file does appear to contain
41408         ** a valid header following Pager.journalOff, then write a 0x00
41409         ** byte to the start of it to prevent it from being recognized.
41410         **
41411         ** Variable iNextHdrOffset is set to the offset at which this
41412         ** problematic header will occur, if it exists. aMagic is used
41413         ** as a temporary buffer to inspect the first couple of bytes of
41414         ** the potential journal header.
41415         */
41416         i64 iNextHdrOffset;
41417         u8 aMagic[8];
41418         u8 zHeader[sizeof(aJournalMagic)+4];
41419 
41420         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
41421         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
41422 
41423         iNextHdrOffset = journalHdrOffset(pPager);
41424         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
41425         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
41426           static const u8 zerobyte = 0;
41427           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
41428         }
41429         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
41430           return rc;
41431         }
41432 
41433         /* Write the nRec value into the journal file header. If in
41434         ** full-synchronous mode, sync the journal first. This ensures that
41435         ** all data has really hit the disk before nRec is updated to mark
41436         ** it as a candidate for rollback.
41437         **
41438         ** This is not required if the persistent media supports the
41439         ** SAFE_APPEND property. Because in this case it is not possible
41440         ** for garbage data to be appended to the file, the nRec field
41441         ** is populated with 0xFFFFFFFF when the journal header is written
41442         ** and never needs to be updated.
41443         */
41444         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41445           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41446           IOTRACE(("JSYNC %p\n", pPager))
41447           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
41448           if( rc!=SQLITE_OK ) return rc;
41449         }
41450         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
41451         rc = sqlite3OsWrite(
41452             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
41453         );
41454         if( rc!=SQLITE_OK ) return rc;
41455       }
41456       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
41457         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
41458         IOTRACE(("JSYNC %p\n", pPager))
41459         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
41460           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
41461         );
41462         if( rc!=SQLITE_OK ) return rc;
41463       }
41464 
41465       pPager->journalHdr = pPager->journalOff;
41466       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
41467         pPager->nRec = 0;
41468         rc = writeJournalHdr(pPager);
41469         if( rc!=SQLITE_OK ) return rc;
41470       }
41471     }else{
41472       pPager->journalHdr = pPager->journalOff;
41473     }
41474   }
41475 
41476   /* Unless the pager is in noSync mode, the journal file was just
41477   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
41478   ** all pages.
41479   */
41480   sqlite3PcacheClearSyncFlags(pPager->pPCache);
41481   pPager->eState = PAGER_WRITER_DBMOD;
41482   assert( assert_pager_state(pPager) );
41483   return SQLITE_OK;
41484 }
41485 
41486 /*
41487 ** The argument is the first in a linked list of dirty pages connected
41488 ** by the PgHdr.pDirty pointer. This function writes each one of the
41489 ** in-memory pages in the list to the database file. The argument may
41490 ** be NULL, representing an empty list. In this case this function is
41491 ** a no-op.
41492 **
41493 ** The pager must hold at least a RESERVED lock when this function
41494 ** is called. Before writing anything to the database file, this lock
41495 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
41496 ** SQLITE_BUSY is returned and no data is written to the database file.
41497 **
41498 ** If the pager is a temp-file pager and the actual file-system file
41499 ** is not yet open, it is created and opened before any data is
41500 ** written out.
41501 **
41502 ** Once the lock has been upgraded and, if necessary, the file opened,
41503 ** the pages are written out to the database file in list order. Writing
41504 ** a page is skipped if it meets either of the following criteria:
41505 **
41506 **   * The page number is greater than Pager.dbSize, or
41507 **   * The PGHDR_DONT_WRITE flag is set on the page.
41508 **
41509 ** If writing out a page causes the database file to grow, Pager.dbFileSize
41510 ** is updated accordingly. If page 1 is written out, then the value cached
41511 ** in Pager.dbFileVers[] is updated to match the new value stored in
41512 ** the database file.
41513 **
41514 ** If everything is successful, SQLITE_OK is returned. If an IO error
41515 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
41516 ** be obtained, SQLITE_BUSY is returned.
41517 */
41518 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
41519   int rc = SQLITE_OK;                  /* Return code */
41520 
41521   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
41522   assert( !pagerUseWal(pPager) );
41523   assert( pPager->eState==PAGER_WRITER_DBMOD );
41524   assert( pPager->eLock==EXCLUSIVE_LOCK );
41525 
41526   /* If the file is a temp-file has not yet been opened, open it now. It
41527   ** is not possible for rc to be other than SQLITE_OK if this branch
41528   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
41529   */
41530   if( !isOpen(pPager->fd) ){
41531     assert( pPager->tempFile && rc==SQLITE_OK );
41532     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
41533   }
41534 
41535   /* Before the first write, give the VFS a hint of what the final
41536   ** file size will be.
41537   */
41538   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
41539   if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
41540     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
41541     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
41542     pPager->dbHintSize = pPager->dbSize;
41543   }
41544 
41545   while( rc==SQLITE_OK && pList ){
41546     Pgno pgno = pList->pgno;
41547 
41548     /* If there are dirty pages in the page cache with page numbers greater
41549     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
41550     ** make the file smaller (presumably by auto-vacuum code). Do not write
41551     ** any such pages to the file.
41552     **
41553     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
41554     ** set (set by sqlite3PagerDontWrite()).
41555     */
41556     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
41557       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
41558       char *pData;                                   /* Data to write */
41559 
41560       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
41561       if( pList->pgno==1 ) pager_write_changecounter(pList);
41562 
41563       /* Encode the database */
41564       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
41565 
41566       /* Write out the page data. */
41567       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
41568 
41569       /* If page 1 was just written, update Pager.dbFileVers to match
41570       ** the value now stored in the database file. If writing this
41571       ** page caused the database file to grow, update dbFileSize.
41572       */
41573       if( pgno==1 ){
41574         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
41575       }
41576       if( pgno>pPager->dbFileSize ){
41577         pPager->dbFileSize = pgno;
41578       }
41579 
41580       /* Update any backup objects copying the contents of this pager. */
41581       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
41582 
41583       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
41584                    PAGERID(pPager), pgno, pager_pagehash(pList)));
41585       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
41586       PAGER_INCR(sqlite3_pager_writedb_count);
41587       PAGER_INCR(pPager->nWrite);
41588     }else{
41589       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
41590     }
41591     pager_set_pagehash(pList);
41592     pList = pList->pDirty;
41593   }
41594 
41595   return rc;
41596 }
41597 
41598 /*
41599 ** Ensure that the sub-journal file is open. If it is already open, this
41600 ** function is a no-op.
41601 **
41602 ** SQLITE_OK is returned if everything goes according to plan. An
41603 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
41604 ** fails.
41605 */
41606 static int openSubJournal(Pager *pPager){
41607   int rc = SQLITE_OK;
41608   if( !isOpen(pPager->sjfd) ){
41609     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
41610       sqlite3MemJournalOpen(pPager->sjfd);
41611     }else{
41612       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
41613     }
41614   }
41615   return rc;
41616 }
41617 
41618 /*
41619 ** Append a record of the current state of page pPg to the sub-journal.
41620 ** It is the callers responsibility to use subjRequiresPage() to check
41621 ** that it is really required before calling this function.
41622 **
41623 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
41624 ** for all open savepoints before returning.
41625 **
41626 ** This function returns SQLITE_OK if everything is successful, an IO
41627 ** error code if the attempt to write to the sub-journal fails, or
41628 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
41629 ** bitvec.
41630 */
41631 static int subjournalPage(PgHdr *pPg){
41632   int rc = SQLITE_OK;
41633   Pager *pPager = pPg->pPager;
41634   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
41635 
41636     /* Open the sub-journal, if it has not already been opened */
41637     assert( pPager->useJournal );
41638     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
41639     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
41640     assert( pagerUseWal(pPager)
41641          || pageInJournal(pPg)
41642          || pPg->pgno>pPager->dbOrigSize
41643     );
41644     rc = openSubJournal(pPager);
41645 
41646     /* If the sub-journal was opened successfully (or was already open),
41647     ** write the journal record into the file.  */
41648     if( rc==SQLITE_OK ){
41649       void *pData = pPg->pData;
41650       i64 offset = pPager->nSubRec*(4+pPager->pageSize);
41651       char *pData2;
41652 
41653       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
41654       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
41655       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
41656       if( rc==SQLITE_OK ){
41657         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
41658       }
41659     }
41660   }
41661   if( rc==SQLITE_OK ){
41662     pPager->nSubRec++;
41663     assert( pPager->nSavepoint>0 );
41664     rc = addToSavepointBitvecs(pPager, pPg->pgno);
41665   }
41666   return rc;
41667 }
41668 
41669 /*
41670 ** This function is called by the pcache layer when it has reached some
41671 ** soft memory limit. The first argument is a pointer to a Pager object
41672 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
41673 ** database). The second argument is a reference to a page that is
41674 ** currently dirty but has no outstanding references. The page
41675 ** is always associated with the Pager object passed as the first
41676 ** argument.
41677 **
41678 ** The job of this function is to make pPg clean by writing its contents
41679 ** out to the database file, if possible. This may involve syncing the
41680 ** journal file.
41681 **
41682 ** If successful, sqlite3PcacheMakeClean() is called on the page and
41683 ** SQLITE_OK returned. If an IO error occurs while trying to make the
41684 ** page clean, the IO error code is returned. If the page cannot be
41685 ** made clean for some other reason, but no error occurs, then SQLITE_OK
41686 ** is returned by sqlite3PcacheMakeClean() is not called.
41687 */
41688 static int pagerStress(void *p, PgHdr *pPg){
41689   Pager *pPager = (Pager *)p;
41690   int rc = SQLITE_OK;
41691 
41692   assert( pPg->pPager==pPager );
41693   assert( pPg->flags&PGHDR_DIRTY );
41694 
41695   /* The doNotSyncSpill flag is set during times when doing a sync of
41696   ** journal (and adding a new header) is not allowed.  This occurs
41697   ** during calls to sqlite3PagerWrite() while trying to journal multiple
41698   ** pages belonging to the same sector.
41699   **
41700   ** The doNotSpill flag inhibits all cache spilling regardless of whether
41701   ** or not a sync is required.  This is set during a rollback.
41702   **
41703   ** Spilling is also prohibited when in an error state since that could
41704   ** lead to database corruption.   In the current implementaton it
41705   ** is impossible for sqlite3PCacheFetch() to be called with createFlag==1
41706   ** while in the error state, hence it is impossible for this routine to
41707   ** be called in the error state.  Nevertheless, we include a NEVER()
41708   ** test for the error state as a safeguard against future changes.
41709   */
41710   if( NEVER(pPager->errCode) ) return SQLITE_OK;
41711   if( pPager->doNotSpill ) return SQLITE_OK;
41712   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
41713     return SQLITE_OK;
41714   }
41715 
41716   pPg->pDirty = 0;
41717   if( pagerUseWal(pPager) ){
41718     /* Write a single frame for this page to the log. */
41719     if( subjRequiresPage(pPg) ){
41720       rc = subjournalPage(pPg);
41721     }
41722     if( rc==SQLITE_OK ){
41723       rc = pagerWalFrames(pPager, pPg, 0, 0, 0);
41724     }
41725   }else{
41726 
41727     /* Sync the journal file if required. */
41728     if( pPg->flags&PGHDR_NEED_SYNC
41729      || pPager->eState==PAGER_WRITER_CACHEMOD
41730     ){
41731       rc = syncJournal(pPager, 1);
41732     }
41733 
41734     /* If the page number of this page is larger than the current size of
41735     ** the database image, it may need to be written to the sub-journal.
41736     ** This is because the call to pager_write_pagelist() below will not
41737     ** actually write data to the file in this case.
41738     **
41739     ** Consider the following sequence of events:
41740     **
41741     **   BEGIN;
41742     **     <journal page X>
41743     **     <modify page X>
41744     **     SAVEPOINT sp;
41745     **       <shrink database file to Y pages>
41746     **       pagerStress(page X)
41747     **     ROLLBACK TO sp;
41748     **
41749     ** If (X>Y), then when pagerStress is called page X will not be written
41750     ** out to the database file, but will be dropped from the cache. Then,
41751     ** following the "ROLLBACK TO sp" statement, reading page X will read
41752     ** data from the database file. This will be the copy of page X as it
41753     ** was when the transaction started, not as it was when "SAVEPOINT sp"
41754     ** was executed.
41755     **
41756     ** The solution is to write the current data for page X into the
41757     ** sub-journal file now (if it is not already there), so that it will
41758     ** be restored to its current value when the "ROLLBACK TO sp" is
41759     ** executed.
41760     */
41761     if( NEVER(
41762         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
41763     ) ){
41764       rc = subjournalPage(pPg);
41765     }
41766 
41767     /* Write the contents of the page out to the database file. */
41768     if( rc==SQLITE_OK ){
41769       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
41770       rc = pager_write_pagelist(pPager, pPg);
41771     }
41772   }
41773 
41774   /* Mark the page as clean. */
41775   if( rc==SQLITE_OK ){
41776     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
41777     sqlite3PcacheMakeClean(pPg);
41778   }
41779 
41780   return pager_error(pPager, rc);
41781 }
41782 
41783 
41784 /*
41785 ** Allocate and initialize a new Pager object and put a pointer to it
41786 ** in *ppPager. The pager should eventually be freed by passing it
41787 ** to sqlite3PagerClose().
41788 **
41789 ** The zFilename argument is the path to the database file to open.
41790 ** If zFilename is NULL then a randomly-named temporary file is created
41791 ** and used as the file to be cached. Temporary files are be deleted
41792 ** automatically when they are closed. If zFilename is ":memory:" then
41793 ** all information is held in cache. It is never written to disk.
41794 ** This can be used to implement an in-memory database.
41795 **
41796 ** The nExtra parameter specifies the number of bytes of space allocated
41797 ** along with each page reference. This space is available to the user
41798 ** via the sqlite3PagerGetExtra() API.
41799 **
41800 ** The flags argument is used to specify properties that affect the
41801 ** operation of the pager. It should be passed some bitwise combination
41802 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
41803 **
41804 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
41805 ** of the xOpen() method of the supplied VFS when opening files.
41806 **
41807 ** If the pager object is allocated and the specified file opened
41808 ** successfully, SQLITE_OK is returned and *ppPager set to point to
41809 ** the new pager object. If an error occurs, *ppPager is set to NULL
41810 ** and error code returned. This function may return SQLITE_NOMEM
41811 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
41812 ** various SQLITE_IO_XXX errors.
41813 */
41814 SQLITE_PRIVATE int sqlite3PagerOpen(
41815   sqlite3_vfs *pVfs,       /* The virtual file system to use */
41816   Pager **ppPager,         /* OUT: Return the Pager structure here */
41817   const char *zFilename,   /* Name of the database file to open */
41818   int nExtra,              /* Extra bytes append to each in-memory page */
41819   int flags,               /* flags controlling this file */
41820   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
41821   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
41822 ){
41823   u8 *pPtr;
41824   Pager *pPager = 0;       /* Pager object to allocate and return */
41825   int rc = SQLITE_OK;      /* Return code */
41826   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
41827   int memDb = 0;           /* True if this is an in-memory file */
41828   int readOnly = 0;        /* True if this is a read-only file */
41829   int journalFileSize;     /* Bytes to allocate for each journal fd */
41830   char *zPathname = 0;     /* Full path to database file */
41831   int nPathname = 0;       /* Number of bytes in zPathname */
41832   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
41833   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
41834   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
41835   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
41836   const char *zUri = 0;    /* URI args to copy */
41837   int nUri = 0;            /* Number of bytes of URI args at *zUri */
41838 
41839   /* Figure out how much space is required for each journal file-handle
41840   ** (there are two of them, the main journal and the sub-journal). This
41841   ** is the maximum space required for an in-memory journal file handle
41842   ** and a regular journal file-handle. Note that a "regular journal-handle"
41843   ** may be a wrapper capable of caching the first portion of the journal
41844   ** file in memory to implement the atomic-write optimization (see
41845   ** source file journal.c).
41846   */
41847   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
41848     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
41849   }else{
41850     journalFileSize = ROUND8(sqlite3MemJournalSize());
41851   }
41852 
41853   /* Set the output variable to NULL in case an error occurs. */
41854   *ppPager = 0;
41855 
41856 #ifndef SQLITE_OMIT_MEMORYDB
41857   if( flags & PAGER_MEMORY ){
41858     memDb = 1;
41859     zFilename = 0;
41860   }
41861 #endif
41862 
41863   /* Compute and store the full pathname in an allocated buffer pointed
41864   ** to by zPathname, length nPathname. Or, if this is a temporary file,
41865   ** leave both nPathname and zPathname set to 0.
41866   */
41867   if( zFilename && zFilename[0] ){
41868     const char *z;
41869     nPathname = pVfs->mxPathname+1;
41870     zPathname = sqlite3Malloc(nPathname*2);
41871     if( zPathname==0 ){
41872       return SQLITE_NOMEM;
41873     }
41874     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
41875     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
41876     nPathname = sqlite3Strlen30(zPathname);
41877     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
41878     while( *z ){
41879       z += sqlite3Strlen30(z)+1;
41880       z += sqlite3Strlen30(z)+1;
41881     }
41882     nUri = &z[1] - zUri;
41883     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
41884       /* This branch is taken when the journal path required by
41885       ** the database being opened will be more than pVfs->mxPathname
41886       ** bytes in length. This means the database cannot be opened,
41887       ** as it will not be possible to open the journal file or even
41888       ** check for a hot-journal before reading.
41889       */
41890       rc = SQLITE_CANTOPEN_BKPT;
41891     }
41892     if( rc!=SQLITE_OK ){
41893       sqlite3_free(zPathname);
41894       return rc;
41895     }
41896   }
41897 
41898   /* Allocate memory for the Pager structure, PCache object, the
41899   ** three file descriptors, the database file name and the journal
41900   ** file name. The layout in memory is as follows:
41901   **
41902   **     Pager object                    (sizeof(Pager) bytes)
41903   **     PCache object                   (sqlite3PcacheSize() bytes)
41904   **     Database file handle            (pVfs->szOsFile bytes)
41905   **     Sub-journal file handle         (journalFileSize bytes)
41906   **     Main journal file handle        (journalFileSize bytes)
41907   **     Database file name              (nPathname+1 bytes)
41908   **     Journal file name               (nPathname+8+1 bytes)
41909   */
41910   pPtr = (u8 *)sqlite3MallocZero(
41911     ROUND8(sizeof(*pPager)) +      /* Pager structure */
41912     ROUND8(pcacheSize) +           /* PCache object */
41913     ROUND8(pVfs->szOsFile) +       /* The main db file */
41914     journalFileSize * 2 +          /* The two journal files */
41915     nPathname + 1 + nUri +         /* zFilename */
41916     nPathname + 8 + 1              /* zJournal */
41917 #ifndef SQLITE_OMIT_WAL
41918     + nPathname + 4 + 1              /* zWal */
41919 #endif
41920   );
41921   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
41922   if( !pPtr ){
41923     sqlite3_free(zPathname);
41924     return SQLITE_NOMEM;
41925   }
41926   pPager =              (Pager*)(pPtr);
41927   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
41928   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
41929   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
41930   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
41931   pPager->zFilename =    (char*)(pPtr += journalFileSize);
41932   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
41933 
41934   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
41935   if( zPathname ){
41936     assert( nPathname>0 );
41937     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
41938     memcpy(pPager->zFilename, zPathname, nPathname);
41939     memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
41940     memcpy(pPager->zJournal, zPathname, nPathname);
41941     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
41942     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
41943 #ifndef SQLITE_OMIT_WAL
41944     pPager->zWal = &pPager->zJournal[nPathname+8+1];
41945     memcpy(pPager->zWal, zPathname, nPathname);
41946     memcpy(&pPager->zWal[nPathname], "-wal", 4);
41947     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
41948 #endif
41949     sqlite3_free(zPathname);
41950   }
41951   pPager->pVfs = pVfs;
41952   pPager->vfsFlags = vfsFlags;
41953 
41954   /* Open the pager file.
41955   */
41956   if( zFilename && zFilename[0] ){
41957     int fout = 0;                    /* VFS flags returned by xOpen() */
41958     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
41959     assert( !memDb );
41960     readOnly = (fout&SQLITE_OPEN_READONLY);
41961 
41962     /* If the file was successfully opened for read/write access,
41963     ** choose a default page size in case we have to create the
41964     ** database file. The default page size is the maximum of:
41965     **
41966     **    + SQLITE_DEFAULT_PAGE_SIZE,
41967     **    + The value returned by sqlite3OsSectorSize()
41968     **    + The largest page size that can be written atomically.
41969     */
41970     if( rc==SQLITE_OK && !readOnly ){
41971       setSectorSize(pPager);
41972       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
41973       if( szPageDflt<pPager->sectorSize ){
41974         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
41975           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
41976         }else{
41977           szPageDflt = (u32)pPager->sectorSize;
41978         }
41979       }
41980 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
41981       {
41982         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
41983         int ii;
41984         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
41985         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
41986         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
41987         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
41988           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
41989             szPageDflt = ii;
41990           }
41991         }
41992       }
41993 #endif
41994     }
41995   }else{
41996     /* If a temporary file is requested, it is not opened immediately.
41997     ** In this case we accept the default page size and delay actually
41998     ** opening the file until the first call to OsWrite().
41999     **
42000     ** This branch is also run for an in-memory database. An in-memory
42001     ** database is the same as a temp-file that is never written out to
42002     ** disk and uses an in-memory rollback journal.
42003     */
42004     tempFile = 1;
42005     pPager->eState = PAGER_READER;
42006     pPager->eLock = EXCLUSIVE_LOCK;
42007     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
42008   }
42009 
42010   /* The following call to PagerSetPagesize() serves to set the value of
42011   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
42012   */
42013   if( rc==SQLITE_OK ){
42014     assert( pPager->memDb==0 );
42015     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
42016     testcase( rc!=SQLITE_OK );
42017   }
42018 
42019   /* If an error occurred in either of the blocks above, free the
42020   ** Pager structure and close the file.
42021   */
42022   if( rc!=SQLITE_OK ){
42023     assert( !pPager->pTmpSpace );
42024     sqlite3OsClose(pPager->fd);
42025     sqlite3_free(pPager);
42026     return rc;
42027   }
42028 
42029   /* Initialize the PCache object. */
42030   assert( nExtra<1000 );
42031   nExtra = ROUND8(nExtra);
42032   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
42033                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
42034 
42035   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
42036   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
42037 
42038   pPager->useJournal = (u8)useJournal;
42039   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
42040   /* pPager->stmtOpen = 0; */
42041   /* pPager->stmtInUse = 0; */
42042   /* pPager->nRef = 0; */
42043   /* pPager->stmtSize = 0; */
42044   /* pPager->stmtJSize = 0; */
42045   /* pPager->nPage = 0; */
42046   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
42047   /* pPager->state = PAGER_UNLOCK; */
42048 #if 0
42049   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
42050 #endif
42051   /* pPager->errMask = 0; */
42052   pPager->tempFile = (u8)tempFile;
42053   assert( tempFile==PAGER_LOCKINGMODE_NORMAL
42054           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
42055   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
42056   pPager->exclusiveMode = (u8)tempFile;
42057   pPager->changeCountDone = pPager->tempFile;
42058   pPager->memDb = (u8)memDb;
42059   pPager->readOnly = (u8)readOnly;
42060   assert( useJournal || pPager->tempFile );
42061   pPager->noSync = pPager->tempFile;
42062   pPager->fullSync = pPager->noSync ?0:1;
42063   pPager->syncFlags = pPager->noSync ? 0 : SQLITE_SYNC_NORMAL;
42064   pPager->ckptSyncFlags = pPager->syncFlags;
42065   /* pPager->pFirst = 0; */
42066   /* pPager->pFirstSynced = 0; */
42067   /* pPager->pLast = 0; */
42068   pPager->nExtra = (u16)nExtra;
42069   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
42070   assert( isOpen(pPager->fd) || tempFile );
42071   setSectorSize(pPager);
42072   if( !useJournal ){
42073     pPager->journalMode = PAGER_JOURNALMODE_OFF;
42074   }else if( memDb ){
42075     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
42076   }
42077   /* pPager->xBusyHandler = 0; */
42078   /* pPager->pBusyHandlerArg = 0; */
42079   pPager->xReiniter = xReinit;
42080   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
42081 
42082   *ppPager = pPager;
42083   return SQLITE_OK;
42084 }
42085 
42086 
42087 
42088 /*
42089 ** This function is called after transitioning from PAGER_UNLOCK to
42090 ** PAGER_SHARED state. It tests if there is a hot journal present in
42091 ** the file-system for the given pager. A hot journal is one that
42092 ** needs to be played back. According to this function, a hot-journal
42093 ** file exists if the following criteria are met:
42094 **
42095 **   * The journal file exists in the file system, and
42096 **   * No process holds a RESERVED or greater lock on the database file, and
42097 **   * The database file itself is greater than 0 bytes in size, and
42098 **   * The first byte of the journal file exists and is not 0x00.
42099 **
42100 ** If the current size of the database file is 0 but a journal file
42101 ** exists, that is probably an old journal left over from a prior
42102 ** database with the same name. In this case the journal file is
42103 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
42104 ** is returned.
42105 **
42106 ** This routine does not check if there is a master journal filename
42107 ** at the end of the file. If there is, and that master journal file
42108 ** does not exist, then the journal file is not really hot. In this
42109 ** case this routine will return a false-positive. The pager_playback()
42110 ** routine will discover that the journal file is not really hot and
42111 ** will not roll it back.
42112 **
42113 ** If a hot-journal file is found to exist, *pExists is set to 1 and
42114 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
42115 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
42116 ** to determine whether or not a hot-journal file exists, the IO error
42117 ** code is returned and the value of *pExists is undefined.
42118 */
42119 static int hasHotJournal(Pager *pPager, int *pExists){
42120   sqlite3_vfs * const pVfs = pPager->pVfs;
42121   int rc = SQLITE_OK;           /* Return code */
42122   int exists = 1;               /* True if a journal file is present */
42123   int jrnlOpen = !!isOpen(pPager->jfd);
42124 
42125   assert( pPager->useJournal );
42126   assert( isOpen(pPager->fd) );
42127   assert( pPager->eState==PAGER_OPEN );
42128 
42129   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
42130     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
42131   ));
42132 
42133   *pExists = 0;
42134   if( !jrnlOpen ){
42135     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
42136   }
42137   if( rc==SQLITE_OK && exists ){
42138     int locked = 0;             /* True if some process holds a RESERVED lock */
42139 
42140     /* Race condition here:  Another process might have been holding the
42141     ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
42142     ** call above, but then delete the journal and drop the lock before
42143     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
42144     ** is the case, this routine might think there is a hot journal when
42145     ** in fact there is none.  This results in a false-positive which will
42146     ** be dealt with by the playback routine.  Ticket #3883.
42147     */
42148     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
42149     if( rc==SQLITE_OK && !locked ){
42150       Pgno nPage;                 /* Number of pages in database file */
42151 
42152       /* Check the size of the database file. If it consists of 0 pages,
42153       ** then delete the journal file. See the header comment above for
42154       ** the reasoning here.  Delete the obsolete journal file under
42155       ** a RESERVED lock to avoid race conditions and to avoid violating
42156       ** [H33020].
42157       */
42158       rc = pagerPagecount(pPager, &nPage);
42159       if( rc==SQLITE_OK ){
42160         if( nPage==0 ){
42161           sqlite3BeginBenignMalloc();
42162           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
42163             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
42164             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
42165           }
42166           sqlite3EndBenignMalloc();
42167         }else{
42168           /* The journal file exists and no other connection has a reserved
42169           ** or greater lock on the database file. Now check that there is
42170           ** at least one non-zero bytes at the start of the journal file.
42171           ** If there is, then we consider this journal to be hot. If not,
42172           ** it can be ignored.
42173           */
42174           if( !jrnlOpen ){
42175             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
42176             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
42177           }
42178           if( rc==SQLITE_OK ){
42179             u8 first = 0;
42180             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
42181             if( rc==SQLITE_IOERR_SHORT_READ ){
42182               rc = SQLITE_OK;
42183             }
42184             if( !jrnlOpen ){
42185               sqlite3OsClose(pPager->jfd);
42186             }
42187             *pExists = (first!=0);
42188           }else if( rc==SQLITE_CANTOPEN ){
42189             /* If we cannot open the rollback journal file in order to see if
42190             ** its has a zero header, that might be due to an I/O error, or
42191             ** it might be due to the race condition described above and in
42192             ** ticket #3883.  Either way, assume that the journal is hot.
42193             ** This might be a false positive.  But if it is, then the
42194             ** automatic journal playback and recovery mechanism will deal
42195             ** with it under an EXCLUSIVE lock where we do not need to
42196             ** worry so much with race conditions.
42197             */
42198             *pExists = 1;
42199             rc = SQLITE_OK;
42200           }
42201         }
42202       }
42203     }
42204   }
42205 
42206   return rc;
42207 }
42208 
42209 /*
42210 ** This function is called to obtain a shared lock on the database file.
42211 ** It is illegal to call sqlite3PagerAcquire() until after this function
42212 ** has been successfully called. If a shared-lock is already held when
42213 ** this function is called, it is a no-op.
42214 **
42215 ** The following operations are also performed by this function.
42216 **
42217 **   1) If the pager is currently in PAGER_OPEN state (no lock held
42218 **      on the database file), then an attempt is made to obtain a
42219 **      SHARED lock on the database file. Immediately after obtaining
42220 **      the SHARED lock, the file-system is checked for a hot-journal,
42221 **      which is played back if present. Following any hot-journal
42222 **      rollback, the contents of the cache are validated by checking
42223 **      the 'change-counter' field of the database file header and
42224 **      discarded if they are found to be invalid.
42225 **
42226 **   2) If the pager is running in exclusive-mode, and there are currently
42227 **      no outstanding references to any pages, and is in the error state,
42228 **      then an attempt is made to clear the error state by discarding
42229 **      the contents of the page cache and rolling back any open journal
42230 **      file.
42231 **
42232 ** If everything is successful, SQLITE_OK is returned. If an IO error
42233 ** occurs while locking the database, checking for a hot-journal file or
42234 ** rolling back a journal file, the IO error code is returned.
42235 */
42236 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
42237   int rc = SQLITE_OK;                /* Return code */
42238 
42239   /* This routine is only called from b-tree and only when there are no
42240   ** outstanding pages. This implies that the pager state should either
42241   ** be OPEN or READER. READER is only possible if the pager is or was in
42242   ** exclusive access mode.
42243   */
42244   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
42245   assert( assert_pager_state(pPager) );
42246   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
42247   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
42248 
42249   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
42250     int bHotJournal = 1;          /* True if there exists a hot journal-file */
42251 
42252     assert( !MEMDB );
42253     assert( pPager->noReadlock==0 || pPager->readOnly );
42254 
42255     if( pPager->noReadlock==0 ){
42256       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
42257       if( rc!=SQLITE_OK ){
42258         assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
42259         goto failed;
42260       }
42261     }
42262 
42263     /* If a journal file exists, and there is no RESERVED lock on the
42264     ** database file, then it either needs to be played back or deleted.
42265     */
42266     if( pPager->eLock<=SHARED_LOCK ){
42267       rc = hasHotJournal(pPager, &bHotJournal);
42268     }
42269     if( rc!=SQLITE_OK ){
42270       goto failed;
42271     }
42272     if( bHotJournal ){
42273       /* Get an EXCLUSIVE lock on the database file. At this point it is
42274       ** important that a RESERVED lock is not obtained on the way to the
42275       ** EXCLUSIVE lock. If it were, another process might open the
42276       ** database file, detect the RESERVED lock, and conclude that the
42277       ** database is safe to read while this process is still rolling the
42278       ** hot-journal back.
42279       **
42280       ** Because the intermediate RESERVED lock is not requested, any
42281       ** other process attempting to access the database file will get to
42282       ** this point in the code and fail to obtain its own EXCLUSIVE lock
42283       ** on the database file.
42284       **
42285       ** Unless the pager is in locking_mode=exclusive mode, the lock is
42286       ** downgraded to SHARED_LOCK before this function returns.
42287       */
42288       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42289       if( rc!=SQLITE_OK ){
42290         goto failed;
42291       }
42292 
42293       /* If it is not already open and the file exists on disk, open the
42294       ** journal for read/write access. Write access is required because
42295       ** in exclusive-access mode the file descriptor will be kept open
42296       ** and possibly used for a transaction later on. Also, write-access
42297       ** is usually required to finalize the journal in journal_mode=persist
42298       ** mode (and also for journal_mode=truncate on some systems).
42299       **
42300       ** If the journal does not exist, it usually means that some
42301       ** other connection managed to get in and roll it back before
42302       ** this connection obtained the exclusive lock above. Or, it
42303       ** may mean that the pager was in the error-state when this
42304       ** function was called and the journal file does not exist.
42305       */
42306       if( !isOpen(pPager->jfd) ){
42307         sqlite3_vfs * const pVfs = pPager->pVfs;
42308         int bExists;              /* True if journal file exists */
42309         rc = sqlite3OsAccess(
42310             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
42311         if( rc==SQLITE_OK && bExists ){
42312           int fout = 0;
42313           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
42314           assert( !pPager->tempFile );
42315           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
42316           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42317           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
42318             rc = SQLITE_CANTOPEN_BKPT;
42319             sqlite3OsClose(pPager->jfd);
42320           }
42321         }
42322       }
42323 
42324       /* Playback and delete the journal.  Drop the database write
42325       ** lock and reacquire the read lock. Purge the cache before
42326       ** playing back the hot-journal so that we don't end up with
42327       ** an inconsistent cache.  Sync the hot journal before playing
42328       ** it back since the process that crashed and left the hot journal
42329       ** probably did not sync it and we are required to always sync
42330       ** the journal before playing it back.
42331       */
42332       if( isOpen(pPager->jfd) ){
42333         assert( rc==SQLITE_OK );
42334         rc = pagerSyncHotJournal(pPager);
42335         if( rc==SQLITE_OK ){
42336           rc = pager_playback(pPager, 1);
42337           pPager->eState = PAGER_OPEN;
42338         }
42339       }else if( !pPager->exclusiveMode ){
42340         pagerUnlockDb(pPager, SHARED_LOCK);
42341       }
42342 
42343       if( rc!=SQLITE_OK ){
42344         /* This branch is taken if an error occurs while trying to open
42345         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
42346         ** pager_unlock() routine will be called before returning to unlock
42347         ** the file. If the unlock attempt fails, then Pager.eLock must be
42348         ** set to UNKNOWN_LOCK (see the comment above the #define for
42349         ** UNKNOWN_LOCK above for an explanation).
42350         **
42351         ** In order to get pager_unlock() to do this, set Pager.eState to
42352         ** PAGER_ERROR now. This is not actually counted as a transition
42353         ** to ERROR state in the state diagram at the top of this file,
42354         ** since we know that the same call to pager_unlock() will very
42355         ** shortly transition the pager object to the OPEN state. Calling
42356         ** assert_pager_state() would fail now, as it should not be possible
42357         ** to be in ERROR state when there are zero outstanding page
42358         ** references.
42359         */
42360         pager_error(pPager, rc);
42361         goto failed;
42362       }
42363 
42364       assert( pPager->eState==PAGER_OPEN );
42365       assert( (pPager->eLock==SHARED_LOCK)
42366            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
42367       );
42368     }
42369 
42370     if( !pPager->tempFile
42371      && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
42372     ){
42373       /* The shared-lock has just been acquired on the database file
42374       ** and there are already pages in the cache (from a previous
42375       ** read or write transaction).  Check to see if the database
42376       ** has been modified.  If the database has changed, flush the
42377       ** cache.
42378       **
42379       ** Database changes is detected by looking at 15 bytes beginning
42380       ** at offset 24 into the file.  The first 4 of these 16 bytes are
42381       ** a 32-bit counter that is incremented with each change.  The
42382       ** other bytes change randomly with each file change when
42383       ** a codec is in use.
42384       **
42385       ** There is a vanishingly small chance that a change will not be
42386       ** detected.  The chance of an undetected change is so small that
42387       ** it can be neglected.
42388       */
42389       Pgno nPage = 0;
42390       char dbFileVers[sizeof(pPager->dbFileVers)];
42391 
42392       rc = pagerPagecount(pPager, &nPage);
42393       if( rc ) goto failed;
42394 
42395       if( nPage>0 ){
42396         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
42397         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
42398         if( rc!=SQLITE_OK ){
42399           goto failed;
42400         }
42401       }else{
42402         memset(dbFileVers, 0, sizeof(dbFileVers));
42403       }
42404 
42405       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
42406         pager_reset(pPager);
42407       }
42408     }
42409 
42410     /* If there is a WAL file in the file-system, open this database in WAL
42411     ** mode. Otherwise, the following function call is a no-op.
42412     */
42413     rc = pagerOpenWalIfPresent(pPager);
42414 #ifndef SQLITE_OMIT_WAL
42415     assert( pPager->pWal==0 || rc==SQLITE_OK );
42416 #endif
42417   }
42418 
42419   if( pagerUseWal(pPager) ){
42420     assert( rc==SQLITE_OK );
42421     rc = pagerBeginReadTransaction(pPager);
42422   }
42423 
42424   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
42425     rc = pagerPagecount(pPager, &pPager->dbSize);
42426   }
42427 
42428  failed:
42429   if( rc!=SQLITE_OK ){
42430     assert( !MEMDB );
42431     pager_unlock(pPager);
42432     assert( pPager->eState==PAGER_OPEN );
42433   }else{
42434     pPager->eState = PAGER_READER;
42435   }
42436   return rc;
42437 }
42438 
42439 /*
42440 ** If the reference count has reached zero, rollback any active
42441 ** transaction and unlock the pager.
42442 **
42443 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
42444 ** the rollback journal, the unlock is not performed and there is
42445 ** nothing to rollback, so this routine is a no-op.
42446 */
42447 static void pagerUnlockIfUnused(Pager *pPager){
42448   if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
42449     pagerUnlockAndRollback(pPager);
42450   }
42451 }
42452 
42453 /*
42454 ** Acquire a reference to page number pgno in pager pPager (a page
42455 ** reference has type DbPage*). If the requested reference is
42456 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
42457 **
42458 ** If the requested page is already in the cache, it is returned.
42459 ** Otherwise, a new page object is allocated and populated with data
42460 ** read from the database file. In some cases, the pcache module may
42461 ** choose not to allocate a new page object and may reuse an existing
42462 ** object with no outstanding references.
42463 **
42464 ** The extra data appended to a page is always initialized to zeros the
42465 ** first time a page is loaded into memory. If the page requested is
42466 ** already in the cache when this function is called, then the extra
42467 ** data is left as it was when the page object was last used.
42468 **
42469 ** If the database image is smaller than the requested page or if a
42470 ** non-zero value is passed as the noContent parameter and the
42471 ** requested page is not already stored in the cache, then no
42472 ** actual disk read occurs. In this case the memory image of the
42473 ** page is initialized to all zeros.
42474 **
42475 ** If noContent is true, it means that we do not care about the contents
42476 ** of the page. This occurs in two seperate scenarios:
42477 **
42478 **   a) When reading a free-list leaf page from the database, and
42479 **
42480 **   b) When a savepoint is being rolled back and we need to load
42481 **      a new page into the cache to be filled with the data read
42482 **      from the savepoint journal.
42483 **
42484 ** If noContent is true, then the data returned is zeroed instead of
42485 ** being read from the database. Additionally, the bits corresponding
42486 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
42487 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
42488 ** savepoints are set. This means if the page is made writable at any
42489 ** point in the future, using a call to sqlite3PagerWrite(), its contents
42490 ** will not be journaled. This saves IO.
42491 **
42492 ** The acquisition might fail for several reasons.  In all cases,
42493 ** an appropriate error code is returned and *ppPage is set to NULL.
42494 **
42495 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
42496 ** to find a page in the in-memory cache first.  If the page is not already
42497 ** in memory, this routine goes to disk to read it in whereas Lookup()
42498 ** just returns 0.  This routine acquires a read-lock the first time it
42499 ** has to go to disk, and could also playback an old journal if necessary.
42500 ** Since Lookup() never goes to disk, it never has to deal with locks
42501 ** or journal files.
42502 */
42503 SQLITE_PRIVATE int sqlite3PagerAcquire(
42504   Pager *pPager,      /* The pager open on the database file */
42505   Pgno pgno,          /* Page number to fetch */
42506   DbPage **ppPage,    /* Write a pointer to the page here */
42507   int noContent       /* Do not bother reading content from disk if true */
42508 ){
42509   int rc;
42510   PgHdr *pPg;
42511 
42512   assert( pPager->eState>=PAGER_READER );
42513   assert( assert_pager_state(pPager) );
42514 
42515   if( pgno==0 ){
42516     return SQLITE_CORRUPT_BKPT;
42517   }
42518 
42519   /* If the pager is in the error state, return an error immediately.
42520   ** Otherwise, request the page from the PCache layer. */
42521   if( pPager->errCode!=SQLITE_OK ){
42522     rc = pPager->errCode;
42523   }else{
42524     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
42525   }
42526 
42527   if( rc!=SQLITE_OK ){
42528     /* Either the call to sqlite3PcacheFetch() returned an error or the
42529     ** pager was already in the error-state when this function was called.
42530     ** Set pPg to 0 and jump to the exception handler.  */
42531     pPg = 0;
42532     goto pager_acquire_err;
42533   }
42534   assert( (*ppPage)->pgno==pgno );
42535   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
42536 
42537   if( (*ppPage)->pPager && !noContent ){
42538     /* In this case the pcache already contains an initialized copy of
42539     ** the page. Return without further ado.  */
42540     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
42541     PAGER_INCR(pPager->nHit);
42542     return SQLITE_OK;
42543 
42544   }else{
42545     /* The pager cache has created a new page. Its content needs to
42546     ** be initialized.  */
42547 
42548     PAGER_INCR(pPager->nMiss);
42549     pPg = *ppPage;
42550     pPg->pPager = pPager;
42551 
42552     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
42553     ** number greater than this, or the unused locking-page, is requested. */
42554     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
42555       rc = SQLITE_CORRUPT_BKPT;
42556       goto pager_acquire_err;
42557     }
42558 
42559     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
42560       if( pgno>pPager->mxPgno ){
42561         rc = SQLITE_FULL;
42562         goto pager_acquire_err;
42563       }
42564       if( noContent ){
42565         /* Failure to set the bits in the InJournal bit-vectors is benign.
42566         ** It merely means that we might do some extra work to journal a
42567         ** page that does not need to be journaled.  Nevertheless, be sure
42568         ** to test the case where a malloc error occurs while trying to set
42569         ** a bit in a bit vector.
42570         */
42571         sqlite3BeginBenignMalloc();
42572         if( pgno<=pPager->dbOrigSize ){
42573           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
42574           testcase( rc==SQLITE_NOMEM );
42575         }
42576         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
42577         testcase( rc==SQLITE_NOMEM );
42578         sqlite3EndBenignMalloc();
42579       }
42580       memset(pPg->pData, 0, pPager->pageSize);
42581       IOTRACE(("ZERO %p %d\n", pPager, pgno));
42582     }else{
42583       assert( pPg->pPager==pPager );
42584       rc = readDbPage(pPg);
42585       if( rc!=SQLITE_OK ){
42586         goto pager_acquire_err;
42587       }
42588     }
42589     pager_set_pagehash(pPg);
42590   }
42591 
42592   return SQLITE_OK;
42593 
42594 pager_acquire_err:
42595   assert( rc!=SQLITE_OK );
42596   if( pPg ){
42597     sqlite3PcacheDrop(pPg);
42598   }
42599   pagerUnlockIfUnused(pPager);
42600 
42601   *ppPage = 0;
42602   return rc;
42603 }
42604 
42605 /*
42606 ** Acquire a page if it is already in the in-memory cache.  Do
42607 ** not read the page from disk.  Return a pointer to the page,
42608 ** or 0 if the page is not in cache.
42609 **
42610 ** See also sqlite3PagerGet().  The difference between this routine
42611 ** and sqlite3PagerGet() is that _get() will go to the disk and read
42612 ** in the page if the page is not already in cache.  This routine
42613 ** returns NULL if the page is not in cache or if a disk I/O error
42614 ** has ever happened.
42615 */
42616 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
42617   PgHdr *pPg = 0;
42618   assert( pPager!=0 );
42619   assert( pgno!=0 );
42620   assert( pPager->pPCache!=0 );
42621   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
42622   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
42623   return pPg;
42624 }
42625 
42626 /*
42627 ** Release a page reference.
42628 **
42629 ** If the number of references to the page drop to zero, then the
42630 ** page is added to the LRU list.  When all references to all pages
42631 ** are released, a rollback occurs and the lock on the database is
42632 ** removed.
42633 */
42634 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
42635   if( pPg ){
42636     Pager *pPager = pPg->pPager;
42637     sqlite3PcacheRelease(pPg);
42638     pagerUnlockIfUnused(pPager);
42639   }
42640 }
42641 
42642 /*
42643 ** This function is called at the start of every write transaction.
42644 ** There must already be a RESERVED or EXCLUSIVE lock on the database
42645 ** file when this routine is called.
42646 **
42647 ** Open the journal file for pager pPager and write a journal header
42648 ** to the start of it. If there are active savepoints, open the sub-journal
42649 ** as well. This function is only used when the journal file is being
42650 ** opened to write a rollback log for a transaction. It is not used
42651 ** when opening a hot journal file to roll it back.
42652 **
42653 ** If the journal file is already open (as it may be in exclusive mode),
42654 ** then this function just writes a journal header to the start of the
42655 ** already open file.
42656 **
42657 ** Whether or not the journal file is opened by this function, the
42658 ** Pager.pInJournal bitvec structure is allocated.
42659 **
42660 ** Return SQLITE_OK if everything is successful. Otherwise, return
42661 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
42662 ** an IO error code if opening or writing the journal file fails.
42663 */
42664 static int pager_open_journal(Pager *pPager){
42665   int rc = SQLITE_OK;                        /* Return code */
42666   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
42667 
42668   assert( pPager->eState==PAGER_WRITER_LOCKED );
42669   assert( assert_pager_state(pPager) );
42670   assert( pPager->pInJournal==0 );
42671 
42672   /* If already in the error state, this function is a no-op.  But on
42673   ** the other hand, this routine is never called if we are already in
42674   ** an error state. */
42675   if( NEVER(pPager->errCode) ) return pPager->errCode;
42676 
42677   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42678     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
42679     if( pPager->pInJournal==0 ){
42680       return SQLITE_NOMEM;
42681     }
42682 
42683     /* Open the journal file if it is not already open. */
42684     if( !isOpen(pPager->jfd) ){
42685       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
42686         sqlite3MemJournalOpen(pPager->jfd);
42687       }else{
42688         const int flags =                   /* VFS flags to open journal file */
42689           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
42690           (pPager->tempFile ?
42691             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
42692             (SQLITE_OPEN_MAIN_JOURNAL)
42693           );
42694   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42695         rc = sqlite3JournalOpen(
42696             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
42697         );
42698   #else
42699         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
42700   #endif
42701       }
42702       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
42703     }
42704 
42705 
42706     /* Write the first journal header to the journal file and open
42707     ** the sub-journal if necessary.
42708     */
42709     if( rc==SQLITE_OK ){
42710       /* TODO: Check if all of these are really required. */
42711       pPager->nRec = 0;
42712       pPager->journalOff = 0;
42713       pPager->setMaster = 0;
42714       pPager->journalHdr = 0;
42715       rc = writeJournalHdr(pPager);
42716     }
42717   }
42718 
42719   if( rc!=SQLITE_OK ){
42720     sqlite3BitvecDestroy(pPager->pInJournal);
42721     pPager->pInJournal = 0;
42722   }else{
42723     assert( pPager->eState==PAGER_WRITER_LOCKED );
42724     pPager->eState = PAGER_WRITER_CACHEMOD;
42725   }
42726 
42727   return rc;
42728 }
42729 
42730 /*
42731 ** Begin a write-transaction on the specified pager object. If a
42732 ** write-transaction has already been opened, this function is a no-op.
42733 **
42734 ** If the exFlag argument is false, then acquire at least a RESERVED
42735 ** lock on the database file. If exFlag is true, then acquire at least
42736 ** an EXCLUSIVE lock. If such a lock is already held, no locking
42737 ** functions need be called.
42738 **
42739 ** If the subjInMemory argument is non-zero, then any sub-journal opened
42740 ** within this transaction will be opened as an in-memory file. This
42741 ** has no effect if the sub-journal is already opened (as it may be when
42742 ** running in exclusive mode) or if the transaction does not require a
42743 ** sub-journal. If the subjInMemory argument is zero, then any required
42744 ** sub-journal is implemented in-memory if pPager is an in-memory database,
42745 ** or using a temporary file otherwise.
42746 */
42747 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
42748   int rc = SQLITE_OK;
42749 
42750   if( pPager->errCode ) return pPager->errCode;
42751   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
42752   pPager->subjInMemory = (u8)subjInMemory;
42753 
42754   if( ALWAYS(pPager->eState==PAGER_READER) ){
42755     assert( pPager->pInJournal==0 );
42756 
42757     if( pagerUseWal(pPager) ){
42758       /* If the pager is configured to use locking_mode=exclusive, and an
42759       ** exclusive lock on the database is not already held, obtain it now.
42760       */
42761       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
42762         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
42763         if( rc!=SQLITE_OK ){
42764           return rc;
42765         }
42766         sqlite3WalExclusiveMode(pPager->pWal, 1);
42767       }
42768 
42769       /* Grab the write lock on the log file. If successful, upgrade to
42770       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
42771       ** The busy-handler is not invoked if another connection already
42772       ** holds the write-lock. If possible, the upper layer will call it.
42773       */
42774       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
42775     }else{
42776       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
42777       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
42778       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
42779       ** lock, but not when obtaining the RESERVED lock.
42780       */
42781       rc = pagerLockDb(pPager, RESERVED_LOCK);
42782       if( rc==SQLITE_OK && exFlag ){
42783         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
42784       }
42785     }
42786 
42787     if( rc==SQLITE_OK ){
42788       /* Change to WRITER_LOCKED state.
42789       **
42790       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
42791       ** when it has an open transaction, but never to DBMOD or FINISHED.
42792       ** This is because in those states the code to roll back savepoint
42793       ** transactions may copy data from the sub-journal into the database
42794       ** file as well as into the page cache. Which would be incorrect in
42795       ** WAL mode.
42796       */
42797       pPager->eState = PAGER_WRITER_LOCKED;
42798       pPager->dbHintSize = pPager->dbSize;
42799       pPager->dbFileSize = pPager->dbSize;
42800       pPager->dbOrigSize = pPager->dbSize;
42801       pPager->journalOff = 0;
42802     }
42803 
42804     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
42805     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
42806     assert( assert_pager_state(pPager) );
42807   }
42808 
42809   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
42810   return rc;
42811 }
42812 
42813 /*
42814 ** Mark a single data page as writeable. The page is written into the
42815 ** main journal or sub-journal as required. If the page is written into
42816 ** one of the journals, the corresponding bit is set in the
42817 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
42818 ** of any open savepoints as appropriate.
42819 */
42820 static int pager_write(PgHdr *pPg){
42821   void *pData = pPg->pData;
42822   Pager *pPager = pPg->pPager;
42823   int rc = SQLITE_OK;
42824 
42825   /* This routine is not called unless a write-transaction has already
42826   ** been started. The journal file may or may not be open at this point.
42827   ** It is never called in the ERROR state.
42828   */
42829   assert( pPager->eState==PAGER_WRITER_LOCKED
42830        || pPager->eState==PAGER_WRITER_CACHEMOD
42831        || pPager->eState==PAGER_WRITER_DBMOD
42832   );
42833   assert( assert_pager_state(pPager) );
42834 
42835   /* If an error has been previously detected, report the same error
42836   ** again. This should not happen, but the check provides robustness. */
42837   if( NEVER(pPager->errCode) )  return pPager->errCode;
42838 
42839   /* Higher-level routines never call this function if database is not
42840   ** writable.  But check anyway, just for robustness. */
42841   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
42842 
42843   CHECK_PAGE(pPg);
42844 
42845   /* The journal file needs to be opened. Higher level routines have already
42846   ** obtained the necessary locks to begin the write-transaction, but the
42847   ** rollback journal might not yet be open. Open it now if this is the case.
42848   **
42849   ** This is done before calling sqlite3PcacheMakeDirty() on the page.
42850   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
42851   ** an error might occur and the pager would end up in WRITER_LOCKED state
42852   ** with pages marked as dirty in the cache.
42853   */
42854   if( pPager->eState==PAGER_WRITER_LOCKED ){
42855     rc = pager_open_journal(pPager);
42856     if( rc!=SQLITE_OK ) return rc;
42857   }
42858   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42859   assert( assert_pager_state(pPager) );
42860 
42861   /* Mark the page as dirty.  If the page has already been written
42862   ** to the journal then we can return right away.
42863   */
42864   sqlite3PcacheMakeDirty(pPg);
42865   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
42866     assert( !pagerUseWal(pPager) );
42867   }else{
42868 
42869     /* The transaction journal now exists and we have a RESERVED or an
42870     ** EXCLUSIVE lock on the main database file.  Write the current page to
42871     ** the transaction journal if it is not there already.
42872     */
42873     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
42874       assert( pagerUseWal(pPager)==0 );
42875       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
42876         u32 cksum;
42877         char *pData2;
42878         i64 iOff = pPager->journalOff;
42879 
42880         /* We should never write to the journal file the page that
42881         ** contains the database locks.  The following assert verifies
42882         ** that we do not. */
42883         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
42884 
42885         assert( pPager->journalHdr<=pPager->journalOff );
42886         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42887         cksum = pager_cksum(pPager, (u8*)pData2);
42888 
42889         /* Even if an IO or diskfull error occurs while journalling the
42890         ** page in the block above, set the need-sync flag for the page.
42891         ** Otherwise, when the transaction is rolled back, the logic in
42892         ** playback_one_page() will think that the page needs to be restored
42893         ** in the database file. And if an IO error occurs while doing so,
42894         ** then corruption may follow.
42895         */
42896         pPg->flags |= PGHDR_NEED_SYNC;
42897 
42898         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
42899         if( rc!=SQLITE_OK ) return rc;
42900         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
42901         if( rc!=SQLITE_OK ) return rc;
42902         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
42903         if( rc!=SQLITE_OK ) return rc;
42904 
42905         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
42906                  pPager->journalOff, pPager->pageSize));
42907         PAGER_INCR(sqlite3_pager_writej_count);
42908         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
42909              PAGERID(pPager), pPg->pgno,
42910              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
42911 
42912         pPager->journalOff += 8 + pPager->pageSize;
42913         pPager->nRec++;
42914         assert( pPager->pInJournal!=0 );
42915         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
42916         testcase( rc==SQLITE_NOMEM );
42917         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
42918         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
42919         if( rc!=SQLITE_OK ){
42920           assert( rc==SQLITE_NOMEM );
42921           return rc;
42922         }
42923       }else{
42924         if( pPager->eState!=PAGER_WRITER_DBMOD ){
42925           pPg->flags |= PGHDR_NEED_SYNC;
42926         }
42927         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
42928                 PAGERID(pPager), pPg->pgno,
42929                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
42930       }
42931     }
42932 
42933     /* If the statement journal is open and the page is not in it,
42934     ** then write the current page to the statement journal.  Note that
42935     ** the statement journal format differs from the standard journal format
42936     ** in that it omits the checksums and the header.
42937     */
42938     if( subjRequiresPage(pPg) ){
42939       rc = subjournalPage(pPg);
42940     }
42941   }
42942 
42943   /* Update the database size and return.
42944   */
42945   if( pPager->dbSize<pPg->pgno ){
42946     pPager->dbSize = pPg->pgno;
42947   }
42948   return rc;
42949 }
42950 
42951 /*
42952 ** Mark a data page as writeable. This routine must be called before
42953 ** making changes to a page. The caller must check the return value
42954 ** of this function and be careful not to change any page data unless
42955 ** this routine returns SQLITE_OK.
42956 **
42957 ** The difference between this function and pager_write() is that this
42958 ** function also deals with the special case where 2 or more pages
42959 ** fit on a single disk sector. In this case all co-resident pages
42960 ** must have been written to the journal file before returning.
42961 **
42962 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
42963 ** as appropriate. Otherwise, SQLITE_OK.
42964 */
42965 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
42966   int rc = SQLITE_OK;
42967 
42968   PgHdr *pPg = pDbPage;
42969   Pager *pPager = pPg->pPager;
42970   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
42971 
42972   assert( pPager->eState>=PAGER_WRITER_LOCKED );
42973   assert( pPager->eState!=PAGER_ERROR );
42974   assert( assert_pager_state(pPager) );
42975 
42976   if( nPagePerSector>1 ){
42977     Pgno nPageCount;          /* Total number of pages in database file */
42978     Pgno pg1;                 /* First page of the sector pPg is located on. */
42979     int nPage = 0;            /* Number of pages starting at pg1 to journal */
42980     int ii;                   /* Loop counter */
42981     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
42982 
42983     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
42984     ** a journal header to be written between the pages journaled by
42985     ** this function.
42986     */
42987     assert( !MEMDB );
42988     assert( pPager->doNotSyncSpill==0 );
42989     pPager->doNotSyncSpill++;
42990 
42991     /* This trick assumes that both the page-size and sector-size are
42992     ** an integer power of 2. It sets variable pg1 to the identifier
42993     ** of the first page of the sector pPg is located on.
42994     */
42995     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
42996 
42997     nPageCount = pPager->dbSize;
42998     if( pPg->pgno>nPageCount ){
42999       nPage = (pPg->pgno - pg1)+1;
43000     }else if( (pg1+nPagePerSector-1)>nPageCount ){
43001       nPage = nPageCount+1-pg1;
43002     }else{
43003       nPage = nPagePerSector;
43004     }
43005     assert(nPage>0);
43006     assert(pg1<=pPg->pgno);
43007     assert((pg1+nPage)>pPg->pgno);
43008 
43009     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
43010       Pgno pg = pg1+ii;
43011       PgHdr *pPage;
43012       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
43013         if( pg!=PAGER_MJ_PGNO(pPager) ){
43014           rc = sqlite3PagerGet(pPager, pg, &pPage);
43015           if( rc==SQLITE_OK ){
43016             rc = pager_write(pPage);
43017             if( pPage->flags&PGHDR_NEED_SYNC ){
43018               needSync = 1;
43019             }
43020             sqlite3PagerUnref(pPage);
43021           }
43022         }
43023       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
43024         if( pPage->flags&PGHDR_NEED_SYNC ){
43025           needSync = 1;
43026         }
43027         sqlite3PagerUnref(pPage);
43028       }
43029     }
43030 
43031     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
43032     ** starting at pg1, then it needs to be set for all of them. Because
43033     ** writing to any of these nPage pages may damage the others, the
43034     ** journal file must contain sync()ed copies of all of them
43035     ** before any of them can be written out to the database file.
43036     */
43037     if( rc==SQLITE_OK && needSync ){
43038       assert( !MEMDB );
43039       for(ii=0; ii<nPage; ii++){
43040         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
43041         if( pPage ){
43042           pPage->flags |= PGHDR_NEED_SYNC;
43043           sqlite3PagerUnref(pPage);
43044         }
43045       }
43046     }
43047 
43048     assert( pPager->doNotSyncSpill==1 );
43049     pPager->doNotSyncSpill--;
43050   }else{
43051     rc = pager_write(pDbPage);
43052   }
43053   return rc;
43054 }
43055 
43056 /*
43057 ** Return TRUE if the page given in the argument was previously passed
43058 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
43059 ** to change the content of the page.
43060 */
43061 #ifndef NDEBUG
43062 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
43063   return pPg->flags&PGHDR_DIRTY;
43064 }
43065 #endif
43066 
43067 /*
43068 ** A call to this routine tells the pager that it is not necessary to
43069 ** write the information on page pPg back to the disk, even though
43070 ** that page might be marked as dirty.  This happens, for example, when
43071 ** the page has been added as a leaf of the freelist and so its
43072 ** content no longer matters.
43073 **
43074 ** The overlying software layer calls this routine when all of the data
43075 ** on the given page is unused. The pager marks the page as clean so
43076 ** that it does not get written to disk.
43077 **
43078 ** Tests show that this optimization can quadruple the speed of large
43079 ** DELETE operations.
43080 */
43081 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
43082   Pager *pPager = pPg->pPager;
43083   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
43084     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
43085     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
43086     pPg->flags |= PGHDR_DONT_WRITE;
43087     pager_set_pagehash(pPg);
43088   }
43089 }
43090 
43091 /*
43092 ** This routine is called to increment the value of the database file
43093 ** change-counter, stored as a 4-byte big-endian integer starting at
43094 ** byte offset 24 of the pager file.  The secondary change counter at
43095 ** 92 is also updated, as is the SQLite version number at offset 96.
43096 **
43097 ** But this only happens if the pPager->changeCountDone flag is false.
43098 ** To avoid excess churning of page 1, the update only happens once.
43099 ** See also the pager_write_changecounter() routine that does an
43100 ** unconditional update of the change counters.
43101 **
43102 ** If the isDirectMode flag is zero, then this is done by calling
43103 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
43104 ** page data. In this case the file will be updated when the current
43105 ** transaction is committed.
43106 **
43107 ** The isDirectMode flag may only be non-zero if the library was compiled
43108 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
43109 ** if isDirect is non-zero, then the database file is updated directly
43110 ** by writing an updated version of page 1 using a call to the
43111 ** sqlite3OsWrite() function.
43112 */
43113 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
43114   int rc = SQLITE_OK;
43115 
43116   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43117        || pPager->eState==PAGER_WRITER_DBMOD
43118   );
43119   assert( assert_pager_state(pPager) );
43120 
43121   /* Declare and initialize constant integer 'isDirect'. If the
43122   ** atomic-write optimization is enabled in this build, then isDirect
43123   ** is initialized to the value passed as the isDirectMode parameter
43124   ** to this function. Otherwise, it is always set to zero.
43125   **
43126   ** The idea is that if the atomic-write optimization is not
43127   ** enabled at compile time, the compiler can omit the tests of
43128   ** 'isDirect' below, as well as the block enclosed in the
43129   ** "if( isDirect )" condition.
43130   */
43131 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
43132 # define DIRECT_MODE 0
43133   assert( isDirectMode==0 );
43134   UNUSED_PARAMETER(isDirectMode);
43135 #else
43136 # define DIRECT_MODE isDirectMode
43137 #endif
43138 
43139   if( !pPager->changeCountDone && pPager->dbSize>0 ){
43140     PgHdr *pPgHdr;                /* Reference to page 1 */
43141 
43142     assert( !pPager->tempFile && isOpen(pPager->fd) );
43143 
43144     /* Open page 1 of the file for writing. */
43145     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
43146     assert( pPgHdr==0 || rc==SQLITE_OK );
43147 
43148     /* If page one was fetched successfully, and this function is not
43149     ** operating in direct-mode, make page 1 writable.  When not in
43150     ** direct mode, page 1 is always held in cache and hence the PagerGet()
43151     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
43152     */
43153     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
43154       rc = sqlite3PagerWrite(pPgHdr);
43155     }
43156 
43157     if( rc==SQLITE_OK ){
43158       /* Actually do the update of the change counter */
43159       pager_write_changecounter(pPgHdr);
43160 
43161       /* If running in direct mode, write the contents of page 1 to the file. */
43162       if( DIRECT_MODE ){
43163         const void *zBuf;
43164         assert( pPager->dbFileSize>0 );
43165         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
43166         if( rc==SQLITE_OK ){
43167           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
43168         }
43169         if( rc==SQLITE_OK ){
43170           pPager->changeCountDone = 1;
43171         }
43172       }else{
43173         pPager->changeCountDone = 1;
43174       }
43175     }
43176 
43177     /* Release the page reference. */
43178     sqlite3PagerUnref(pPgHdr);
43179   }
43180   return rc;
43181 }
43182 
43183 /*
43184 ** Sync the database file to disk. This is a no-op for in-memory databases
43185 ** or pages with the Pager.noSync flag set.
43186 **
43187 ** If successful, or if called on a pager for which it is a no-op, this
43188 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
43189 */
43190 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
43191   int rc = SQLITE_OK;
43192   if( !pPager->noSync ){
43193     assert( !MEMDB );
43194     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
43195   }else if( isOpen(pPager->fd) ){
43196     assert( !MEMDB );
43197     sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, (void *)&rc);
43198   }
43199   return rc;
43200 }
43201 
43202 /*
43203 ** This function may only be called while a write-transaction is active in
43204 ** rollback. If the connection is in WAL mode, this call is a no-op.
43205 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
43206 ** the database file, an attempt is made to obtain one.
43207 **
43208 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
43209 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
43210 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
43211 ** returned.
43212 */
43213 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
43214   int rc = SQLITE_OK;
43215   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43216        || pPager->eState==PAGER_WRITER_DBMOD
43217        || pPager->eState==PAGER_WRITER_LOCKED
43218   );
43219   assert( assert_pager_state(pPager) );
43220   if( 0==pagerUseWal(pPager) ){
43221     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43222   }
43223   return rc;
43224 }
43225 
43226 /*
43227 ** Sync the database file for the pager pPager. zMaster points to the name
43228 ** of a master journal file that should be written into the individual
43229 ** journal file. zMaster may be NULL, which is interpreted as no master
43230 ** journal (a single database transaction).
43231 **
43232 ** This routine ensures that:
43233 **
43234 **   * The database file change-counter is updated,
43235 **   * the journal is synced (unless the atomic-write optimization is used),
43236 **   * all dirty pages are written to the database file,
43237 **   * the database file is truncated (if required), and
43238 **   * the database file synced.
43239 **
43240 ** The only thing that remains to commit the transaction is to finalize
43241 ** (delete, truncate or zero the first part of) the journal file (or
43242 ** delete the master journal file if specified).
43243 **
43244 ** Note that if zMaster==NULL, this does not overwrite a previous value
43245 ** passed to an sqlite3PagerCommitPhaseOne() call.
43246 **
43247 ** If the final parameter - noSync - is true, then the database file itself
43248 ** is not synced. The caller must call sqlite3PagerSync() directly to
43249 ** sync the database file before calling CommitPhaseTwo() to delete the
43250 ** journal file in this case.
43251 */
43252 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
43253   Pager *pPager,                  /* Pager object */
43254   const char *zMaster,            /* If not NULL, the master journal name */
43255   int noSync                      /* True to omit the xSync on the db file */
43256 ){
43257   int rc = SQLITE_OK;             /* Return code */
43258 
43259   assert( pPager->eState==PAGER_WRITER_LOCKED
43260        || pPager->eState==PAGER_WRITER_CACHEMOD
43261        || pPager->eState==PAGER_WRITER_DBMOD
43262        || pPager->eState==PAGER_ERROR
43263   );
43264   assert( assert_pager_state(pPager) );
43265 
43266   /* If a prior error occurred, report that error again. */
43267   if( NEVER(pPager->errCode) ) return pPager->errCode;
43268 
43269   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
43270       pPager->zFilename, zMaster, pPager->dbSize));
43271 
43272   /* If no database changes have been made, return early. */
43273   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
43274 
43275   if( MEMDB ){
43276     /* If this is an in-memory db, or no pages have been written to, or this
43277     ** function has already been called, it is mostly a no-op.  However, any
43278     ** backup in progress needs to be restarted.
43279     */
43280     sqlite3BackupRestart(pPager->pBackup);
43281   }else{
43282     if( pagerUseWal(pPager) ){
43283       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
43284       PgHdr *pPageOne = 0;
43285       if( pList==0 ){
43286         /* Must have at least one page for the WAL commit flag.
43287         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
43288         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
43289         pList = pPageOne;
43290         pList->pDirty = 0;
43291       }
43292       assert( rc==SQLITE_OK );
43293       if( ALWAYS(pList) ){
43294         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1,
43295             (pPager->fullSync ? pPager->syncFlags : 0)
43296         );
43297       }
43298       sqlite3PagerUnref(pPageOne);
43299       if( rc==SQLITE_OK ){
43300         sqlite3PcacheCleanAll(pPager->pPCache);
43301       }
43302     }else{
43303       /* The following block updates the change-counter. Exactly how it
43304       ** does this depends on whether or not the atomic-update optimization
43305       ** was enabled at compile time, and if this transaction meets the
43306       ** runtime criteria to use the operation:
43307       **
43308       **    * The file-system supports the atomic-write property for
43309       **      blocks of size page-size, and
43310       **    * This commit is not part of a multi-file transaction, and
43311       **    * Exactly one page has been modified and store in the journal file.
43312       **
43313       ** If the optimization was not enabled at compile time, then the
43314       ** pager_incr_changecounter() function is called to update the change
43315       ** counter in 'indirect-mode'. If the optimization is compiled in but
43316       ** is not applicable to this transaction, call sqlite3JournalCreate()
43317       ** to make sure the journal file has actually been created, then call
43318       ** pager_incr_changecounter() to update the change-counter in indirect
43319       ** mode.
43320       **
43321       ** Otherwise, if the optimization is both enabled and applicable,
43322       ** then call pager_incr_changecounter() to update the change-counter
43323       ** in 'direct' mode. In this case the journal file will never be
43324       ** created for this transaction.
43325       */
43326   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43327       PgHdr *pPg;
43328       assert( isOpen(pPager->jfd)
43329            || pPager->journalMode==PAGER_JOURNALMODE_OFF
43330            || pPager->journalMode==PAGER_JOURNALMODE_WAL
43331       );
43332       if( !zMaster && isOpen(pPager->jfd)
43333        && pPager->journalOff==jrnlBufferSize(pPager)
43334        && pPager->dbSize>=pPager->dbOrigSize
43335        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
43336       ){
43337         /* Update the db file change counter via the direct-write method. The
43338         ** following call will modify the in-memory representation of page 1
43339         ** to include the updated change counter and then write page 1
43340         ** directly to the database file. Because of the atomic-write
43341         ** property of the host file-system, this is safe.
43342         */
43343         rc = pager_incr_changecounter(pPager, 1);
43344       }else{
43345         rc = sqlite3JournalCreate(pPager->jfd);
43346         if( rc==SQLITE_OK ){
43347           rc = pager_incr_changecounter(pPager, 0);
43348         }
43349       }
43350   #else
43351       rc = pager_incr_changecounter(pPager, 0);
43352   #endif
43353       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43354 
43355       /* If this transaction has made the database smaller, then all pages
43356       ** being discarded by the truncation must be written to the journal
43357       ** file. This can only happen in auto-vacuum mode.
43358       **
43359       ** Before reading the pages with page numbers larger than the
43360       ** current value of Pager.dbSize, set dbSize back to the value
43361       ** that it took at the start of the transaction. Otherwise, the
43362       ** calls to sqlite3PagerGet() return zeroed pages instead of
43363       ** reading data from the database file.
43364       */
43365   #ifndef SQLITE_OMIT_AUTOVACUUM
43366       if( pPager->dbSize<pPager->dbOrigSize
43367        && pPager->journalMode!=PAGER_JOURNALMODE_OFF
43368       ){
43369         Pgno i;                                   /* Iterator variable */
43370         const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
43371         const Pgno dbSize = pPager->dbSize;       /* Database image size */
43372         pPager->dbSize = pPager->dbOrigSize;
43373         for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
43374           if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
43375             PgHdr *pPage;             /* Page to journal */
43376             rc = sqlite3PagerGet(pPager, i, &pPage);
43377             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43378             rc = sqlite3PagerWrite(pPage);
43379             sqlite3PagerUnref(pPage);
43380             if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43381           }
43382         }
43383         pPager->dbSize = dbSize;
43384       }
43385   #endif
43386 
43387       /* Write the master journal name into the journal file. If a master
43388       ** journal file name has already been written to the journal file,
43389       ** or if zMaster is NULL (no master journal), then this call is a no-op.
43390       */
43391       rc = writeMasterJournal(pPager, zMaster);
43392       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43393 
43394       /* Sync the journal file and write all dirty pages to the database.
43395       ** If the atomic-update optimization is being used, this sync will not
43396       ** create the journal file or perform any real IO.
43397       **
43398       ** Because the change-counter page was just modified, unless the
43399       ** atomic-update optimization is used it is almost certain that the
43400       ** journal requires a sync here. However, in locking_mode=exclusive
43401       ** on a system under memory pressure it is just possible that this is
43402       ** not the case. In this case it is likely enough that the redundant
43403       ** xSync() call will be changed to a no-op by the OS anyhow.
43404       */
43405       rc = syncJournal(pPager, 0);
43406       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43407 
43408       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
43409       if( rc!=SQLITE_OK ){
43410         assert( rc!=SQLITE_IOERR_BLOCKED );
43411         goto commit_phase_one_exit;
43412       }
43413       sqlite3PcacheCleanAll(pPager->pPCache);
43414 
43415       /* If the file on disk is not the same size as the database image,
43416       ** then use pager_truncate to grow or shrink the file here.
43417       */
43418       if( pPager->dbSize!=pPager->dbFileSize ){
43419         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
43420         assert( pPager->eState==PAGER_WRITER_DBMOD );
43421         rc = pager_truncate(pPager, nNew);
43422         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
43423       }
43424 
43425       /* Finally, sync the database file. */
43426       if( !noSync ){
43427         rc = sqlite3PagerSync(pPager);
43428       }
43429       IOTRACE(("DBSYNC %p\n", pPager))
43430     }
43431   }
43432 
43433 commit_phase_one_exit:
43434   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
43435     pPager->eState = PAGER_WRITER_FINISHED;
43436   }
43437   return rc;
43438 }
43439 
43440 
43441 /*
43442 ** When this function is called, the database file has been completely
43443 ** updated to reflect the changes made by the current transaction and
43444 ** synced to disk. The journal file still exists in the file-system
43445 ** though, and if a failure occurs at this point it will eventually
43446 ** be used as a hot-journal and the current transaction rolled back.
43447 **
43448 ** This function finalizes the journal file, either by deleting,
43449 ** truncating or partially zeroing it, so that it cannot be used
43450 ** for hot-journal rollback. Once this is done the transaction is
43451 ** irrevocably committed.
43452 **
43453 ** If an error occurs, an IO error code is returned and the pager
43454 ** moves into the error state. Otherwise, SQLITE_OK is returned.
43455 */
43456 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
43457   int rc = SQLITE_OK;                  /* Return code */
43458 
43459   /* This routine should not be called if a prior error has occurred.
43460   ** But if (due to a coding error elsewhere in the system) it does get
43461   ** called, just return the same error code without doing anything. */
43462   if( NEVER(pPager->errCode) ) return pPager->errCode;
43463 
43464   assert( pPager->eState==PAGER_WRITER_LOCKED
43465        || pPager->eState==PAGER_WRITER_FINISHED
43466        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
43467   );
43468   assert( assert_pager_state(pPager) );
43469 
43470   /* An optimization. If the database was not actually modified during
43471   ** this transaction, the pager is running in exclusive-mode and is
43472   ** using persistent journals, then this function is a no-op.
43473   **
43474   ** The start of the journal file currently contains a single journal
43475   ** header with the nRec field set to 0. If such a journal is used as
43476   ** a hot-journal during hot-journal rollback, 0 changes will be made
43477   ** to the database file. So there is no need to zero the journal
43478   ** header. Since the pager is in exclusive mode, there is no need
43479   ** to drop any locks either.
43480   */
43481   if( pPager->eState==PAGER_WRITER_LOCKED
43482    && pPager->exclusiveMode
43483    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43484   ){
43485     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
43486     pPager->eState = PAGER_READER;
43487     return SQLITE_OK;
43488   }
43489 
43490   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
43491   rc = pager_end_transaction(pPager, pPager->setMaster);
43492   return pager_error(pPager, rc);
43493 }
43494 
43495 /*
43496 ** If a write transaction is open, then all changes made within the
43497 ** transaction are reverted and the current write-transaction is closed.
43498 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
43499 ** state if an error occurs.
43500 **
43501 ** If the pager is already in PAGER_ERROR state when this function is called,
43502 ** it returns Pager.errCode immediately. No work is performed in this case.
43503 **
43504 ** Otherwise, in rollback mode, this function performs two functions:
43505 **
43506 **   1) It rolls back the journal file, restoring all database file and
43507 **      in-memory cache pages to the state they were in when the transaction
43508 **      was opened, and
43509 **
43510 **   2) It finalizes the journal file, so that it is not used for hot
43511 **      rollback at any point in the future.
43512 **
43513 ** Finalization of the journal file (task 2) is only performed if the
43514 ** rollback is successful.
43515 **
43516 ** In WAL mode, all cache-entries containing data modified within the
43517 ** current transaction are either expelled from the cache or reverted to
43518 ** their pre-transaction state by re-reading data from the database or
43519 ** WAL files. The WAL transaction is then closed.
43520 */
43521 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
43522   int rc = SQLITE_OK;                  /* Return code */
43523   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
43524 
43525   /* PagerRollback() is a no-op if called in READER or OPEN state. If
43526   ** the pager is already in the ERROR state, the rollback is not
43527   ** attempted here. Instead, the error code is returned to the caller.
43528   */
43529   assert( assert_pager_state(pPager) );
43530   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
43531   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
43532 
43533   if( pagerUseWal(pPager) ){
43534     int rc2;
43535     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
43536     rc2 = pager_end_transaction(pPager, pPager->setMaster);
43537     if( rc==SQLITE_OK ) rc = rc2;
43538   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
43539     int eState = pPager->eState;
43540     rc = pager_end_transaction(pPager, 0);
43541     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
43542       /* This can happen using journal_mode=off. Move the pager to the error
43543       ** state to indicate that the contents of the cache may not be trusted.
43544       ** Any active readers will get SQLITE_ABORT.
43545       */
43546       pPager->errCode = SQLITE_ABORT;
43547       pPager->eState = PAGER_ERROR;
43548       return rc;
43549     }
43550   }else{
43551     rc = pager_playback(pPager, 0);
43552   }
43553 
43554   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
43555   assert( rc==SQLITE_OK || rc==SQLITE_FULL || (rc&0xFF)==SQLITE_IOERR );
43556 
43557   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
43558   ** cache. So call pager_error() on the way out to make any error persistent.
43559   */
43560   return pager_error(pPager, rc);
43561 }
43562 
43563 /*
43564 ** Return TRUE if the database file is opened read-only.  Return FALSE
43565 ** if the database is (in theory) writable.
43566 */
43567 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
43568   return pPager->readOnly;
43569 }
43570 
43571 /*
43572 ** Return the number of references to the pager.
43573 */
43574 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
43575   return sqlite3PcacheRefCount(pPager->pPCache);
43576 }
43577 
43578 /*
43579 ** Return the approximate number of bytes of memory currently
43580 ** used by the pager and its associated cache.
43581 */
43582 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
43583   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
43584                                      + 5*sizeof(void*);
43585   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
43586            + sqlite3MallocSize(pPager)
43587            + pPager->pageSize;
43588 }
43589 
43590 /*
43591 ** Return the number of references to the specified page.
43592 */
43593 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
43594   return sqlite3PcachePageRefcount(pPage);
43595 }
43596 
43597 #ifdef SQLITE_TEST
43598 /*
43599 ** This routine is used for testing and analysis only.
43600 */
43601 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
43602   static int a[11];
43603   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
43604   a[1] = sqlite3PcachePagecount(pPager->pPCache);
43605   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
43606   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
43607   a[4] = pPager->eState;
43608   a[5] = pPager->errCode;
43609   a[6] = pPager->nHit;
43610   a[7] = pPager->nMiss;
43611   a[8] = 0;  /* Used to be pPager->nOvfl */
43612   a[9] = pPager->nRead;
43613   a[10] = pPager->nWrite;
43614   return a;
43615 }
43616 #endif
43617 
43618 /*
43619 ** Return true if this is an in-memory pager.
43620 */
43621 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
43622   return MEMDB;
43623 }
43624 
43625 /*
43626 ** Check that there are at least nSavepoint savepoints open. If there are
43627 ** currently less than nSavepoints open, then open one or more savepoints
43628 ** to make up the difference. If the number of savepoints is already
43629 ** equal to nSavepoint, then this function is a no-op.
43630 **
43631 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
43632 ** occurs while opening the sub-journal file, then an IO error code is
43633 ** returned. Otherwise, SQLITE_OK.
43634 */
43635 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
43636   int rc = SQLITE_OK;                       /* Return code */
43637   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
43638 
43639   assert( pPager->eState>=PAGER_WRITER_LOCKED );
43640   assert( assert_pager_state(pPager) );
43641 
43642   if( nSavepoint>nCurrent && pPager->useJournal ){
43643     int ii;                                 /* Iterator variable */
43644     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
43645 
43646     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
43647     ** if the allocation fails. Otherwise, zero the new portion in case a
43648     ** malloc failure occurs while populating it in the for(...) loop below.
43649     */
43650     aNew = (PagerSavepoint *)sqlite3Realloc(
43651         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
43652     );
43653     if( !aNew ){
43654       return SQLITE_NOMEM;
43655     }
43656     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
43657     pPager->aSavepoint = aNew;
43658 
43659     /* Populate the PagerSavepoint structures just allocated. */
43660     for(ii=nCurrent; ii<nSavepoint; ii++){
43661       aNew[ii].nOrig = pPager->dbSize;
43662       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
43663         aNew[ii].iOffset = pPager->journalOff;
43664       }else{
43665         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
43666       }
43667       aNew[ii].iSubRec = pPager->nSubRec;
43668       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
43669       if( !aNew[ii].pInSavepoint ){
43670         return SQLITE_NOMEM;
43671       }
43672       if( pagerUseWal(pPager) ){
43673         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
43674       }
43675       pPager->nSavepoint = ii+1;
43676     }
43677     assert( pPager->nSavepoint==nSavepoint );
43678     assertTruncateConstraint(pPager);
43679   }
43680 
43681   return rc;
43682 }
43683 
43684 /*
43685 ** This function is called to rollback or release (commit) a savepoint.
43686 ** The savepoint to release or rollback need not be the most recently
43687 ** created savepoint.
43688 **
43689 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
43690 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
43691 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
43692 ** that have occurred since the specified savepoint was created.
43693 **
43694 ** The savepoint to rollback or release is identified by parameter
43695 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
43696 ** (the first created). A value of (Pager.nSavepoint-1) means operate
43697 ** on the most recently created savepoint. If iSavepoint is greater than
43698 ** (Pager.nSavepoint-1), then this function is a no-op.
43699 **
43700 ** If a negative value is passed to this function, then the current
43701 ** transaction is rolled back. This is different to calling
43702 ** sqlite3PagerRollback() because this function does not terminate
43703 ** the transaction or unlock the database, it just restores the
43704 ** contents of the database to its original state.
43705 **
43706 ** In any case, all savepoints with an index greater than iSavepoint
43707 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
43708 ** then savepoint iSavepoint is also destroyed.
43709 **
43710 ** This function may return SQLITE_NOMEM if a memory allocation fails,
43711 ** or an IO error code if an IO error occurs while rolling back a
43712 ** savepoint. If no errors occur, SQLITE_OK is returned.
43713 */
43714 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
43715   int rc = pPager->errCode;       /* Return code */
43716 
43717   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
43718   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
43719 
43720   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
43721     int ii;            /* Iterator variable */
43722     int nNew;          /* Number of remaining savepoints after this op. */
43723 
43724     /* Figure out how many savepoints will still be active after this
43725     ** operation. Store this value in nNew. Then free resources associated
43726     ** with any savepoints that are destroyed by this operation.
43727     */
43728     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
43729     for(ii=nNew; ii<pPager->nSavepoint; ii++){
43730       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43731     }
43732     pPager->nSavepoint = nNew;
43733 
43734     /* If this is a release of the outermost savepoint, truncate
43735     ** the sub-journal to zero bytes in size. */
43736     if( op==SAVEPOINT_RELEASE ){
43737       if( nNew==0 && isOpen(pPager->sjfd) ){
43738         /* Only truncate if it is an in-memory sub-journal. */
43739         if( sqlite3IsMemJournal(pPager->sjfd) ){
43740           rc = sqlite3OsTruncate(pPager->sjfd, 0);
43741           assert( rc==SQLITE_OK );
43742         }
43743         pPager->nSubRec = 0;
43744       }
43745     }
43746     /* Else this is a rollback operation, playback the specified savepoint.
43747     ** If this is a temp-file, it is possible that the journal file has
43748     ** not yet been opened. In this case there have been no changes to
43749     ** the database file, so the playback operation can be skipped.
43750     */
43751     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
43752       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
43753       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
43754       assert(rc!=SQLITE_DONE);
43755     }
43756   }
43757 
43758   return rc;
43759 }
43760 
43761 /*
43762 ** Return the full pathname of the database file.
43763 */
43764 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
43765   return pPager->zFilename;
43766 }
43767 
43768 /*
43769 ** Return the VFS structure for the pager.
43770 */
43771 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
43772   return pPager->pVfs;
43773 }
43774 
43775 /*
43776 ** Return the file handle for the database file associated
43777 ** with the pager.  This might return NULL if the file has
43778 ** not yet been opened.
43779 */
43780 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
43781   return pPager->fd;
43782 }
43783 
43784 /*
43785 ** Return the full pathname of the journal file.
43786 */
43787 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
43788   return pPager->zJournal;
43789 }
43790 
43791 /*
43792 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
43793 ** if fsync()s are executed normally.
43794 */
43795 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
43796   return pPager->noSync;
43797 }
43798 
43799 #ifdef SQLITE_HAS_CODEC
43800 /*
43801 ** Set or retrieve the codec for this pager
43802 */
43803 SQLITE_PRIVATE void sqlite3PagerSetCodec(
43804   Pager *pPager,
43805   void *(*xCodec)(void*,void*,Pgno,int),
43806   void (*xCodecSizeChng)(void*,int,int),
43807   void (*xCodecFree)(void*),
43808   void *pCodec
43809 ){
43810   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
43811   pPager->xCodec = pPager->memDb ? 0 : xCodec;
43812   pPager->xCodecSizeChng = xCodecSizeChng;
43813   pPager->xCodecFree = xCodecFree;
43814   pPager->pCodec = pCodec;
43815   pagerReportSize(pPager);
43816 }
43817 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
43818   return pPager->pCodec;
43819 }
43820 #endif
43821 
43822 #ifndef SQLITE_OMIT_AUTOVACUUM
43823 /*
43824 ** Move the page pPg to location pgno in the file.
43825 **
43826 ** There must be no references to the page previously located at
43827 ** pgno (which we call pPgOld) though that page is allowed to be
43828 ** in cache.  If the page previously located at pgno is not already
43829 ** in the rollback journal, it is not put there by by this routine.
43830 **
43831 ** References to the page pPg remain valid. Updating any
43832 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
43833 ** allocated along with the page) is the responsibility of the caller.
43834 **
43835 ** A transaction must be active when this routine is called. It used to be
43836 ** required that a statement transaction was not active, but this restriction
43837 ** has been removed (CREATE INDEX needs to move a page when a statement
43838 ** transaction is active).
43839 **
43840 ** If the fourth argument, isCommit, is non-zero, then this page is being
43841 ** moved as part of a database reorganization just before the transaction
43842 ** is being committed. In this case, it is guaranteed that the database page
43843 ** pPg refers to will not be written to again within this transaction.
43844 **
43845 ** This function may return SQLITE_NOMEM or an IO error code if an error
43846 ** occurs. Otherwise, it returns SQLITE_OK.
43847 */
43848 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
43849   PgHdr *pPgOld;               /* The page being overwritten. */
43850   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
43851   int rc;                      /* Return code */
43852   Pgno origPgno;               /* The original page number */
43853 
43854   assert( pPg->nRef>0 );
43855   assert( pPager->eState==PAGER_WRITER_CACHEMOD
43856        || pPager->eState==PAGER_WRITER_DBMOD
43857   );
43858   assert( assert_pager_state(pPager) );
43859 
43860   /* In order to be able to rollback, an in-memory database must journal
43861   ** the page we are moving from.
43862   */
43863   if( MEMDB ){
43864     rc = sqlite3PagerWrite(pPg);
43865     if( rc ) return rc;
43866   }
43867 
43868   /* If the page being moved is dirty and has not been saved by the latest
43869   ** savepoint, then save the current contents of the page into the
43870   ** sub-journal now. This is required to handle the following scenario:
43871   **
43872   **   BEGIN;
43873   **     <journal page X, then modify it in memory>
43874   **     SAVEPOINT one;
43875   **       <Move page X to location Y>
43876   **     ROLLBACK TO one;
43877   **
43878   ** If page X were not written to the sub-journal here, it would not
43879   ** be possible to restore its contents when the "ROLLBACK TO one"
43880   ** statement were is processed.
43881   **
43882   ** subjournalPage() may need to allocate space to store pPg->pgno into
43883   ** one or more savepoint bitvecs. This is the reason this function
43884   ** may return SQLITE_NOMEM.
43885   */
43886   if( pPg->flags&PGHDR_DIRTY
43887    && subjRequiresPage(pPg)
43888    && SQLITE_OK!=(rc = subjournalPage(pPg))
43889   ){
43890     return rc;
43891   }
43892 
43893   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
43894       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
43895   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
43896 
43897   /* If the journal needs to be sync()ed before page pPg->pgno can
43898   ** be written to, store pPg->pgno in local variable needSyncPgno.
43899   **
43900   ** If the isCommit flag is set, there is no need to remember that
43901   ** the journal needs to be sync()ed before database page pPg->pgno
43902   ** can be written to. The caller has already promised not to write to it.
43903   */
43904   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
43905     needSyncPgno = pPg->pgno;
43906     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
43907     assert( pPg->flags&PGHDR_DIRTY );
43908   }
43909 
43910   /* If the cache contains a page with page-number pgno, remove it
43911   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
43912   ** page pgno before the 'move' operation, it needs to be retained
43913   ** for the page moved there.
43914   */
43915   pPg->flags &= ~PGHDR_NEED_SYNC;
43916   pPgOld = pager_lookup(pPager, pgno);
43917   assert( !pPgOld || pPgOld->nRef==1 );
43918   if( pPgOld ){
43919     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
43920     if( MEMDB ){
43921       /* Do not discard pages from an in-memory database since we might
43922       ** need to rollback later.  Just move the page out of the way. */
43923       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
43924     }else{
43925       sqlite3PcacheDrop(pPgOld);
43926     }
43927   }
43928 
43929   origPgno = pPg->pgno;
43930   sqlite3PcacheMove(pPg, pgno);
43931   sqlite3PcacheMakeDirty(pPg);
43932 
43933   /* For an in-memory database, make sure the original page continues
43934   ** to exist, in case the transaction needs to roll back.  Use pPgOld
43935   ** as the original page since it has already been allocated.
43936   */
43937   if( MEMDB ){
43938     assert( pPgOld );
43939     sqlite3PcacheMove(pPgOld, origPgno);
43940     sqlite3PagerUnref(pPgOld);
43941   }
43942 
43943   if( needSyncPgno ){
43944     /* If needSyncPgno is non-zero, then the journal file needs to be
43945     ** sync()ed before any data is written to database file page needSyncPgno.
43946     ** Currently, no such page exists in the page-cache and the
43947     ** "is journaled" bitvec flag has been set. This needs to be remedied by
43948     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
43949     ** flag.
43950     **
43951     ** If the attempt to load the page into the page-cache fails, (due
43952     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
43953     ** array. Otherwise, if the page is loaded and written again in
43954     ** this transaction, it may be written to the database file before
43955     ** it is synced into the journal file. This way, it may end up in
43956     ** the journal file twice, but that is not a problem.
43957     */
43958     PgHdr *pPgHdr;
43959     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
43960     if( rc!=SQLITE_OK ){
43961       if( needSyncPgno<=pPager->dbOrigSize ){
43962         assert( pPager->pTmpSpace!=0 );
43963         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
43964       }
43965       return rc;
43966     }
43967     pPgHdr->flags |= PGHDR_NEED_SYNC;
43968     sqlite3PcacheMakeDirty(pPgHdr);
43969     sqlite3PagerUnref(pPgHdr);
43970   }
43971 
43972   return SQLITE_OK;
43973 }
43974 #endif
43975 
43976 /*
43977 ** Return a pointer to the data for the specified page.
43978 */
43979 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
43980   assert( pPg->nRef>0 || pPg->pPager->memDb );
43981   return pPg->pData;
43982 }
43983 
43984 /*
43985 ** Return a pointer to the Pager.nExtra bytes of "extra" space
43986 ** allocated along with the specified page.
43987 */
43988 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
43989   return pPg->pExtra;
43990 }
43991 
43992 /*
43993 ** Get/set the locking-mode for this pager. Parameter eMode must be one
43994 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
43995 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
43996 ** the locking-mode is set to the value specified.
43997 **
43998 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
43999 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
44000 ** locking-mode.
44001 */
44002 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
44003   assert( eMode==PAGER_LOCKINGMODE_QUERY
44004             || eMode==PAGER_LOCKINGMODE_NORMAL
44005             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
44006   assert( PAGER_LOCKINGMODE_QUERY<0 );
44007   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
44008   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
44009   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
44010     pPager->exclusiveMode = (u8)eMode;
44011   }
44012   return (int)pPager->exclusiveMode;
44013 }
44014 
44015 /*
44016 ** Set the journal-mode for this pager. Parameter eMode must be one of:
44017 **
44018 **    PAGER_JOURNALMODE_DELETE
44019 **    PAGER_JOURNALMODE_TRUNCATE
44020 **    PAGER_JOURNALMODE_PERSIST
44021 **    PAGER_JOURNALMODE_OFF
44022 **    PAGER_JOURNALMODE_MEMORY
44023 **    PAGER_JOURNALMODE_WAL
44024 **
44025 ** The journalmode is set to the value specified if the change is allowed.
44026 ** The change may be disallowed for the following reasons:
44027 **
44028 **   *  An in-memory database can only have its journal_mode set to _OFF
44029 **      or _MEMORY.
44030 **
44031 **   *  Temporary databases cannot have _WAL journalmode.
44032 **
44033 ** The returned indicate the current (possibly updated) journal-mode.
44034 */
44035 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
44036   u8 eOld = pPager->journalMode;    /* Prior journalmode */
44037 
44038 #ifdef SQLITE_DEBUG
44039   /* The print_pager_state() routine is intended to be used by the debugger
44040   ** only.  We invoke it once here to suppress a compiler warning. */
44041   print_pager_state(pPager);
44042 #endif
44043 
44044 
44045   /* The eMode parameter is always valid */
44046   assert(      eMode==PAGER_JOURNALMODE_DELETE
44047             || eMode==PAGER_JOURNALMODE_TRUNCATE
44048             || eMode==PAGER_JOURNALMODE_PERSIST
44049             || eMode==PAGER_JOURNALMODE_OFF
44050             || eMode==PAGER_JOURNALMODE_WAL
44051             || eMode==PAGER_JOURNALMODE_MEMORY );
44052 
44053   /* This routine is only called from the OP_JournalMode opcode, and
44054   ** the logic there will never allow a temporary file to be changed
44055   ** to WAL mode.
44056   */
44057   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
44058 
44059   /* Do allow the journalmode of an in-memory database to be set to
44060   ** anything other than MEMORY or OFF
44061   */
44062   if( MEMDB ){
44063     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
44064     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
44065       eMode = eOld;
44066     }
44067   }
44068 
44069   if( eMode!=eOld ){
44070 
44071     /* Change the journal mode. */
44072     assert( pPager->eState!=PAGER_ERROR );
44073     pPager->journalMode = (u8)eMode;
44074 
44075     /* When transistioning from TRUNCATE or PERSIST to any other journal
44076     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
44077     ** delete the journal file.
44078     */
44079     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
44080     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
44081     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
44082     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
44083     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
44084     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
44085 
44086     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
44087     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
44088 
44089       /* In this case we would like to delete the journal file. If it is
44090       ** not possible, then that is not a problem. Deleting the journal file
44091       ** here is an optimization only.
44092       **
44093       ** Before deleting the journal file, obtain a RESERVED lock on the
44094       ** database file. This ensures that the journal file is not deleted
44095       ** while it is in use by some other client.
44096       */
44097       sqlite3OsClose(pPager->jfd);
44098       if( pPager->eLock>=RESERVED_LOCK ){
44099         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44100       }else{
44101         int rc = SQLITE_OK;
44102         int state = pPager->eState;
44103         assert( state==PAGER_OPEN || state==PAGER_READER );
44104         if( state==PAGER_OPEN ){
44105           rc = sqlite3PagerSharedLock(pPager);
44106         }
44107         if( pPager->eState==PAGER_READER ){
44108           assert( rc==SQLITE_OK );
44109           rc = pagerLockDb(pPager, RESERVED_LOCK);
44110         }
44111         if( rc==SQLITE_OK ){
44112           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
44113         }
44114         if( rc==SQLITE_OK && state==PAGER_READER ){
44115           pagerUnlockDb(pPager, SHARED_LOCK);
44116         }else if( state==PAGER_OPEN ){
44117           pager_unlock(pPager);
44118         }
44119         assert( state==pPager->eState );
44120       }
44121     }
44122   }
44123 
44124   /* Return the new journal mode */
44125   return (int)pPager->journalMode;
44126 }
44127 
44128 /*
44129 ** Return the current journal mode.
44130 */
44131 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
44132   return (int)pPager->journalMode;
44133 }
44134 
44135 /*
44136 ** Return TRUE if the pager is in a state where it is OK to change the
44137 ** journalmode.  Journalmode changes can only happen when the database
44138 ** is unmodified.
44139 */
44140 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
44141   assert( assert_pager_state(pPager) );
44142   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
44143   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
44144   return 1;
44145 }
44146 
44147 /*
44148 ** Get/set the size-limit used for persistent journal files.
44149 **
44150 ** Setting the size limit to -1 means no limit is enforced.
44151 ** An attempt to set a limit smaller than -1 is a no-op.
44152 */
44153 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
44154   if( iLimit>=-1 ){
44155     pPager->journalSizeLimit = iLimit;
44156     sqlite3WalLimit(pPager->pWal, iLimit);
44157   }
44158   return pPager->journalSizeLimit;
44159 }
44160 
44161 /*
44162 ** Return a pointer to the pPager->pBackup variable. The backup module
44163 ** in backup.c maintains the content of this variable. This module
44164 ** uses it opaquely as an argument to sqlite3BackupRestart() and
44165 ** sqlite3BackupUpdate() only.
44166 */
44167 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
44168   return &pPager->pBackup;
44169 }
44170 
44171 #ifndef SQLITE_OMIT_WAL
44172 /*
44173 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
44174 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
44175 ** or wal_blocking_checkpoint() API functions.
44176 **
44177 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
44178 */
44179 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
44180   int rc = SQLITE_OK;
44181   if( pPager->pWal ){
44182     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
44183         pPager->xBusyHandler, pPager->pBusyHandlerArg,
44184         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
44185         pnLog, pnCkpt
44186     );
44187   }
44188   return rc;
44189 }
44190 
44191 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
44192   return sqlite3WalCallback(pPager->pWal);
44193 }
44194 
44195 /*
44196 ** Return true if the underlying VFS for the given pager supports the
44197 ** primitives necessary for write-ahead logging.
44198 */
44199 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
44200   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
44201   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
44202 }
44203 
44204 /*
44205 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
44206 ** is obtained instead, immediately release it.
44207 */
44208 static int pagerExclusiveLock(Pager *pPager){
44209   int rc;                         /* Return code */
44210 
44211   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
44212   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
44213   if( rc!=SQLITE_OK ){
44214     /* If the attempt to grab the exclusive lock failed, release the
44215     ** pending lock that may have been obtained instead.  */
44216     pagerUnlockDb(pPager, SHARED_LOCK);
44217   }
44218 
44219   return rc;
44220 }
44221 
44222 /*
44223 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
44224 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
44225 ** lock on the database file and use heap-memory to store the wal-index
44226 ** in. Otherwise, use the normal shared-memory.
44227 */
44228 static int pagerOpenWal(Pager *pPager){
44229   int rc = SQLITE_OK;
44230 
44231   assert( pPager->pWal==0 && pPager->tempFile==0 );
44232   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK || pPager->noReadlock);
44233 
44234   /* If the pager is already in exclusive-mode, the WAL module will use
44235   ** heap-memory for the wal-index instead of the VFS shared-memory
44236   ** implementation. Take the exclusive lock now, before opening the WAL
44237   ** file, to make sure this is safe.
44238   */
44239   if( pPager->exclusiveMode ){
44240     rc = pagerExclusiveLock(pPager);
44241   }
44242 
44243   /* Open the connection to the log file. If this operation fails,
44244   ** (e.g. due to malloc() failure), return an error code.
44245   */
44246   if( rc==SQLITE_OK ){
44247     rc = sqlite3WalOpen(pPager->pVfs,
44248         pPager->fd, pPager->zWal, pPager->exclusiveMode,
44249         pPager->journalSizeLimit, &pPager->pWal
44250     );
44251   }
44252 
44253   return rc;
44254 }
44255 
44256 
44257 /*
44258 ** The caller must be holding a SHARED lock on the database file to call
44259 ** this function.
44260 **
44261 ** If the pager passed as the first argument is open on a real database
44262 ** file (not a temp file or an in-memory database), and the WAL file
44263 ** is not already open, make an attempt to open it now. If successful,
44264 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
44265 ** not support the xShmXXX() methods, return an error code. *pbOpen is
44266 ** not modified in either case.
44267 **
44268 ** If the pager is open on a temp-file (or in-memory database), or if
44269 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
44270 ** without doing anything.
44271 */
44272 SQLITE_PRIVATE int sqlite3PagerOpenWal(
44273   Pager *pPager,                  /* Pager object */
44274   int *pbOpen                     /* OUT: Set to true if call is a no-op */
44275 ){
44276   int rc = SQLITE_OK;             /* Return code */
44277 
44278   assert( assert_pager_state(pPager) );
44279   assert( pPager->eState==PAGER_OPEN   || pbOpen );
44280   assert( pPager->eState==PAGER_READER || !pbOpen );
44281   assert( pbOpen==0 || *pbOpen==0 );
44282   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
44283 
44284   if( !pPager->tempFile && !pPager->pWal ){
44285     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
44286 
44287     /* Close any rollback journal previously open */
44288     sqlite3OsClose(pPager->jfd);
44289 
44290     rc = pagerOpenWal(pPager);
44291     if( rc==SQLITE_OK ){
44292       pPager->journalMode = PAGER_JOURNALMODE_WAL;
44293       pPager->eState = PAGER_OPEN;
44294     }
44295   }else{
44296     *pbOpen = 1;
44297   }
44298 
44299   return rc;
44300 }
44301 
44302 /*
44303 ** This function is called to close the connection to the log file prior
44304 ** to switching from WAL to rollback mode.
44305 **
44306 ** Before closing the log file, this function attempts to take an
44307 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
44308 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
44309 ** If successful, the EXCLUSIVE lock is not released before returning.
44310 */
44311 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
44312   int rc = SQLITE_OK;
44313 
44314   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
44315 
44316   /* If the log file is not already open, but does exist in the file-system,
44317   ** it may need to be checkpointed before the connection can switch to
44318   ** rollback mode. Open it now so this can happen.
44319   */
44320   if( !pPager->pWal ){
44321     int logexists = 0;
44322     rc = pagerLockDb(pPager, SHARED_LOCK);
44323     if( rc==SQLITE_OK ){
44324       rc = sqlite3OsAccess(
44325           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
44326       );
44327     }
44328     if( rc==SQLITE_OK && logexists ){
44329       rc = pagerOpenWal(pPager);
44330     }
44331   }
44332 
44333   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
44334   ** the database file, the log and log-summary files will be deleted.
44335   */
44336   if( rc==SQLITE_OK && pPager->pWal ){
44337     rc = pagerExclusiveLock(pPager);
44338     if( rc==SQLITE_OK ){
44339       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
44340                            pPager->pageSize, (u8*)pPager->pTmpSpace);
44341       pPager->pWal = 0;
44342     }
44343   }
44344   return rc;
44345 }
44346 
44347 #ifdef SQLITE_HAS_CODEC
44348 /*
44349 ** This function is called by the wal module when writing page content
44350 ** into the log file.
44351 **
44352 ** This function returns a pointer to a buffer containing the encrypted
44353 ** page content. If a malloc fails, this function may return NULL.
44354 */
44355 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
44356   void *aData = 0;
44357   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
44358   return aData;
44359 }
44360 #endif /* SQLITE_HAS_CODEC */
44361 
44362 #endif /* !SQLITE_OMIT_WAL */
44363 
44364 #endif /* SQLITE_OMIT_DISKIO */
44365 
44366 /************** End of pager.c ***********************************************/
44367 /************** Begin file wal.c *********************************************/
44368 /*
44369 ** 2010 February 1
44370 **
44371 ** The author disclaims copyright to this source code.  In place of
44372 ** a legal notice, here is a blessing:
44373 **
44374 **    May you do good and not evil.
44375 **    May you find forgiveness for yourself and forgive others.
44376 **    May you share freely, never taking more than you give.
44377 **
44378 *************************************************************************
44379 **
44380 ** This file contains the implementation of a write-ahead log (WAL) used in
44381 ** "journal_mode=WAL" mode.
44382 **
44383 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
44384 **
44385 ** A WAL file consists of a header followed by zero or more "frames".
44386 ** Each frame records the revised content of a single page from the
44387 ** database file.  All changes to the database are recorded by writing
44388 ** frames into the WAL.  Transactions commit when a frame is written that
44389 ** contains a commit marker.  A single WAL can and usually does record
44390 ** multiple transactions.  Periodically, the content of the WAL is
44391 ** transferred back into the database file in an operation called a
44392 ** "checkpoint".
44393 **
44394 ** A single WAL file can be used multiple times.  In other words, the
44395 ** WAL can fill up with frames and then be checkpointed and then new
44396 ** frames can overwrite the old ones.  A WAL always grows from beginning
44397 ** toward the end.  Checksums and counters attached to each frame are
44398 ** used to determine which frames within the WAL are valid and which
44399 ** are leftovers from prior checkpoints.
44400 **
44401 ** The WAL header is 32 bytes in size and consists of the following eight
44402 ** big-endian 32-bit unsigned integer values:
44403 **
44404 **     0: Magic number.  0x377f0682 or 0x377f0683
44405 **     4: File format version.  Currently 3007000
44406 **     8: Database page size.  Example: 1024
44407 **    12: Checkpoint sequence number
44408 **    16: Salt-1, random integer incremented with each checkpoint
44409 **    20: Salt-2, a different random integer changing with each ckpt
44410 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
44411 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
44412 **
44413 ** Immediately following the wal-header are zero or more frames. Each
44414 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
44415 ** of page data. The frame-header is six big-endian 32-bit unsigned
44416 ** integer values, as follows:
44417 **
44418 **     0: Page number.
44419 **     4: For commit records, the size of the database image in pages
44420 **        after the commit. For all other records, zero.
44421 **     8: Salt-1 (copied from the header)
44422 **    12: Salt-2 (copied from the header)
44423 **    16: Checksum-1.
44424 **    20: Checksum-2.
44425 **
44426 ** A frame is considered valid if and only if the following conditions are
44427 ** true:
44428 **
44429 **    (1) The salt-1 and salt-2 values in the frame-header match
44430 **        salt values in the wal-header
44431 **
44432 **    (2) The checksum values in the final 8 bytes of the frame-header
44433 **        exactly match the checksum computed consecutively on the
44434 **        WAL header and the first 8 bytes and the content of all frames
44435 **        up to and including the current frame.
44436 **
44437 ** The checksum is computed using 32-bit big-endian integers if the
44438 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
44439 ** is computed using little-endian if the magic number is 0x377f0682.
44440 ** The checksum values are always stored in the frame header in a
44441 ** big-endian format regardless of which byte order is used to compute
44442 ** the checksum.  The checksum is computed by interpreting the input as
44443 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
44444 ** algorithm used for the checksum is as follows:
44445 **
44446 **   for i from 0 to n-1 step 2:
44447 **     s0 += x[i] + s1;
44448 **     s1 += x[i+1] + s0;
44449 **   endfor
44450 **
44451 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
44452 ** in reverse order (the largest fibonacci weight occurs on the first element
44453 ** of the sequence being summed.)  The s1 value spans all 32-bit
44454 ** terms of the sequence whereas s0 omits the final term.
44455 **
44456 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
44457 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
44458 ** The VFS.xSync operations serve as write barriers - all writes launched
44459 ** before the xSync must complete before any write that launches after the
44460 ** xSync begins.
44461 **
44462 ** After each checkpoint, the salt-1 value is incremented and the salt-2
44463 ** value is randomized.  This prevents old and new frames in the WAL from
44464 ** being considered valid at the same time and being checkpointing together
44465 ** following a crash.
44466 **
44467 ** READER ALGORITHM
44468 **
44469 ** To read a page from the database (call it page number P), a reader
44470 ** first checks the WAL to see if it contains page P.  If so, then the
44471 ** last valid instance of page P that is a followed by a commit frame
44472 ** or is a commit frame itself becomes the value read.  If the WAL
44473 ** contains no copies of page P that are valid and which are a commit
44474 ** frame or are followed by a commit frame, then page P is read from
44475 ** the database file.
44476 **
44477 ** To start a read transaction, the reader records the index of the last
44478 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
44479 ** for all subsequent read operations.  New transactions can be appended
44480 ** to the WAL, but as long as the reader uses its original mxFrame value
44481 ** and ignores the newly appended content, it will see a consistent snapshot
44482 ** of the database from a single point in time.  This technique allows
44483 ** multiple concurrent readers to view different versions of the database
44484 ** content simultaneously.
44485 **
44486 ** The reader algorithm in the previous paragraphs works correctly, but
44487 ** because frames for page P can appear anywhere within the WAL, the
44488 ** reader has to scan the entire WAL looking for page P frames.  If the
44489 ** WAL is large (multiple megabytes is typical) that scan can be slow,
44490 ** and read performance suffers.  To overcome this problem, a separate
44491 ** data structure called the wal-index is maintained to expedite the
44492 ** search for frames of a particular page.
44493 **
44494 ** WAL-INDEX FORMAT
44495 **
44496 ** Conceptually, the wal-index is shared memory, though VFS implementations
44497 ** might choose to implement the wal-index using a mmapped file.  Because
44498 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
44499 ** on a network filesystem.  All users of the database must be able to
44500 ** share memory.
44501 **
44502 ** The wal-index is transient.  After a crash, the wal-index can (and should
44503 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
44504 ** to either truncate or zero the header of the wal-index when the last
44505 ** connection to it closes.  Because the wal-index is transient, it can
44506 ** use an architecture-specific format; it does not have to be cross-platform.
44507 ** Hence, unlike the database and WAL file formats which store all values
44508 ** as big endian, the wal-index can store multi-byte values in the native
44509 ** byte order of the host computer.
44510 **
44511 ** The purpose of the wal-index is to answer this question quickly:  Given
44512 ** a page number P, return the index of the last frame for page P in the WAL,
44513 ** or return NULL if there are no frames for page P in the WAL.
44514 **
44515 ** The wal-index consists of a header region, followed by an one or
44516 ** more index blocks.
44517 **
44518 ** The wal-index header contains the total number of frames within the WAL
44519 ** in the the mxFrame field.
44520 **
44521 ** Each index block except for the first contains information on
44522 ** HASHTABLE_NPAGE frames. The first index block contains information on
44523 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
44524 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
44525 ** first index block are the same size as all other index blocks in the
44526 ** wal-index.
44527 **
44528 ** Each index block contains two sections, a page-mapping that contains the
44529 ** database page number associated with each wal frame, and a hash-table
44530 ** that allows readers to query an index block for a specific page number.
44531 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
44532 ** for the first index block) 32-bit page numbers. The first entry in the
44533 ** first index-block contains the database page number corresponding to the
44534 ** first frame in the WAL file. The first entry in the second index block
44535 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
44536 ** the log, and so on.
44537 **
44538 ** The last index block in a wal-index usually contains less than the full
44539 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
44540 ** depending on the contents of the WAL file. This does not change the
44541 ** allocated size of the page-mapping array - the page-mapping array merely
44542 ** contains unused entries.
44543 **
44544 ** Even without using the hash table, the last frame for page P
44545 ** can be found by scanning the page-mapping sections of each index block
44546 ** starting with the last index block and moving toward the first, and
44547 ** within each index block, starting at the end and moving toward the
44548 ** beginning.  The first entry that equals P corresponds to the frame
44549 ** holding the content for that page.
44550 **
44551 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
44552 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
44553 ** hash table for each page number in the mapping section, so the hash
44554 ** table is never more than half full.  The expected number of collisions
44555 ** prior to finding a match is 1.  Each entry of the hash table is an
44556 ** 1-based index of an entry in the mapping section of the same
44557 ** index block.   Let K be the 1-based index of the largest entry in
44558 ** the mapping section.  (For index blocks other than the last, K will
44559 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
44560 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
44561 ** contain a value of 0.
44562 **
44563 ** To look for page P in the hash table, first compute a hash iKey on
44564 ** P as follows:
44565 **
44566 **      iKey = (P * 383) % HASHTABLE_NSLOT
44567 **
44568 ** Then start scanning entries of the hash table, starting with iKey
44569 ** (wrapping around to the beginning when the end of the hash table is
44570 ** reached) until an unused hash slot is found. Let the first unused slot
44571 ** be at index iUnused.  (iUnused might be less than iKey if there was
44572 ** wrap-around.) Because the hash table is never more than half full,
44573 ** the search is guaranteed to eventually hit an unused entry.  Let
44574 ** iMax be the value between iKey and iUnused, closest to iUnused,
44575 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
44576 ** no hash slot such that aHash[i]==p) then page P is not in the
44577 ** current index block.  Otherwise the iMax-th mapping entry of the
44578 ** current index block corresponds to the last entry that references
44579 ** page P.
44580 **
44581 ** A hash search begins with the last index block and moves toward the
44582 ** first index block, looking for entries corresponding to page P.  On
44583 ** average, only two or three slots in each index block need to be
44584 ** examined in order to either find the last entry for page P, or to
44585 ** establish that no such entry exists in the block.  Each index block
44586 ** holds over 4000 entries.  So two or three index blocks are sufficient
44587 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
44588 ** comparisons (on average) suffice to either locate a frame in the
44589 ** WAL or to establish that the frame does not exist in the WAL.  This
44590 ** is much faster than scanning the entire 10MB WAL.
44591 **
44592 ** Note that entries are added in order of increasing K.  Hence, one
44593 ** reader might be using some value K0 and a second reader that started
44594 ** at a later time (after additional transactions were added to the WAL
44595 ** and to the wal-index) might be using a different value K1, where K1>K0.
44596 ** Both readers can use the same hash table and mapping section to get
44597 ** the correct result.  There may be entries in the hash table with
44598 ** K>K0 but to the first reader, those entries will appear to be unused
44599 ** slots in the hash table and so the first reader will get an answer as
44600 ** if no values greater than K0 had ever been inserted into the hash table
44601 ** in the first place - which is what reader one wants.  Meanwhile, the
44602 ** second reader using K1 will see additional values that were inserted
44603 ** later, which is exactly what reader two wants.
44604 **
44605 ** When a rollback occurs, the value of K is decreased. Hash table entries
44606 ** that correspond to frames greater than the new K value are removed
44607 ** from the hash table at this point.
44608 */
44609 #ifndef SQLITE_OMIT_WAL
44610 
44611 
44612 /*
44613 ** Trace output macros
44614 */
44615 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
44616 SQLITE_PRIVATE int sqlite3WalTrace = 0;
44617 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
44618 #else
44619 # define WALTRACE(X)
44620 #endif
44621 
44622 /*
44623 ** The maximum (and only) versions of the wal and wal-index formats
44624 ** that may be interpreted by this version of SQLite.
44625 **
44626 ** If a client begins recovering a WAL file and finds that (a) the checksum
44627 ** values in the wal-header are correct and (b) the version field is not
44628 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
44629 **
44630 ** Similarly, if a client successfully reads a wal-index header (i.e. the
44631 ** checksum test is successful) and finds that the version field is not
44632 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
44633 ** returns SQLITE_CANTOPEN.
44634 */
44635 #define WAL_MAX_VERSION      3007000
44636 #define WALINDEX_MAX_VERSION 3007000
44637 
44638 /*
44639 ** Indices of various locking bytes.   WAL_NREADER is the number
44640 ** of available reader locks and should be at least 3.
44641 */
44642 #define WAL_WRITE_LOCK         0
44643 #define WAL_ALL_BUT_WRITE      1
44644 #define WAL_CKPT_LOCK          1
44645 #define WAL_RECOVER_LOCK       2
44646 #define WAL_READ_LOCK(I)       (3+(I))
44647 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
44648 
44649 
44650 /* Object declarations */
44651 typedef struct WalIndexHdr WalIndexHdr;
44652 typedef struct WalIterator WalIterator;
44653 typedef struct WalCkptInfo WalCkptInfo;
44654 
44655 
44656 /*
44657 ** The following object holds a copy of the wal-index header content.
44658 **
44659 ** The actual header in the wal-index consists of two copies of this
44660 ** object.
44661 **
44662 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
44663 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
44664 ** added in 3.7.1 when support for 64K pages was added.
44665 */
44666 struct WalIndexHdr {
44667   u32 iVersion;                   /* Wal-index version */
44668   u32 unused;                     /* Unused (padding) field */
44669   u32 iChange;                    /* Counter incremented each transaction */
44670   u8 isInit;                      /* 1 when initialized */
44671   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
44672   u16 szPage;                     /* Database page size in bytes. 1==64K */
44673   u32 mxFrame;                    /* Index of last valid frame in the WAL */
44674   u32 nPage;                      /* Size of database in pages */
44675   u32 aFrameCksum[2];             /* Checksum of last frame in log */
44676   u32 aSalt[2];                   /* Two salt values copied from WAL header */
44677   u32 aCksum[2];                  /* Checksum over all prior fields */
44678 };
44679 
44680 /*
44681 ** A copy of the following object occurs in the wal-index immediately
44682 ** following the second copy of the WalIndexHdr.  This object stores
44683 ** information used by checkpoint.
44684 **
44685 ** nBackfill is the number of frames in the WAL that have been written
44686 ** back into the database. (We call the act of moving content from WAL to
44687 ** database "backfilling".)  The nBackfill number is never greater than
44688 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
44689 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
44690 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
44691 ** mxFrame back to zero when the WAL is reset.
44692 **
44693 ** There is one entry in aReadMark[] for each reader lock.  If a reader
44694 ** holds read-lock K, then the value in aReadMark[K] is no greater than
44695 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
44696 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is
44697 ** a special case; its value is never used and it exists as a place-holder
44698 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
44699 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
44700 ** directly from the database.
44701 **
44702 ** The value of aReadMark[K] may only be changed by a thread that
44703 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
44704 ** aReadMark[K] cannot changed while there is a reader is using that mark
44705 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
44706 **
44707 ** The checkpointer may only transfer frames from WAL to database where
44708 ** the frame numbers are less than or equal to every aReadMark[] that is
44709 ** in use (that is, every aReadMark[j] for which there is a corresponding
44710 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
44711 ** largest value and will increase an unused aReadMark[] to mxFrame if there
44712 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
44713 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
44714 ** in the WAL has been backfilled into the database) then new readers
44715 ** will choose aReadMark[0] which has value 0 and hence such reader will
44716 ** get all their all content directly from the database file and ignore
44717 ** the WAL.
44718 **
44719 ** Writers normally append new frames to the end of the WAL.  However,
44720 ** if nBackfill equals mxFrame (meaning that all WAL content has been
44721 ** written back into the database) and if no readers are using the WAL
44722 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
44723 ** the writer will first "reset" the WAL back to the beginning and start
44724 ** writing new content beginning at frame 1.
44725 **
44726 ** We assume that 32-bit loads are atomic and so no locks are needed in
44727 ** order to read from any aReadMark[] entries.
44728 */
44729 struct WalCkptInfo {
44730   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
44731   u32 aReadMark[WAL_NREADER];     /* Reader marks */
44732 };
44733 #define READMARK_NOT_USED  0xffffffff
44734 
44735 
44736 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
44737 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
44738 ** only support mandatory file-locks, we do not read or write data
44739 ** from the region of the file on which locks are applied.
44740 */
44741 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
44742 #define WALINDEX_LOCK_RESERVED 16
44743 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
44744 
44745 /* Size of header before each frame in wal */
44746 #define WAL_FRAME_HDRSIZE 24
44747 
44748 /* Size of write ahead log header, including checksum. */
44749 /* #define WAL_HDRSIZE 24 */
44750 #define WAL_HDRSIZE 32
44751 
44752 /* WAL magic value. Either this value, or the same value with the least
44753 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
44754 ** big-endian format in the first 4 bytes of a WAL file.
44755 **
44756 ** If the LSB is set, then the checksums for each frame within the WAL
44757 ** file are calculated by treating all data as an array of 32-bit
44758 ** big-endian words. Otherwise, they are calculated by interpreting
44759 ** all data as 32-bit little-endian words.
44760 */
44761 #define WAL_MAGIC 0x377f0682
44762 
44763 /*
44764 ** Return the offset of frame iFrame in the write-ahead log file,
44765 ** assuming a database page size of szPage bytes. The offset returned
44766 ** is to the start of the write-ahead log frame-header.
44767 */
44768 #define walFrameOffset(iFrame, szPage) (                               \
44769   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
44770 )
44771 
44772 /*
44773 ** An open write-ahead log file is represented by an instance of the
44774 ** following object.
44775 */
44776 struct Wal {
44777   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
44778   sqlite3_file *pDbFd;       /* File handle for the database file */
44779   sqlite3_file *pWalFd;      /* File handle for WAL file */
44780   u32 iCallback;             /* Value to pass to log callback (or 0) */
44781   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
44782   int nWiData;               /* Size of array apWiData */
44783   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
44784   u32 szPage;                /* Database page size */
44785   i16 readLock;              /* Which read lock is being held.  -1 for none */
44786   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
44787   u8 writeLock;              /* True if in a write transaction */
44788   u8 ckptLock;               /* True if holding a checkpoint lock */
44789   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
44790   WalIndexHdr hdr;           /* Wal-index header for current transaction */
44791   const char *zWalName;      /* Name of WAL file */
44792   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
44793 #ifdef SQLITE_DEBUG
44794   u8 lockError;              /* True if a locking error has occurred */
44795 #endif
44796 };
44797 
44798 /*
44799 ** Candidate values for Wal.exclusiveMode.
44800 */
44801 #define WAL_NORMAL_MODE     0
44802 #define WAL_EXCLUSIVE_MODE  1
44803 #define WAL_HEAPMEMORY_MODE 2
44804 
44805 /*
44806 ** Possible values for WAL.readOnly
44807 */
44808 #define WAL_RDWR        0    /* Normal read/write connection */
44809 #define WAL_RDONLY      1    /* The WAL file is readonly */
44810 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
44811 
44812 /*
44813 ** Each page of the wal-index mapping contains a hash-table made up of
44814 ** an array of HASHTABLE_NSLOT elements of the following type.
44815 */
44816 typedef u16 ht_slot;
44817 
44818 /*
44819 ** This structure is used to implement an iterator that loops through
44820 ** all frames in the WAL in database page order. Where two or more frames
44821 ** correspond to the same database page, the iterator visits only the
44822 ** frame most recently written to the WAL (in other words, the frame with
44823 ** the largest index).
44824 **
44825 ** The internals of this structure are only accessed by:
44826 **
44827 **   walIteratorInit() - Create a new iterator,
44828 **   walIteratorNext() - Step an iterator,
44829 **   walIteratorFree() - Free an iterator.
44830 **
44831 ** This functionality is used by the checkpoint code (see walCheckpoint()).
44832 */
44833 struct WalIterator {
44834   int iPrior;                     /* Last result returned from the iterator */
44835   int nSegment;                   /* Number of entries in aSegment[] */
44836   struct WalSegment {
44837     int iNext;                    /* Next slot in aIndex[] not yet returned */
44838     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
44839     u32 *aPgno;                   /* Array of page numbers. */
44840     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
44841     int iZero;                    /* Frame number associated with aPgno[0] */
44842   } aSegment[1];                  /* One for every 32KB page in the wal-index */
44843 };
44844 
44845 /*
44846 ** Define the parameters of the hash tables in the wal-index file. There
44847 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
44848 ** wal-index.
44849 **
44850 ** Changing any of these constants will alter the wal-index format and
44851 ** create incompatibilities.
44852 */
44853 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
44854 #define HASHTABLE_HASH_1     383                  /* Should be prime */
44855 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
44856 
44857 /*
44858 ** The block of page numbers associated with the first hash-table in a
44859 ** wal-index is smaller than usual. This is so that there is a complete
44860 ** hash-table on each aligned 32KB page of the wal-index.
44861 */
44862 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
44863 
44864 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
44865 #define WALINDEX_PGSZ   (                                         \
44866     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
44867 )
44868 
44869 /*
44870 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
44871 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
44872 ** numbered from zero.
44873 **
44874 ** If this call is successful, *ppPage is set to point to the wal-index
44875 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
44876 ** then an SQLite error code is returned and *ppPage is set to 0.
44877 */
44878 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
44879   int rc = SQLITE_OK;
44880 
44881   /* Enlarge the pWal->apWiData[] array if required */
44882   if( pWal->nWiData<=iPage ){
44883     int nByte = sizeof(u32*)*(iPage+1);
44884     volatile u32 **apNew;
44885     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
44886     if( !apNew ){
44887       *ppPage = 0;
44888       return SQLITE_NOMEM;
44889     }
44890     memset((void*)&apNew[pWal->nWiData], 0,
44891            sizeof(u32*)*(iPage+1-pWal->nWiData));
44892     pWal->apWiData = apNew;
44893     pWal->nWiData = iPage+1;
44894   }
44895 
44896   /* Request a pointer to the required page from the VFS */
44897   if( pWal->apWiData[iPage]==0 ){
44898     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
44899       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
44900       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
44901     }else{
44902       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
44903           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
44904       );
44905       if( rc==SQLITE_READONLY ){
44906         pWal->readOnly |= WAL_SHM_RDONLY;
44907         rc = SQLITE_OK;
44908       }
44909     }
44910   }
44911 
44912   *ppPage = pWal->apWiData[iPage];
44913   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
44914   return rc;
44915 }
44916 
44917 /*
44918 ** Return a pointer to the WalCkptInfo structure in the wal-index.
44919 */
44920 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
44921   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44922   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
44923 }
44924 
44925 /*
44926 ** Return a pointer to the WalIndexHdr structure in the wal-index.
44927 */
44928 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
44929   assert( pWal->nWiData>0 && pWal->apWiData[0] );
44930   return (volatile WalIndexHdr*)pWal->apWiData[0];
44931 }
44932 
44933 /*
44934 ** The argument to this macro must be of type u32. On a little-endian
44935 ** architecture, it returns the u32 value that results from interpreting
44936 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
44937 ** returns the value that would be produced by intepreting the 4 bytes
44938 ** of the input value as a little-endian integer.
44939 */
44940 #define BYTESWAP32(x) ( \
44941     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
44942   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
44943 )
44944 
44945 /*
44946 ** Generate or extend an 8 byte checksum based on the data in
44947 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
44948 ** initial values of 0 and 0 if aIn==NULL).
44949 **
44950 ** The checksum is written back into aOut[] before returning.
44951 **
44952 ** nByte must be a positive multiple of 8.
44953 */
44954 static void walChecksumBytes(
44955   int nativeCksum, /* True for native byte-order, false for non-native */
44956   u8 *a,           /* Content to be checksummed */
44957   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
44958   const u32 *aIn,  /* Initial checksum value input */
44959   u32 *aOut        /* OUT: Final checksum value output */
44960 ){
44961   u32 s1, s2;
44962   u32 *aData = (u32 *)a;
44963   u32 *aEnd = (u32 *)&a[nByte];
44964 
44965   if( aIn ){
44966     s1 = aIn[0];
44967     s2 = aIn[1];
44968   }else{
44969     s1 = s2 = 0;
44970   }
44971 
44972   assert( nByte>=8 );
44973   assert( (nByte&0x00000007)==0 );
44974 
44975   if( nativeCksum ){
44976     do {
44977       s1 += *aData++ + s2;
44978       s2 += *aData++ + s1;
44979     }while( aData<aEnd );
44980   }else{
44981     do {
44982       s1 += BYTESWAP32(aData[0]) + s2;
44983       s2 += BYTESWAP32(aData[1]) + s1;
44984       aData += 2;
44985     }while( aData<aEnd );
44986   }
44987 
44988   aOut[0] = s1;
44989   aOut[1] = s2;
44990 }
44991 
44992 static void walShmBarrier(Wal *pWal){
44993   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
44994     sqlite3OsShmBarrier(pWal->pDbFd);
44995   }
44996 }
44997 
44998 /*
44999 ** Write the header information in pWal->hdr into the wal-index.
45000 **
45001 ** The checksum on pWal->hdr is updated before it is written.
45002 */
45003 static void walIndexWriteHdr(Wal *pWal){
45004   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
45005   const int nCksum = offsetof(WalIndexHdr, aCksum);
45006 
45007   assert( pWal->writeLock );
45008   pWal->hdr.isInit = 1;
45009   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
45010   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
45011   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45012   walShmBarrier(pWal);
45013   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45014 }
45015 
45016 /*
45017 ** This function encodes a single frame header and writes it to a buffer
45018 ** supplied by the caller. A frame-header is made up of a series of
45019 ** 4-byte big-endian integers, as follows:
45020 **
45021 **     0: Page number.
45022 **     4: For commit records, the size of the database image in pages
45023 **        after the commit. For all other records, zero.
45024 **     8: Salt-1 (copied from the wal-header)
45025 **    12: Salt-2 (copied from the wal-header)
45026 **    16: Checksum-1.
45027 **    20: Checksum-2.
45028 */
45029 static void walEncodeFrame(
45030   Wal *pWal,                      /* The write-ahead log */
45031   u32 iPage,                      /* Database page number for frame */
45032   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
45033   u8 *aData,                      /* Pointer to page data */
45034   u8 *aFrame                      /* OUT: Write encoded frame here */
45035 ){
45036   int nativeCksum;                /* True for native byte-order checksums */
45037   u32 *aCksum = pWal->hdr.aFrameCksum;
45038   assert( WAL_FRAME_HDRSIZE==24 );
45039   sqlite3Put4byte(&aFrame[0], iPage);
45040   sqlite3Put4byte(&aFrame[4], nTruncate);
45041   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
45042 
45043   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45044   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45045   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45046 
45047   sqlite3Put4byte(&aFrame[16], aCksum[0]);
45048   sqlite3Put4byte(&aFrame[20], aCksum[1]);
45049 }
45050 
45051 /*
45052 ** Check to see if the frame with header in aFrame[] and content
45053 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
45054 ** *pnTruncate and return true.  Return if the frame is not valid.
45055 */
45056 static int walDecodeFrame(
45057   Wal *pWal,                      /* The write-ahead log */
45058   u32 *piPage,                    /* OUT: Database page number for frame */
45059   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
45060   u8 *aData,                      /* Pointer to page data (for checksum) */
45061   u8 *aFrame                      /* Frame data */
45062 ){
45063   int nativeCksum;                /* True for native byte-order checksums */
45064   u32 *aCksum = pWal->hdr.aFrameCksum;
45065   u32 pgno;                       /* Page number of the frame */
45066   assert( WAL_FRAME_HDRSIZE==24 );
45067 
45068   /* A frame is only valid if the salt values in the frame-header
45069   ** match the salt values in the wal-header.
45070   */
45071   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
45072     return 0;
45073   }
45074 
45075   /* A frame is only valid if the page number is creater than zero.
45076   */
45077   pgno = sqlite3Get4byte(&aFrame[0]);
45078   if( pgno==0 ){
45079     return 0;
45080   }
45081 
45082   /* A frame is only valid if a checksum of the WAL header,
45083   ** all prior frams, the first 16 bytes of this frame-header,
45084   ** and the frame-data matches the checksum in the last 8
45085   ** bytes of this frame-header.
45086   */
45087   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
45088   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
45089   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
45090   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
45091    || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
45092   ){
45093     /* Checksum failed. */
45094     return 0;
45095   }
45096 
45097   /* If we reach this point, the frame is valid.  Return the page number
45098   ** and the new database size.
45099   */
45100   *piPage = pgno;
45101   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
45102   return 1;
45103 }
45104 
45105 
45106 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45107 /*
45108 ** Names of locks.  This routine is used to provide debugging output and is not
45109 ** a part of an ordinary build.
45110 */
45111 static const char *walLockName(int lockIdx){
45112   if( lockIdx==WAL_WRITE_LOCK ){
45113     return "WRITE-LOCK";
45114   }else if( lockIdx==WAL_CKPT_LOCK ){
45115     return "CKPT-LOCK";
45116   }else if( lockIdx==WAL_RECOVER_LOCK ){
45117     return "RECOVER-LOCK";
45118   }else{
45119     static char zName[15];
45120     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
45121                      lockIdx-WAL_READ_LOCK(0));
45122     return zName;
45123   }
45124 }
45125 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
45126 
45127 
45128 /*
45129 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
45130 ** A lock cannot be moved directly between shared and exclusive - it must go
45131 ** through the unlocked state first.
45132 **
45133 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
45134 */
45135 static int walLockShared(Wal *pWal, int lockIdx){
45136   int rc;
45137   if( pWal->exclusiveMode ) return SQLITE_OK;
45138   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45139                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
45140   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
45141             walLockName(lockIdx), rc ? "failed" : "ok"));
45142   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45143   return rc;
45144 }
45145 static void walUnlockShared(Wal *pWal, int lockIdx){
45146   if( pWal->exclusiveMode ) return;
45147   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
45148                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
45149   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
45150 }
45151 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
45152   int rc;
45153   if( pWal->exclusiveMode ) return SQLITE_OK;
45154   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45155                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
45156   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
45157             walLockName(lockIdx), n, rc ? "failed" : "ok"));
45158   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
45159   return rc;
45160 }
45161 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
45162   if( pWal->exclusiveMode ) return;
45163   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
45164                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
45165   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
45166              walLockName(lockIdx), n));
45167 }
45168 
45169 /*
45170 ** Compute a hash on a page number.  The resulting hash value must land
45171 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
45172 ** the hash to the next value in the event of a collision.
45173 */
45174 static int walHash(u32 iPage){
45175   assert( iPage>0 );
45176   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
45177   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
45178 }
45179 static int walNextHash(int iPriorHash){
45180   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
45181 }
45182 
45183 /*
45184 ** Return pointers to the hash table and page number array stored on
45185 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
45186 ** numbered starting from 0.
45187 **
45188 ** Set output variable *paHash to point to the start of the hash table
45189 ** in the wal-index file. Set *piZero to one less than the frame
45190 ** number of the first frame indexed by this hash table. If a
45191 ** slot in the hash table is set to N, it refers to frame number
45192 ** (*piZero+N) in the log.
45193 **
45194 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
45195 ** first frame indexed by the hash table, frame (*piZero+1).
45196 */
45197 static int walHashGet(
45198   Wal *pWal,                      /* WAL handle */
45199   int iHash,                      /* Find the iHash'th table */
45200   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
45201   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
45202   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
45203 ){
45204   int rc;                         /* Return code */
45205   volatile u32 *aPgno;
45206 
45207   rc = walIndexPage(pWal, iHash, &aPgno);
45208   assert( rc==SQLITE_OK || iHash>0 );
45209 
45210   if( rc==SQLITE_OK ){
45211     u32 iZero;
45212     volatile ht_slot *aHash;
45213 
45214     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
45215     if( iHash==0 ){
45216       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
45217       iZero = 0;
45218     }else{
45219       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
45220     }
45221 
45222     *paPgno = &aPgno[-1];
45223     *paHash = aHash;
45224     *piZero = iZero;
45225   }
45226   return rc;
45227 }
45228 
45229 /*
45230 ** Return the number of the wal-index page that contains the hash-table
45231 ** and page-number array that contain entries corresponding to WAL frame
45232 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
45233 ** are numbered starting from 0.
45234 */
45235 static int walFramePage(u32 iFrame){
45236   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
45237   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
45238        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
45239        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
45240        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
45241        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
45242   );
45243   return iHash;
45244 }
45245 
45246 /*
45247 ** Return the page number associated with frame iFrame in this WAL.
45248 */
45249 static u32 walFramePgno(Wal *pWal, u32 iFrame){
45250   int iHash = walFramePage(iFrame);
45251   if( iHash==0 ){
45252     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
45253   }
45254   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
45255 }
45256 
45257 /*
45258 ** Remove entries from the hash table that point to WAL slots greater
45259 ** than pWal->hdr.mxFrame.
45260 **
45261 ** This function is called whenever pWal->hdr.mxFrame is decreased due
45262 ** to a rollback or savepoint.
45263 **
45264 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
45265 ** updated.  Any later hash tables will be automatically cleared when
45266 ** pWal->hdr.mxFrame advances to the point where those hash tables are
45267 ** actually needed.
45268 */
45269 static void walCleanupHash(Wal *pWal){
45270   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
45271   volatile u32 *aPgno = 0;        /* Page number array for hash table */
45272   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
45273   int iLimit = 0;                 /* Zero values greater than this */
45274   int nByte;                      /* Number of bytes to zero in aPgno[] */
45275   int i;                          /* Used to iterate through aHash[] */
45276 
45277   assert( pWal->writeLock );
45278   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
45279   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
45280   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
45281 
45282   if( pWal->hdr.mxFrame==0 ) return;
45283 
45284   /* Obtain pointers to the hash-table and page-number array containing
45285   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
45286   ** that the page said hash-table and array reside on is already mapped.
45287   */
45288   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
45289   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
45290   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
45291 
45292   /* Zero all hash-table entries that correspond to frame numbers greater
45293   ** than pWal->hdr.mxFrame.
45294   */
45295   iLimit = pWal->hdr.mxFrame - iZero;
45296   assert( iLimit>0 );
45297   for(i=0; i<HASHTABLE_NSLOT; i++){
45298     if( aHash[i]>iLimit ){
45299       aHash[i] = 0;
45300     }
45301   }
45302 
45303   /* Zero the entries in the aPgno array that correspond to frames with
45304   ** frame numbers greater than pWal->hdr.mxFrame.
45305   */
45306   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
45307   memset((void *)&aPgno[iLimit+1], 0, nByte);
45308 
45309 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45310   /* Verify that the every entry in the mapping region is still reachable
45311   ** via the hash table even after the cleanup.
45312   */
45313   if( iLimit ){
45314     int i;           /* Loop counter */
45315     int iKey;        /* Hash key */
45316     for(i=1; i<=iLimit; i++){
45317       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45318         if( aHash[iKey]==i ) break;
45319       }
45320       assert( aHash[iKey]==i );
45321     }
45322   }
45323 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45324 }
45325 
45326 
45327 /*
45328 ** Set an entry in the wal-index that will map database page number
45329 ** pPage into WAL frame iFrame.
45330 */
45331 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
45332   int rc;                         /* Return code */
45333   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
45334   volatile u32 *aPgno = 0;        /* Page number array */
45335   volatile ht_slot *aHash = 0;    /* Hash table */
45336 
45337   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
45338 
45339   /* Assuming the wal-index file was successfully mapped, populate the
45340   ** page number array and hash table entry.
45341   */
45342   if( rc==SQLITE_OK ){
45343     int iKey;                     /* Hash table key */
45344     int idx;                      /* Value to write to hash-table slot */
45345     int nCollide;                 /* Number of hash collisions */
45346 
45347     idx = iFrame - iZero;
45348     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
45349 
45350     /* If this is the first entry to be added to this hash-table, zero the
45351     ** entire hash table and aPgno[] array before proceding.
45352     */
45353     if( idx==1 ){
45354       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
45355       memset((void*)&aPgno[1], 0, nByte);
45356     }
45357 
45358     /* If the entry in aPgno[] is already set, then the previous writer
45359     ** must have exited unexpectedly in the middle of a transaction (after
45360     ** writing one or more dirty pages to the WAL to free up memory).
45361     ** Remove the remnants of that writers uncommitted transaction from
45362     ** the hash-table before writing any new entries.
45363     */
45364     if( aPgno[idx] ){
45365       walCleanupHash(pWal);
45366       assert( !aPgno[idx] );
45367     }
45368 
45369     /* Write the aPgno[] array entry and the hash-table slot. */
45370     nCollide = idx;
45371     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
45372       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
45373     }
45374     aPgno[idx] = iPage;
45375     aHash[iKey] = (ht_slot)idx;
45376 
45377 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
45378     /* Verify that the number of entries in the hash table exactly equals
45379     ** the number of entries in the mapping region.
45380     */
45381     {
45382       int i;           /* Loop counter */
45383       int nEntry = 0;  /* Number of entries in the hash table */
45384       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
45385       assert( nEntry==idx );
45386     }
45387 
45388     /* Verify that the every entry in the mapping region is reachable
45389     ** via the hash table.  This turns out to be a really, really expensive
45390     ** thing to check, so only do this occasionally - not on every
45391     ** iteration.
45392     */
45393     if( (idx&0x3ff)==0 ){
45394       int i;           /* Loop counter */
45395       for(i=1; i<=idx; i++){
45396         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
45397           if( aHash[iKey]==i ) break;
45398         }
45399         assert( aHash[iKey]==i );
45400       }
45401     }
45402 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
45403   }
45404 
45405 
45406   return rc;
45407 }
45408 
45409 
45410 /*
45411 ** Recover the wal-index by reading the write-ahead log file.
45412 **
45413 ** This routine first tries to establish an exclusive lock on the
45414 ** wal-index to prevent other threads/processes from doing anything
45415 ** with the WAL or wal-index while recovery is running.  The
45416 ** WAL_RECOVER_LOCK is also held so that other threads will know
45417 ** that this thread is running recovery.  If unable to establish
45418 ** the necessary locks, this routine returns SQLITE_BUSY.
45419 */
45420 static int walIndexRecover(Wal *pWal){
45421   int rc;                         /* Return Code */
45422   i64 nSize;                      /* Size of log file */
45423   u32 aFrameCksum[2] = {0, 0};
45424   int iLock;                      /* Lock offset to lock for checkpoint */
45425   int nLock;                      /* Number of locks to hold */
45426 
45427   /* Obtain an exclusive lock on all byte in the locking range not already
45428   ** locked by the caller. The caller is guaranteed to have locked the
45429   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
45430   ** If successful, the same bytes that are locked here are unlocked before
45431   ** this function returns.
45432   */
45433   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
45434   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
45435   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
45436   assert( pWal->writeLock );
45437   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
45438   nLock = SQLITE_SHM_NLOCK - iLock;
45439   rc = walLockExclusive(pWal, iLock, nLock);
45440   if( rc ){
45441     return rc;
45442   }
45443   WALTRACE(("WAL%p: recovery begin...\n", pWal));
45444 
45445   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
45446 
45447   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
45448   if( rc!=SQLITE_OK ){
45449     goto recovery_error;
45450   }
45451 
45452   if( nSize>WAL_HDRSIZE ){
45453     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
45454     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
45455     int szFrame;                  /* Number of bytes in buffer aFrame[] */
45456     u8 *aData;                    /* Pointer to data part of aFrame buffer */
45457     int iFrame;                   /* Index of last frame read */
45458     i64 iOffset;                  /* Next offset to read from log file */
45459     int szPage;                   /* Page size according to the log */
45460     u32 magic;                    /* Magic value read from WAL header */
45461     u32 version;                  /* Magic value read from WAL header */
45462 
45463     /* Read in the WAL header. */
45464     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
45465     if( rc!=SQLITE_OK ){
45466       goto recovery_error;
45467     }
45468 
45469     /* If the database page size is not a power of two, or is greater than
45470     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
45471     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
45472     ** WAL file.
45473     */
45474     magic = sqlite3Get4byte(&aBuf[0]);
45475     szPage = sqlite3Get4byte(&aBuf[8]);
45476     if( (magic&0xFFFFFFFE)!=WAL_MAGIC
45477      || szPage&(szPage-1)
45478      || szPage>SQLITE_MAX_PAGE_SIZE
45479      || szPage<512
45480     ){
45481       goto finished;
45482     }
45483     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
45484     pWal->szPage = szPage;
45485     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
45486     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
45487 
45488     /* Verify that the WAL header checksum is correct */
45489     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
45490         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
45491     );
45492     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
45493      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
45494     ){
45495       goto finished;
45496     }
45497 
45498     /* Verify that the version number on the WAL format is one that
45499     ** are able to understand */
45500     version = sqlite3Get4byte(&aBuf[4]);
45501     if( version!=WAL_MAX_VERSION ){
45502       rc = SQLITE_CANTOPEN_BKPT;
45503       goto finished;
45504     }
45505 
45506     /* Malloc a buffer to read frames into. */
45507     szFrame = szPage + WAL_FRAME_HDRSIZE;
45508     aFrame = (u8 *)sqlite3_malloc(szFrame);
45509     if( !aFrame ){
45510       rc = SQLITE_NOMEM;
45511       goto recovery_error;
45512     }
45513     aData = &aFrame[WAL_FRAME_HDRSIZE];
45514 
45515     /* Read all frames from the log file. */
45516     iFrame = 0;
45517     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
45518       u32 pgno;                   /* Database page number for frame */
45519       u32 nTruncate;              /* dbsize field from frame header */
45520       int isValid;                /* True if this frame is valid */
45521 
45522       /* Read and decode the next log frame. */
45523       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
45524       if( rc!=SQLITE_OK ) break;
45525       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
45526       if( !isValid ) break;
45527       rc = walIndexAppend(pWal, ++iFrame, pgno);
45528       if( rc!=SQLITE_OK ) break;
45529 
45530       /* If nTruncate is non-zero, this is a commit record. */
45531       if( nTruncate ){
45532         pWal->hdr.mxFrame = iFrame;
45533         pWal->hdr.nPage = nTruncate;
45534         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
45535         testcase( szPage<=32768 );
45536         testcase( szPage>=65536 );
45537         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
45538         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
45539       }
45540     }
45541 
45542     sqlite3_free(aFrame);
45543   }
45544 
45545 finished:
45546   if( rc==SQLITE_OK ){
45547     volatile WalCkptInfo *pInfo;
45548     int i;
45549     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
45550     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
45551     walIndexWriteHdr(pWal);
45552 
45553     /* Reset the checkpoint-header. This is safe because this thread is
45554     ** currently holding locks that exclude all other readers, writers and
45555     ** checkpointers.
45556     */
45557     pInfo = walCkptInfo(pWal);
45558     pInfo->nBackfill = 0;
45559     pInfo->aReadMark[0] = 0;
45560     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
45561 
45562     /* If more than one frame was recovered from the log file, report an
45563     ** event via sqlite3_log(). This is to help with identifying performance
45564     ** problems caused by applications routinely shutting down without
45565     ** checkpointing the log file.
45566     */
45567     if( pWal->hdr.nPage ){
45568       sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
45569           pWal->hdr.nPage, pWal->zWalName
45570       );
45571     }
45572   }
45573 
45574 recovery_error:
45575   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
45576   walUnlockExclusive(pWal, iLock, nLock);
45577   return rc;
45578 }
45579 
45580 /*
45581 ** Close an open wal-index.
45582 */
45583 static void walIndexClose(Wal *pWal, int isDelete){
45584   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45585     int i;
45586     for(i=0; i<pWal->nWiData; i++){
45587       sqlite3_free((void *)pWal->apWiData[i]);
45588       pWal->apWiData[i] = 0;
45589     }
45590   }else{
45591     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
45592   }
45593 }
45594 
45595 /*
45596 ** Open a connection to the WAL file zWalName. The database file must
45597 ** already be opened on connection pDbFd. The buffer that zWalName points
45598 ** to must remain valid for the lifetime of the returned Wal* handle.
45599 **
45600 ** A SHARED lock should be held on the database file when this function
45601 ** is called. The purpose of this SHARED lock is to prevent any other
45602 ** client from unlinking the WAL or wal-index file. If another process
45603 ** were to do this just after this client opened one of these files, the
45604 ** system would be badly broken.
45605 **
45606 ** If the log file is successfully opened, SQLITE_OK is returned and
45607 ** *ppWal is set to point to a new WAL handle. If an error occurs,
45608 ** an SQLite error code is returned and *ppWal is left unmodified.
45609 */
45610 SQLITE_PRIVATE int sqlite3WalOpen(
45611   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
45612   sqlite3_file *pDbFd,            /* The open database file */
45613   const char *zWalName,           /* Name of the WAL file */
45614   int bNoShm,                     /* True to run in heap-memory mode */
45615   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
45616   Wal **ppWal                     /* OUT: Allocated Wal handle */
45617 ){
45618   int rc;                         /* Return Code */
45619   Wal *pRet;                      /* Object to allocate and return */
45620   int flags;                      /* Flags passed to OsOpen() */
45621 
45622   assert( zWalName && zWalName[0] );
45623   assert( pDbFd );
45624 
45625   /* In the amalgamation, the os_unix.c and os_win.c source files come before
45626   ** this source file.  Verify that the #defines of the locking byte offsets
45627   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
45628   */
45629 #ifdef WIN_SHM_BASE
45630   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
45631 #endif
45632 #ifdef UNIX_SHM_BASE
45633   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
45634 #endif
45635 
45636 
45637   /* Allocate an instance of struct Wal to return. */
45638   *ppWal = 0;
45639   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
45640   if( !pRet ){
45641     return SQLITE_NOMEM;
45642   }
45643 
45644   pRet->pVfs = pVfs;
45645   pRet->pWalFd = (sqlite3_file *)&pRet[1];
45646   pRet->pDbFd = pDbFd;
45647   pRet->readLock = -1;
45648   pRet->mxWalSize = mxWalSize;
45649   pRet->zWalName = zWalName;
45650   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
45651 
45652   /* Open file handle on the write-ahead log file. */
45653   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
45654   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
45655   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
45656     pRet->readOnly = WAL_RDONLY;
45657   }
45658 
45659   if( rc!=SQLITE_OK ){
45660     walIndexClose(pRet, 0);
45661     sqlite3OsClose(pRet->pWalFd);
45662     sqlite3_free(pRet);
45663   }else{
45664     *ppWal = pRet;
45665     WALTRACE(("WAL%d: opened\n", pRet));
45666   }
45667   return rc;
45668 }
45669 
45670 /*
45671 ** Change the size to which the WAL file is trucated on each reset.
45672 */
45673 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
45674   if( pWal ) pWal->mxWalSize = iLimit;
45675 }
45676 
45677 /*
45678 ** Find the smallest page number out of all pages held in the WAL that
45679 ** has not been returned by any prior invocation of this method on the
45680 ** same WalIterator object.   Write into *piFrame the frame index where
45681 ** that page was last written into the WAL.  Write into *piPage the page
45682 ** number.
45683 **
45684 ** Return 0 on success.  If there are no pages in the WAL with a page
45685 ** number larger than *piPage, then return 1.
45686 */
45687 static int walIteratorNext(
45688   WalIterator *p,               /* Iterator */
45689   u32 *piPage,                  /* OUT: The page number of the next page */
45690   u32 *piFrame                  /* OUT: Wal frame index of next page */
45691 ){
45692   u32 iMin;                     /* Result pgno must be greater than iMin */
45693   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
45694   int i;                        /* For looping through segments */
45695 
45696   iMin = p->iPrior;
45697   assert( iMin<0xffffffff );
45698   for(i=p->nSegment-1; i>=0; i--){
45699     struct WalSegment *pSegment = &p->aSegment[i];
45700     while( pSegment->iNext<pSegment->nEntry ){
45701       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
45702       if( iPg>iMin ){
45703         if( iPg<iRet ){
45704           iRet = iPg;
45705           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
45706         }
45707         break;
45708       }
45709       pSegment->iNext++;
45710     }
45711   }
45712 
45713   *piPage = p->iPrior = iRet;
45714   return (iRet==0xFFFFFFFF);
45715 }
45716 
45717 /*
45718 ** This function merges two sorted lists into a single sorted list.
45719 **
45720 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
45721 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
45722 ** is guaranteed for all J<K:
45723 **
45724 **        aContent[aLeft[J]] < aContent[aLeft[K]]
45725 **        aContent[aRight[J]] < aContent[aRight[K]]
45726 **
45727 ** This routine overwrites aRight[] with a new (probably longer) sequence
45728 ** of indices such that the aRight[] contains every index that appears in
45729 ** either aLeft[] or the old aRight[] and such that the second condition
45730 ** above is still met.
45731 **
45732 ** The aContent[aLeft[X]] values will be unique for all X.  And the
45733 ** aContent[aRight[X]] values will be unique too.  But there might be
45734 ** one or more combinations of X and Y such that
45735 **
45736 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
45737 **
45738 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
45739 */
45740 static void walMerge(
45741   const u32 *aContent,            /* Pages in wal - keys for the sort */
45742   ht_slot *aLeft,                 /* IN: Left hand input list */
45743   int nLeft,                      /* IN: Elements in array *paLeft */
45744   ht_slot **paRight,              /* IN/OUT: Right hand input list */
45745   int *pnRight,                   /* IN/OUT: Elements in *paRight */
45746   ht_slot *aTmp                   /* Temporary buffer */
45747 ){
45748   int iLeft = 0;                  /* Current index in aLeft */
45749   int iRight = 0;                 /* Current index in aRight */
45750   int iOut = 0;                   /* Current index in output buffer */
45751   int nRight = *pnRight;
45752   ht_slot *aRight = *paRight;
45753 
45754   assert( nLeft>0 && nRight>0 );
45755   while( iRight<nRight || iLeft<nLeft ){
45756     ht_slot logpage;
45757     Pgno dbpage;
45758 
45759     if( (iLeft<nLeft)
45760      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
45761     ){
45762       logpage = aLeft[iLeft++];
45763     }else{
45764       logpage = aRight[iRight++];
45765     }
45766     dbpage = aContent[logpage];
45767 
45768     aTmp[iOut++] = logpage;
45769     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
45770 
45771     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
45772     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
45773   }
45774 
45775   *paRight = aLeft;
45776   *pnRight = iOut;
45777   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
45778 }
45779 
45780 /*
45781 ** Sort the elements in list aList using aContent[] as the sort key.
45782 ** Remove elements with duplicate keys, preferring to keep the
45783 ** larger aList[] values.
45784 **
45785 ** The aList[] entries are indices into aContent[].  The values in
45786 ** aList[] are to be sorted so that for all J<K:
45787 **
45788 **      aContent[aList[J]] < aContent[aList[K]]
45789 **
45790 ** For any X and Y such that
45791 **
45792 **      aContent[aList[X]] == aContent[aList[Y]]
45793 **
45794 ** Keep the larger of the two values aList[X] and aList[Y] and discard
45795 ** the smaller.
45796 */
45797 static void walMergesort(
45798   const u32 *aContent,            /* Pages in wal */
45799   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
45800   ht_slot *aList,                 /* IN/OUT: List to sort */
45801   int *pnList                     /* IN/OUT: Number of elements in aList[] */
45802 ){
45803   struct Sublist {
45804     int nList;                    /* Number of elements in aList */
45805     ht_slot *aList;               /* Pointer to sub-list content */
45806   };
45807 
45808   const int nList = *pnList;      /* Size of input list */
45809   int nMerge = 0;                 /* Number of elements in list aMerge */
45810   ht_slot *aMerge = 0;            /* List to be merged */
45811   int iList;                      /* Index into input list */
45812   int iSub = 0;                   /* Index into aSub array */
45813   struct Sublist aSub[13];        /* Array of sub-lists */
45814 
45815   memset(aSub, 0, sizeof(aSub));
45816   assert( nList<=HASHTABLE_NPAGE && nList>0 );
45817   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
45818 
45819   for(iList=0; iList<nList; iList++){
45820     nMerge = 1;
45821     aMerge = &aList[iList];
45822     for(iSub=0; iList & (1<<iSub); iSub++){
45823       struct Sublist *p = &aSub[iSub];
45824       assert( p->aList && p->nList<=(1<<iSub) );
45825       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
45826       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45827     }
45828     aSub[iSub].aList = aMerge;
45829     aSub[iSub].nList = nMerge;
45830   }
45831 
45832   for(iSub++; iSub<ArraySize(aSub); iSub++){
45833     if( nList & (1<<iSub) ){
45834       struct Sublist *p = &aSub[iSub];
45835       assert( p->nList<=(1<<iSub) );
45836       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
45837       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
45838     }
45839   }
45840   assert( aMerge==aList );
45841   *pnList = nMerge;
45842 
45843 #ifdef SQLITE_DEBUG
45844   {
45845     int i;
45846     for(i=1; i<*pnList; i++){
45847       assert( aContent[aList[i]] > aContent[aList[i-1]] );
45848     }
45849   }
45850 #endif
45851 }
45852 
45853 /*
45854 ** Free an iterator allocated by walIteratorInit().
45855 */
45856 static void walIteratorFree(WalIterator *p){
45857   sqlite3ScratchFree(p);
45858 }
45859 
45860 /*
45861 ** Construct a WalInterator object that can be used to loop over all
45862 ** pages in the WAL in ascending order. The caller must hold the checkpoint
45863 ** lock.
45864 **
45865 ** On success, make *pp point to the newly allocated WalInterator object
45866 ** return SQLITE_OK. Otherwise, return an error code. If this routine
45867 ** returns an error, the value of *pp is undefined.
45868 **
45869 ** The calling routine should invoke walIteratorFree() to destroy the
45870 ** WalIterator object when it has finished with it.
45871 */
45872 static int walIteratorInit(Wal *pWal, WalIterator **pp){
45873   WalIterator *p;                 /* Return value */
45874   int nSegment;                   /* Number of segments to merge */
45875   u32 iLast;                      /* Last frame in log */
45876   int nByte;                      /* Number of bytes to allocate */
45877   int i;                          /* Iterator variable */
45878   ht_slot *aTmp;                  /* Temp space used by merge-sort */
45879   int rc = SQLITE_OK;             /* Return Code */
45880 
45881   /* This routine only runs while holding the checkpoint lock. And
45882   ** it only runs if there is actually content in the log (mxFrame>0).
45883   */
45884   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
45885   iLast = pWal->hdr.mxFrame;
45886 
45887   /* Allocate space for the WalIterator object. */
45888   nSegment = walFramePage(iLast) + 1;
45889   nByte = sizeof(WalIterator)
45890         + (nSegment-1)*sizeof(struct WalSegment)
45891         + iLast*sizeof(ht_slot);
45892   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
45893   if( !p ){
45894     return SQLITE_NOMEM;
45895   }
45896   memset(p, 0, nByte);
45897   p->nSegment = nSegment;
45898 
45899   /* Allocate temporary space used by the merge-sort routine. This block
45900   ** of memory will be freed before this function returns.
45901   */
45902   aTmp = (ht_slot *)sqlite3ScratchMalloc(
45903       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
45904   );
45905   if( !aTmp ){
45906     rc = SQLITE_NOMEM;
45907   }
45908 
45909   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
45910     volatile ht_slot *aHash;
45911     u32 iZero;
45912     volatile u32 *aPgno;
45913 
45914     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
45915     if( rc==SQLITE_OK ){
45916       int j;                      /* Counter variable */
45917       int nEntry;                 /* Number of entries in this segment */
45918       ht_slot *aIndex;            /* Sorted index for this segment */
45919 
45920       aPgno++;
45921       if( (i+1)==nSegment ){
45922         nEntry = (int)(iLast - iZero);
45923       }else{
45924         nEntry = (int)((u32*)aHash - (u32*)aPgno);
45925       }
45926       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
45927       iZero++;
45928 
45929       for(j=0; j<nEntry; j++){
45930         aIndex[j] = (ht_slot)j;
45931       }
45932       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
45933       p->aSegment[i].iZero = iZero;
45934       p->aSegment[i].nEntry = nEntry;
45935       p->aSegment[i].aIndex = aIndex;
45936       p->aSegment[i].aPgno = (u32 *)aPgno;
45937     }
45938   }
45939   sqlite3ScratchFree(aTmp);
45940 
45941   if( rc!=SQLITE_OK ){
45942     walIteratorFree(p);
45943   }
45944   *pp = p;
45945   return rc;
45946 }
45947 
45948 /*
45949 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
45950 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
45951 ** busy-handler function. Invoke it and retry the lock until either the
45952 ** lock is successfully obtained or the busy-handler returns 0.
45953 */
45954 static int walBusyLock(
45955   Wal *pWal,                      /* WAL connection */
45956   int (*xBusy)(void*),            /* Function to call when busy */
45957   void *pBusyArg,                 /* Context argument for xBusyHandler */
45958   int lockIdx,                    /* Offset of first byte to lock */
45959   int n                           /* Number of bytes to lock */
45960 ){
45961   int rc;
45962   do {
45963     rc = walLockExclusive(pWal, lockIdx, n);
45964   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
45965   return rc;
45966 }
45967 
45968 /*
45969 ** The cache of the wal-index header must be valid to call this function.
45970 ** Return the page-size in bytes used by the database.
45971 */
45972 static int walPagesize(Wal *pWal){
45973   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
45974 }
45975 
45976 /*
45977 ** Copy as much content as we can from the WAL back into the database file
45978 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
45979 **
45980 ** The amount of information copies from WAL to database might be limited
45981 ** by active readers.  This routine will never overwrite a database page
45982 ** that a concurrent reader might be using.
45983 **
45984 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
45985 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
45986 ** checkpoints are always run by a background thread or background
45987 ** process, foreground threads will never block on a lengthy fsync call.
45988 **
45989 ** Fsync is called on the WAL before writing content out of the WAL and
45990 ** into the database.  This ensures that if the new content is persistent
45991 ** in the WAL and can be recovered following a power-loss or hard reset.
45992 **
45993 ** Fsync is also called on the database file if (and only if) the entire
45994 ** WAL content is copied into the database file.  This second fsync makes
45995 ** it safe to delete the WAL since the new content will persist in the
45996 ** database file.
45997 **
45998 ** This routine uses and updates the nBackfill field of the wal-index header.
45999 ** This is the only routine tha will increase the value of nBackfill.
46000 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
46001 ** its value.)
46002 **
46003 ** The caller must be holding sufficient locks to ensure that no other
46004 ** checkpoint is running (in any other thread or process) at the same
46005 ** time.
46006 */
46007 static int walCheckpoint(
46008   Wal *pWal,                      /* Wal connection */
46009   int eMode,                      /* One of PASSIVE, FULL or RESTART */
46010   int (*xBusyCall)(void*),        /* Function to call when busy */
46011   void *pBusyArg,                 /* Context argument for xBusyHandler */
46012   int sync_flags,                 /* Flags for OsSync() (or 0) */
46013   u8 *zBuf                        /* Temporary buffer to use */
46014 ){
46015   int rc;                         /* Return code */
46016   int szPage;                     /* Database page-size */
46017   WalIterator *pIter = 0;         /* Wal iterator context */
46018   u32 iDbpage = 0;                /* Next database page to write */
46019   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
46020   u32 mxSafeFrame;                /* Max frame that can be backfilled */
46021   u32 mxPage;                     /* Max database page to write */
46022   int i;                          /* Loop counter */
46023   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
46024   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
46025 
46026   szPage = walPagesize(pWal);
46027   testcase( szPage<=32768 );
46028   testcase( szPage>=65536 );
46029   pInfo = walCkptInfo(pWal);
46030   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
46031 
46032   /* Allocate the iterator */
46033   rc = walIteratorInit(pWal, &pIter);
46034   if( rc!=SQLITE_OK ){
46035     return rc;
46036   }
46037   assert( pIter );
46038 
46039   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
46040 
46041   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
46042   ** safe to write into the database.  Frames beyond mxSafeFrame might
46043   ** overwrite database pages that are in use by active readers and thus
46044   ** cannot be backfilled from the WAL.
46045   */
46046   mxSafeFrame = pWal->hdr.mxFrame;
46047   mxPage = pWal->hdr.nPage;
46048   for(i=1; i<WAL_NREADER; i++){
46049     u32 y = pInfo->aReadMark[i];
46050     if( mxSafeFrame>y ){
46051       assert( y<=pWal->hdr.mxFrame );
46052       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
46053       if( rc==SQLITE_OK ){
46054         pInfo->aReadMark[i] = READMARK_NOT_USED;
46055         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46056       }else if( rc==SQLITE_BUSY ){
46057         mxSafeFrame = y;
46058         xBusy = 0;
46059       }else{
46060         goto walcheckpoint_out;
46061       }
46062     }
46063   }
46064 
46065   if( pInfo->nBackfill<mxSafeFrame
46066    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
46067   ){
46068     i64 nSize;                    /* Current size of database file */
46069     u32 nBackfill = pInfo->nBackfill;
46070 
46071     /* Sync the WAL to disk */
46072     if( sync_flags ){
46073       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
46074     }
46075 
46076     /* If the database file may grow as a result of this checkpoint, hint
46077     ** about the eventual size of the db file to the VFS layer.
46078     */
46079     if( rc==SQLITE_OK ){
46080       i64 nReq = ((i64)mxPage * szPage);
46081       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
46082       if( rc==SQLITE_OK && nSize<nReq ){
46083         sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
46084       }
46085     }
46086 
46087     /* Iterate through the contents of the WAL, copying data to the db file. */
46088     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
46089       i64 iOffset;
46090       assert( walFramePgno(pWal, iFrame)==iDbpage );
46091       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
46092       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
46093       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
46094       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
46095       if( rc!=SQLITE_OK ) break;
46096       iOffset = (iDbpage-1)*(i64)szPage;
46097       testcase( IS_BIG_INT(iOffset) );
46098       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
46099       if( rc!=SQLITE_OK ) break;
46100     }
46101 
46102     /* If work was actually accomplished... */
46103     if( rc==SQLITE_OK ){
46104       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
46105         i64 szDb = pWal->hdr.nPage*(i64)szPage;
46106         testcase( IS_BIG_INT(szDb) );
46107         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
46108         if( rc==SQLITE_OK && sync_flags ){
46109           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
46110         }
46111       }
46112       if( rc==SQLITE_OK ){
46113         pInfo->nBackfill = mxSafeFrame;
46114       }
46115     }
46116 
46117     /* Release the reader lock held while backfilling */
46118     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
46119   }
46120 
46121   if( rc==SQLITE_BUSY ){
46122     /* Reset the return code so as not to report a checkpoint failure
46123     ** just because there are active readers.  */
46124     rc = SQLITE_OK;
46125   }
46126 
46127   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
46128   ** file has been copied into the database file, then block until all
46129   ** readers have finished using the wal file. This ensures that the next
46130   ** process to write to the database restarts the wal file.
46131   */
46132   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
46133     assert( pWal->writeLock );
46134     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
46135       rc = SQLITE_BUSY;
46136     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
46137       assert( mxSafeFrame==pWal->hdr.mxFrame );
46138       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
46139       if( rc==SQLITE_OK ){
46140         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46141       }
46142     }
46143   }
46144 
46145  walcheckpoint_out:
46146   walIteratorFree(pIter);
46147   return rc;
46148 }
46149 
46150 /*
46151 ** Close a connection to a log file.
46152 */
46153 SQLITE_PRIVATE int sqlite3WalClose(
46154   Wal *pWal,                      /* Wal to close */
46155   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
46156   int nBuf,
46157   u8 *zBuf                        /* Buffer of at least nBuf bytes */
46158 ){
46159   int rc = SQLITE_OK;
46160   if( pWal ){
46161     int isDelete = 0;             /* True to unlink wal and wal-index files */
46162 
46163     /* If an EXCLUSIVE lock can be obtained on the database file (using the
46164     ** ordinary, rollback-mode locking methods, this guarantees that the
46165     ** connection associated with this log file is the only connection to
46166     ** the database. In this case checkpoint the database and unlink both
46167     ** the wal and wal-index files.
46168     **
46169     ** The EXCLUSIVE lock is not released before returning.
46170     */
46171     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
46172     if( rc==SQLITE_OK ){
46173       int bPersistWal = -1;
46174       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
46175         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
46176       }
46177       rc = sqlite3WalCheckpoint(
46178           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
46179       );
46180       sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersistWal);
46181       if( rc==SQLITE_OK && bPersistWal!=1 ){
46182         isDelete = 1;
46183       }
46184     }
46185 
46186     walIndexClose(pWal, isDelete);
46187     sqlite3OsClose(pWal->pWalFd);
46188     if( isDelete ){
46189       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
46190     }
46191     WALTRACE(("WAL%p: closed\n", pWal));
46192     sqlite3_free((void *)pWal->apWiData);
46193     sqlite3_free(pWal);
46194   }
46195   return rc;
46196 }
46197 
46198 /*
46199 ** Try to read the wal-index header.  Return 0 on success and 1 if
46200 ** there is a problem.
46201 **
46202 ** The wal-index is in shared memory.  Another thread or process might
46203 ** be writing the header at the same time this procedure is trying to
46204 ** read it, which might result in inconsistency.  A dirty read is detected
46205 ** by verifying that both copies of the header are the same and also by
46206 ** a checksum on the header.
46207 **
46208 ** If and only if the read is consistent and the header is different from
46209 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
46210 ** and *pChanged is set to 1.
46211 **
46212 ** If the checksum cannot be verified return non-zero. If the header
46213 ** is read successfully and the checksum verified, return zero.
46214 */
46215 static int walIndexTryHdr(Wal *pWal, int *pChanged){
46216   u32 aCksum[2];                  /* Checksum on the header content */
46217   WalIndexHdr h1, h2;             /* Two copies of the header content */
46218   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
46219 
46220   /* The first page of the wal-index must be mapped at this point. */
46221   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46222 
46223   /* Read the header. This might happen concurrently with a write to the
46224   ** same area of shared memory on a different CPU in a SMP,
46225   ** meaning it is possible that an inconsistent snapshot is read
46226   ** from the file. If this happens, return non-zero.
46227   **
46228   ** There are two copies of the header at the beginning of the wal-index.
46229   ** When reading, read [0] first then [1].  Writes are in the reverse order.
46230   ** Memory barriers are used to prevent the compiler or the hardware from
46231   ** reordering the reads and writes.
46232   */
46233   aHdr = walIndexHdr(pWal);
46234   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
46235   walShmBarrier(pWal);
46236   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
46237 
46238   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
46239     return 1;   /* Dirty read */
46240   }
46241   if( h1.isInit==0 ){
46242     return 1;   /* Malformed header - probably all zeros */
46243   }
46244   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
46245   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
46246     return 1;   /* Checksum does not match */
46247   }
46248 
46249   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
46250     *pChanged = 1;
46251     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
46252     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46253     testcase( pWal->szPage<=32768 );
46254     testcase( pWal->szPage>=65536 );
46255   }
46256 
46257   /* The header was successfully read. Return zero. */
46258   return 0;
46259 }
46260 
46261 /*
46262 ** Read the wal-index header from the wal-index and into pWal->hdr.
46263 ** If the wal-header appears to be corrupt, try to reconstruct the
46264 ** wal-index from the WAL before returning.
46265 **
46266 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
46267 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
46268 ** to 0.
46269 **
46270 ** If the wal-index header is successfully read, return SQLITE_OK.
46271 ** Otherwise an SQLite error code.
46272 */
46273 static int walIndexReadHdr(Wal *pWal, int *pChanged){
46274   int rc;                         /* Return code */
46275   int badHdr;                     /* True if a header read failed */
46276   volatile u32 *page0;            /* Chunk of wal-index containing header */
46277 
46278   /* Ensure that page 0 of the wal-index (the page that contains the
46279   ** wal-index header) is mapped. Return early if an error occurs here.
46280   */
46281   assert( pChanged );
46282   rc = walIndexPage(pWal, 0, &page0);
46283   if( rc!=SQLITE_OK ){
46284     return rc;
46285   };
46286   assert( page0 || pWal->writeLock==0 );
46287 
46288   /* If the first page of the wal-index has been mapped, try to read the
46289   ** wal-index header immediately, without holding any lock. This usually
46290   ** works, but may fail if the wal-index header is corrupt or currently
46291   ** being modified by another thread or process.
46292   */
46293   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
46294 
46295   /* If the first attempt failed, it might have been due to a race
46296   ** with a writer.  So get a WRITE lock and try again.
46297   */
46298   assert( badHdr==0 || pWal->writeLock==0 );
46299   if( badHdr ){
46300     if( pWal->readOnly & WAL_SHM_RDONLY ){
46301       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
46302         walUnlockShared(pWal, WAL_WRITE_LOCK);
46303         rc = SQLITE_READONLY_RECOVERY;
46304       }
46305     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
46306       pWal->writeLock = 1;
46307       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
46308         badHdr = walIndexTryHdr(pWal, pChanged);
46309         if( badHdr ){
46310           /* If the wal-index header is still malformed even while holding
46311           ** a WRITE lock, it can only mean that the header is corrupted and
46312           ** needs to be reconstructed.  So run recovery to do exactly that.
46313           */
46314           rc = walIndexRecover(pWal);
46315           *pChanged = 1;
46316         }
46317       }
46318       pWal->writeLock = 0;
46319       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46320     }
46321   }
46322 
46323   /* If the header is read successfully, check the version number to make
46324   ** sure the wal-index was not constructed with some future format that
46325   ** this version of SQLite cannot understand.
46326   */
46327   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
46328     rc = SQLITE_CANTOPEN_BKPT;
46329   }
46330 
46331   return rc;
46332 }
46333 
46334 /*
46335 ** This is the value that walTryBeginRead returns when it needs to
46336 ** be retried.
46337 */
46338 #define WAL_RETRY  (-1)
46339 
46340 /*
46341 ** Attempt to start a read transaction.  This might fail due to a race or
46342 ** other transient condition.  When that happens, it returns WAL_RETRY to
46343 ** indicate to the caller that it is safe to retry immediately.
46344 **
46345 ** On success return SQLITE_OK.  On a permanent failure (such an
46346 ** I/O error or an SQLITE_BUSY because another process is running
46347 ** recovery) return a positive error code.
46348 **
46349 ** The useWal parameter is true to force the use of the WAL and disable
46350 ** the case where the WAL is bypassed because it has been completely
46351 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
46352 ** to make a copy of the wal-index header into pWal->hdr.  If the
46353 ** wal-index header has changed, *pChanged is set to 1 (as an indication
46354 ** to the caller that the local paget cache is obsolete and needs to be
46355 ** flushed.)  When useWal==1, the wal-index header is assumed to already
46356 ** be loaded and the pChanged parameter is unused.
46357 **
46358 ** The caller must set the cnt parameter to the number of prior calls to
46359 ** this routine during the current read attempt that returned WAL_RETRY.
46360 ** This routine will start taking more aggressive measures to clear the
46361 ** race conditions after multiple WAL_RETRY returns, and after an excessive
46362 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
46363 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
46364 ** and is not honoring the locking protocol.  There is a vanishingly small
46365 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
46366 ** bad luck when there is lots of contention for the wal-index, but that
46367 ** possibility is so small that it can be safely neglected, we believe.
46368 **
46369 ** On success, this routine obtains a read lock on
46370 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
46371 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
46372 ** that means the Wal does not hold any read lock.  The reader must not
46373 ** access any database page that is modified by a WAL frame up to and
46374 ** including frame number aReadMark[pWal->readLock].  The reader will
46375 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
46376 ** Or if pWal->readLock==0, then the reader will ignore the WAL
46377 ** completely and get all content directly from the database file.
46378 ** If the useWal parameter is 1 then the WAL will never be ignored and
46379 ** this routine will always set pWal->readLock>0 on success.
46380 ** When the read transaction is completed, the caller must release the
46381 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
46382 **
46383 ** This routine uses the nBackfill and aReadMark[] fields of the header
46384 ** to select a particular WAL_READ_LOCK() that strives to let the
46385 ** checkpoint process do as much work as possible.  This routine might
46386 ** update values of the aReadMark[] array in the header, but if it does
46387 ** so it takes care to hold an exclusive lock on the corresponding
46388 ** WAL_READ_LOCK() while changing values.
46389 */
46390 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
46391   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
46392   u32 mxReadMark;                 /* Largest aReadMark[] value */
46393   int mxI;                        /* Index of largest aReadMark[] value */
46394   int i;                          /* Loop counter */
46395   int rc = SQLITE_OK;             /* Return code  */
46396 
46397   assert( pWal->readLock<0 );     /* Not currently locked */
46398 
46399   /* Take steps to avoid spinning forever if there is a protocol error.
46400   **
46401   ** Circumstances that cause a RETRY should only last for the briefest
46402   ** instances of time.  No I/O or other system calls are done while the
46403   ** locks are held, so the locks should not be held for very long. But
46404   ** if we are unlucky, another process that is holding a lock might get
46405   ** paged out or take a page-fault that is time-consuming to resolve,
46406   ** during the few nanoseconds that it is holding the lock.  In that case,
46407   ** it might take longer than normal for the lock to free.
46408   **
46409   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
46410   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
46411   ** is more of a scheduler yield than an actual delay.  But on the 10th
46412   ** an subsequent retries, the delays start becoming longer and longer,
46413   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
46414   ** The total delay time before giving up is less than 1 second.
46415   */
46416   if( cnt>5 ){
46417     int nDelay = 1;                      /* Pause time in microseconds */
46418     if( cnt>100 ){
46419       VVA_ONLY( pWal->lockError = 1; )
46420       return SQLITE_PROTOCOL;
46421     }
46422     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
46423     sqlite3OsSleep(pWal->pVfs, nDelay);
46424   }
46425 
46426   if( !useWal ){
46427     rc = walIndexReadHdr(pWal, pChanged);
46428     if( rc==SQLITE_BUSY ){
46429       /* If there is not a recovery running in another thread or process
46430       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
46431       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
46432       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
46433       ** would be technically correct.  But the race is benign since with
46434       ** WAL_RETRY this routine will be called again and will probably be
46435       ** right on the second iteration.
46436       */
46437       if( pWal->apWiData[0]==0 ){
46438         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
46439         ** We assume this is a transient condition, so return WAL_RETRY. The
46440         ** xShmMap() implementation used by the default unix and win32 VFS
46441         ** modules may return SQLITE_BUSY due to a race condition in the
46442         ** code that determines whether or not the shared-memory region
46443         ** must be zeroed before the requested page is returned.
46444         */
46445         rc = WAL_RETRY;
46446       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
46447         walUnlockShared(pWal, WAL_RECOVER_LOCK);
46448         rc = WAL_RETRY;
46449       }else if( rc==SQLITE_BUSY ){
46450         rc = SQLITE_BUSY_RECOVERY;
46451       }
46452     }
46453     if( rc!=SQLITE_OK ){
46454       return rc;
46455     }
46456   }
46457 
46458   pInfo = walCkptInfo(pWal);
46459   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
46460     /* The WAL has been completely backfilled (or it is empty).
46461     ** and can be safely ignored.
46462     */
46463     rc = walLockShared(pWal, WAL_READ_LOCK(0));
46464     walShmBarrier(pWal);
46465     if( rc==SQLITE_OK ){
46466       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
46467         /* It is not safe to allow the reader to continue here if frames
46468         ** may have been appended to the log before READ_LOCK(0) was obtained.
46469         ** When holding READ_LOCK(0), the reader ignores the entire log file,
46470         ** which implies that the database file contains a trustworthy
46471         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
46472         ** happening, this is usually correct.
46473         **
46474         ** However, if frames have been appended to the log (or if the log
46475         ** is wrapped and written for that matter) before the READ_LOCK(0)
46476         ** is obtained, that is not necessarily true. A checkpointer may
46477         ** have started to backfill the appended frames but crashed before
46478         ** it finished. Leaving a corrupt image in the database file.
46479         */
46480         walUnlockShared(pWal, WAL_READ_LOCK(0));
46481         return WAL_RETRY;
46482       }
46483       pWal->readLock = 0;
46484       return SQLITE_OK;
46485     }else if( rc!=SQLITE_BUSY ){
46486       return rc;
46487     }
46488   }
46489 
46490   /* If we get this far, it means that the reader will want to use
46491   ** the WAL to get at content from recent commits.  The job now is
46492   ** to select one of the aReadMark[] entries that is closest to
46493   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
46494   */
46495   mxReadMark = 0;
46496   mxI = 0;
46497   for(i=1; i<WAL_NREADER; i++){
46498     u32 thisMark = pInfo->aReadMark[i];
46499     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
46500       assert( thisMark!=READMARK_NOT_USED );
46501       mxReadMark = thisMark;
46502       mxI = i;
46503     }
46504   }
46505   /* There was once an "if" here. The extra "{" is to preserve indentation. */
46506   {
46507     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
46508      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
46509     ){
46510       for(i=1; i<WAL_NREADER; i++){
46511         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
46512         if( rc==SQLITE_OK ){
46513           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
46514           mxI = i;
46515           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
46516           break;
46517         }else if( rc!=SQLITE_BUSY ){
46518           return rc;
46519         }
46520       }
46521     }
46522     if( mxI==0 ){
46523       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
46524       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
46525     }
46526 
46527     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
46528     if( rc ){
46529       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
46530     }
46531     /* Now that the read-lock has been obtained, check that neither the
46532     ** value in the aReadMark[] array or the contents of the wal-index
46533     ** header have changed.
46534     **
46535     ** It is necessary to check that the wal-index header did not change
46536     ** between the time it was read and when the shared-lock was obtained
46537     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
46538     ** that the log file may have been wrapped by a writer, or that frames
46539     ** that occur later in the log than pWal->hdr.mxFrame may have been
46540     ** copied into the database by a checkpointer. If either of these things
46541     ** happened, then reading the database with the current value of
46542     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
46543     ** instead.
46544     **
46545     ** This does not guarantee that the copy of the wal-index header is up to
46546     ** date before proceeding. That would not be possible without somehow
46547     ** blocking writers. It only guarantees that a dangerous checkpoint or
46548     ** log-wrap (either of which would require an exclusive lock on
46549     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
46550     */
46551     walShmBarrier(pWal);
46552     if( pInfo->aReadMark[mxI]!=mxReadMark
46553      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
46554     ){
46555       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
46556       return WAL_RETRY;
46557     }else{
46558       assert( mxReadMark<=pWal->hdr.mxFrame );
46559       pWal->readLock = (i16)mxI;
46560     }
46561   }
46562   return rc;
46563 }
46564 
46565 /*
46566 ** Begin a read transaction on the database.
46567 **
46568 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
46569 ** it takes a snapshot of the state of the WAL and wal-index for the current
46570 ** instant in time.  The current thread will continue to use this snapshot.
46571 ** Other threads might append new content to the WAL and wal-index but
46572 ** that extra content is ignored by the current thread.
46573 **
46574 ** If the database contents have changes since the previous read
46575 ** transaction, then *pChanged is set to 1 before returning.  The
46576 ** Pager layer will use this to know that is cache is stale and
46577 ** needs to be flushed.
46578 */
46579 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
46580   int rc;                         /* Return code */
46581   int cnt = 0;                    /* Number of TryBeginRead attempts */
46582 
46583   do{
46584     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
46585   }while( rc==WAL_RETRY );
46586   testcase( (rc&0xff)==SQLITE_BUSY );
46587   testcase( (rc&0xff)==SQLITE_IOERR );
46588   testcase( rc==SQLITE_PROTOCOL );
46589   testcase( rc==SQLITE_OK );
46590   return rc;
46591 }
46592 
46593 /*
46594 ** Finish with a read transaction.  All this does is release the
46595 ** read-lock.
46596 */
46597 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
46598   sqlite3WalEndWriteTransaction(pWal);
46599   if( pWal->readLock>=0 ){
46600     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
46601     pWal->readLock = -1;
46602   }
46603 }
46604 
46605 /*
46606 ** Read a page from the WAL, if it is present in the WAL and if the
46607 ** current read transaction is configured to use the WAL.
46608 **
46609 ** The *pInWal is set to 1 if the requested page is in the WAL and
46610 ** has been loaded.  Or *pInWal is set to 0 if the page was not in
46611 ** the WAL and needs to be read out of the database.
46612 */
46613 SQLITE_PRIVATE int sqlite3WalRead(
46614   Wal *pWal,                      /* WAL handle */
46615   Pgno pgno,                      /* Database page number to read data for */
46616   int *pInWal,                    /* OUT: True if data is read from WAL */
46617   int nOut,                       /* Size of buffer pOut in bytes */
46618   u8 *pOut                        /* Buffer to write page data to */
46619 ){
46620   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
46621   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
46622   int iHash;                      /* Used to loop through N hash tables */
46623 
46624   /* This routine is only be called from within a read transaction. */
46625   assert( pWal->readLock>=0 || pWal->lockError );
46626 
46627   /* If the "last page" field of the wal-index header snapshot is 0, then
46628   ** no data will be read from the wal under any circumstances. Return early
46629   ** in this case as an optimization.  Likewise, if pWal->readLock==0,
46630   ** then the WAL is ignored by the reader so return early, as if the
46631   ** WAL were empty.
46632   */
46633   if( iLast==0 || pWal->readLock==0 ){
46634     *pInWal = 0;
46635     return SQLITE_OK;
46636   }
46637 
46638   /* Search the hash table or tables for an entry matching page number
46639   ** pgno. Each iteration of the following for() loop searches one
46640   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
46641   **
46642   ** This code might run concurrently to the code in walIndexAppend()
46643   ** that adds entries to the wal-index (and possibly to this hash
46644   ** table). This means the value just read from the hash
46645   ** slot (aHash[iKey]) may have been added before or after the
46646   ** current read transaction was opened. Values added after the
46647   ** read transaction was opened may have been written incorrectly -
46648   ** i.e. these slots may contain garbage data. However, we assume
46649   ** that any slots written before the current read transaction was
46650   ** opened remain unmodified.
46651   **
46652   ** For the reasons above, the if(...) condition featured in the inner
46653   ** loop of the following block is more stringent that would be required
46654   ** if we had exclusive access to the hash-table:
46655   **
46656   **   (aPgno[iFrame]==pgno):
46657   **     This condition filters out normal hash-table collisions.
46658   **
46659   **   (iFrame<=iLast):
46660   **     This condition filters out entries that were added to the hash
46661   **     table after the current read-transaction had started.
46662   */
46663   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
46664     volatile ht_slot *aHash;      /* Pointer to hash table */
46665     volatile u32 *aPgno;          /* Pointer to array of page numbers */
46666     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
46667     int iKey;                     /* Hash slot index */
46668     int nCollide;                 /* Number of hash collisions remaining */
46669     int rc;                       /* Error code */
46670 
46671     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
46672     if( rc!=SQLITE_OK ){
46673       return rc;
46674     }
46675     nCollide = HASHTABLE_NSLOT;
46676     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
46677       u32 iFrame = aHash[iKey] + iZero;
46678       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
46679         assert( iFrame>iRead );
46680         iRead = iFrame;
46681       }
46682       if( (nCollide--)==0 ){
46683         return SQLITE_CORRUPT_BKPT;
46684       }
46685     }
46686   }
46687 
46688 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46689   /* If expensive assert() statements are available, do a linear search
46690   ** of the wal-index file content. Make sure the results agree with the
46691   ** result obtained using the hash indexes above.  */
46692   {
46693     u32 iRead2 = 0;
46694     u32 iTest;
46695     for(iTest=iLast; iTest>0; iTest--){
46696       if( walFramePgno(pWal, iTest)==pgno ){
46697         iRead2 = iTest;
46698         break;
46699       }
46700     }
46701     assert( iRead==iRead2 );
46702   }
46703 #endif
46704 
46705   /* If iRead is non-zero, then it is the log frame number that contains the
46706   ** required page. Read and return data from the log file.
46707   */
46708   if( iRead ){
46709     int sz;
46710     i64 iOffset;
46711     sz = pWal->hdr.szPage;
46712     sz = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46713     testcase( sz<=32768 );
46714     testcase( sz>=65536 );
46715     iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
46716     *pInWal = 1;
46717     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
46718     return sqlite3OsRead(pWal->pWalFd, pOut, nOut, iOffset);
46719   }
46720 
46721   *pInWal = 0;
46722   return SQLITE_OK;
46723 }
46724 
46725 
46726 /*
46727 ** Return the size of the database in pages (or zero, if unknown).
46728 */
46729 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
46730   if( pWal && ALWAYS(pWal->readLock>=0) ){
46731     return pWal->hdr.nPage;
46732   }
46733   return 0;
46734 }
46735 
46736 
46737 /*
46738 ** This function starts a write transaction on the WAL.
46739 **
46740 ** A read transaction must have already been started by a prior call
46741 ** to sqlite3WalBeginReadTransaction().
46742 **
46743 ** If another thread or process has written into the database since
46744 ** the read transaction was started, then it is not possible for this
46745 ** thread to write as doing so would cause a fork.  So this routine
46746 ** returns SQLITE_BUSY in that case and no write transaction is started.
46747 **
46748 ** There can only be a single writer active at a time.
46749 */
46750 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
46751   int rc;
46752 
46753   /* Cannot start a write transaction without first holding a read
46754   ** transaction. */
46755   assert( pWal->readLock>=0 );
46756 
46757   if( pWal->readOnly ){
46758     return SQLITE_READONLY;
46759   }
46760 
46761   /* Only one writer allowed at a time.  Get the write lock.  Return
46762   ** SQLITE_BUSY if unable.
46763   */
46764   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
46765   if( rc ){
46766     return rc;
46767   }
46768   pWal->writeLock = 1;
46769 
46770   /* If another connection has written to the database file since the
46771   ** time the read transaction on this connection was started, then
46772   ** the write is disallowed.
46773   */
46774   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
46775     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46776     pWal->writeLock = 0;
46777     rc = SQLITE_BUSY;
46778   }
46779 
46780   return rc;
46781 }
46782 
46783 /*
46784 ** End a write transaction.  The commit has already been done.  This
46785 ** routine merely releases the lock.
46786 */
46787 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
46788   if( pWal->writeLock ){
46789     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
46790     pWal->writeLock = 0;
46791   }
46792   return SQLITE_OK;
46793 }
46794 
46795 /*
46796 ** If any data has been written (but not committed) to the log file, this
46797 ** function moves the write-pointer back to the start of the transaction.
46798 **
46799 ** Additionally, the callback function is invoked for each frame written
46800 ** to the WAL since the start of the transaction. If the callback returns
46801 ** other than SQLITE_OK, it is not invoked again and the error code is
46802 ** returned to the caller.
46803 **
46804 ** Otherwise, if the callback function does not return an error, this
46805 ** function returns SQLITE_OK.
46806 */
46807 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
46808   int rc = SQLITE_OK;
46809   if( ALWAYS(pWal->writeLock) ){
46810     Pgno iMax = pWal->hdr.mxFrame;
46811     Pgno iFrame;
46812 
46813     /* Restore the clients cache of the wal-index header to the state it
46814     ** was in before the client began writing to the database.
46815     */
46816     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
46817 
46818     for(iFrame=pWal->hdr.mxFrame+1;
46819         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
46820         iFrame++
46821     ){
46822       /* This call cannot fail. Unless the page for which the page number
46823       ** is passed as the second argument is (a) in the cache and
46824       ** (b) has an outstanding reference, then xUndo is either a no-op
46825       ** (if (a) is false) or simply expels the page from the cache (if (b)
46826       ** is false).
46827       **
46828       ** If the upper layer is doing a rollback, it is guaranteed that there
46829       ** are no outstanding references to any page other than page 1. And
46830       ** page 1 is never written to the log until the transaction is
46831       ** committed. As a result, the call to xUndo may not fail.
46832       */
46833       assert( walFramePgno(pWal, iFrame)!=1 );
46834       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
46835     }
46836     walCleanupHash(pWal);
46837   }
46838   assert( rc==SQLITE_OK );
46839   return rc;
46840 }
46841 
46842 /*
46843 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
46844 ** values. This function populates the array with values required to
46845 ** "rollback" the write position of the WAL handle back to the current
46846 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
46847 */
46848 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
46849   assert( pWal->writeLock );
46850   aWalData[0] = pWal->hdr.mxFrame;
46851   aWalData[1] = pWal->hdr.aFrameCksum[0];
46852   aWalData[2] = pWal->hdr.aFrameCksum[1];
46853   aWalData[3] = pWal->nCkpt;
46854 }
46855 
46856 /*
46857 ** Move the write position of the WAL back to the point identified by
46858 ** the values in the aWalData[] array. aWalData must point to an array
46859 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
46860 ** by a call to WalSavepoint().
46861 */
46862 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
46863   int rc = SQLITE_OK;
46864 
46865   assert( pWal->writeLock );
46866   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
46867 
46868   if( aWalData[3]!=pWal->nCkpt ){
46869     /* This savepoint was opened immediately after the write-transaction
46870     ** was started. Right after that, the writer decided to wrap around
46871     ** to the start of the log. Update the savepoint values to match.
46872     */
46873     aWalData[0] = 0;
46874     aWalData[3] = pWal->nCkpt;
46875   }
46876 
46877   if( aWalData[0]<pWal->hdr.mxFrame ){
46878     pWal->hdr.mxFrame = aWalData[0];
46879     pWal->hdr.aFrameCksum[0] = aWalData[1];
46880     pWal->hdr.aFrameCksum[1] = aWalData[2];
46881     walCleanupHash(pWal);
46882   }
46883 
46884   return rc;
46885 }
46886 
46887 /*
46888 ** This function is called just before writing a set of frames to the log
46889 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
46890 ** to the current log file, it is possible to overwrite the start of the
46891 ** existing log file with the new frames (i.e. "reset" the log). If so,
46892 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
46893 ** unchanged.
46894 **
46895 ** SQLITE_OK is returned if no error is encountered (regardless of whether
46896 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
46897 ** if an error occurs.
46898 */
46899 static int walRestartLog(Wal *pWal){
46900   int rc = SQLITE_OK;
46901   int cnt;
46902 
46903   if( pWal->readLock==0 ){
46904     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
46905     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
46906     if( pInfo->nBackfill>0 ){
46907       u32 salt1;
46908       sqlite3_randomness(4, &salt1);
46909       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46910       if( rc==SQLITE_OK ){
46911         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
46912         ** readers are currently using the WAL), then the transactions
46913         ** frames will overwrite the start of the existing log. Update the
46914         ** wal-index header to reflect this.
46915         **
46916         ** In theory it would be Ok to update the cache of the header only
46917         ** at this point. But updating the actual wal-index header is also
46918         ** safe and means there is no special case for sqlite3WalUndo()
46919         ** to handle if this transaction is rolled back.
46920         */
46921         int i;                    /* Loop counter */
46922         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
46923 
46924         /* Limit the size of WAL file if the journal_size_limit PRAGMA is
46925         ** set to a non-negative value.  Log errors encountered
46926         ** during the truncation attempt. */
46927         if( pWal->mxWalSize>=0 ){
46928           i64 sz;
46929           int rx;
46930           sqlite3BeginBenignMalloc();
46931           rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
46932           if( rx==SQLITE_OK && (sz > pWal->mxWalSize) ){
46933             rx = sqlite3OsTruncate(pWal->pWalFd, pWal->mxWalSize);
46934           }
46935           sqlite3EndBenignMalloc();
46936           if( rx ){
46937             sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
46938           }
46939         }
46940 
46941         pWal->nCkpt++;
46942         pWal->hdr.mxFrame = 0;
46943         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
46944         aSalt[1] = salt1;
46945         walIndexWriteHdr(pWal);
46946         pInfo->nBackfill = 0;
46947         for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46948         assert( pInfo->aReadMark[0]==0 );
46949         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
46950       }else if( rc!=SQLITE_BUSY ){
46951         return rc;
46952       }
46953     }
46954     walUnlockShared(pWal, WAL_READ_LOCK(0));
46955     pWal->readLock = -1;
46956     cnt = 0;
46957     do{
46958       int notUsed;
46959       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
46960     }while( rc==WAL_RETRY );
46961     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
46962     testcase( (rc&0xff)==SQLITE_IOERR );
46963     testcase( rc==SQLITE_PROTOCOL );
46964     testcase( rc==SQLITE_OK );
46965   }
46966   return rc;
46967 }
46968 
46969 /*
46970 ** Write a set of frames to the log. The caller must hold the write-lock
46971 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
46972 */
46973 SQLITE_PRIVATE int sqlite3WalFrames(
46974   Wal *pWal,                      /* Wal handle to write to */
46975   int szPage,                     /* Database page-size in bytes */
46976   PgHdr *pList,                   /* List of dirty pages to write */
46977   Pgno nTruncate,                 /* Database size after this commit */
46978   int isCommit,                   /* True if this is a commit */
46979   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
46980 ){
46981   int rc;                         /* Used to catch return codes */
46982   u32 iFrame;                     /* Next frame address */
46983   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
46984   PgHdr *p;                       /* Iterator to run through pList with. */
46985   PgHdr *pLast = 0;               /* Last frame in list */
46986   int nLast = 0;                  /* Number of extra copies of last page */
46987 
46988   assert( pList );
46989   assert( pWal->writeLock );
46990 
46991 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46992   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
46993     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
46994               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
46995   }
46996 #endif
46997 
46998   /* See if it is possible to write these frames into the start of the
46999   ** log file, instead of appending to it at pWal->hdr.mxFrame.
47000   */
47001   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
47002     return rc;
47003   }
47004 
47005   /* If this is the first frame written into the log, write the WAL
47006   ** header to the start of the WAL file. See comments at the top of
47007   ** this source file for a description of the WAL header format.
47008   */
47009   iFrame = pWal->hdr.mxFrame;
47010   if( iFrame==0 ){
47011     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
47012     u32 aCksum[2];                /* Checksum for wal-header */
47013 
47014     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
47015     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
47016     sqlite3Put4byte(&aWalHdr[8], szPage);
47017     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
47018     sqlite3_randomness(8, pWal->hdr.aSalt);
47019     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
47020     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
47021     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
47022     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
47023 
47024     pWal->szPage = szPage;
47025     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
47026     pWal->hdr.aFrameCksum[0] = aCksum[0];
47027     pWal->hdr.aFrameCksum[1] = aCksum[1];
47028 
47029     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
47030     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
47031     if( rc!=SQLITE_OK ){
47032       return rc;
47033     }
47034   }
47035   assert( (int)pWal->szPage==szPage );
47036 
47037   /* Write the log file. */
47038   for(p=pList; p; p=p->pDirty){
47039     u32 nDbsize;                  /* Db-size field for frame header */
47040     i64 iOffset;                  /* Write offset in log file */
47041     void *pData;
47042 
47043     iOffset = walFrameOffset(++iFrame, szPage);
47044     /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47045 
47046     /* Populate and write the frame header */
47047     nDbsize = (isCommit && p->pDirty==0) ? nTruncate : 0;
47048 #if defined(SQLITE_HAS_CODEC)
47049     if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
47050 #else
47051     pData = p->pData;
47052 #endif
47053     walEncodeFrame(pWal, p->pgno, nDbsize, pData, aFrame);
47054     rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
47055     if( rc!=SQLITE_OK ){
47056       return rc;
47057     }
47058 
47059     /* Write the page data */
47060     rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset+sizeof(aFrame));
47061     if( rc!=SQLITE_OK ){
47062       return rc;
47063     }
47064     pLast = p;
47065   }
47066 
47067   /* Sync the log file if the 'isSync' flag was specified. */
47068   if( sync_flags ){
47069     i64 iSegment = sqlite3OsSectorSize(pWal->pWalFd);
47070     i64 iOffset = walFrameOffset(iFrame+1, szPage);
47071 
47072     assert( isCommit );
47073     assert( iSegment>0 );
47074 
47075     iSegment = (((iOffset+iSegment-1)/iSegment) * iSegment);
47076     while( iOffset<iSegment ){
47077       void *pData;
47078 #if defined(SQLITE_HAS_CODEC)
47079       if( (pData = sqlite3PagerCodec(pLast))==0 ) return SQLITE_NOMEM;
47080 #else
47081       pData = pLast->pData;
47082 #endif
47083       walEncodeFrame(pWal, pLast->pgno, nTruncate, pData, aFrame);
47084       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47085       rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOffset);
47086       if( rc!=SQLITE_OK ){
47087         return rc;
47088       }
47089       iOffset += WAL_FRAME_HDRSIZE;
47090       rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOffset);
47091       if( rc!=SQLITE_OK ){
47092         return rc;
47093       }
47094       nLast++;
47095       iOffset += szPage;
47096     }
47097 
47098     rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47099   }
47100 
47101   /* Append data to the wal-index. It is not necessary to lock the
47102   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
47103   ** guarantees that there are no other writers, and no data that may
47104   ** be in use by existing readers is being overwritten.
47105   */
47106   iFrame = pWal->hdr.mxFrame;
47107   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
47108     iFrame++;
47109     rc = walIndexAppend(pWal, iFrame, p->pgno);
47110   }
47111   while( nLast>0 && rc==SQLITE_OK ){
47112     iFrame++;
47113     nLast--;
47114     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
47115   }
47116 
47117   if( rc==SQLITE_OK ){
47118     /* Update the private copy of the header. */
47119     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
47120     testcase( szPage<=32768 );
47121     testcase( szPage>=65536 );
47122     pWal->hdr.mxFrame = iFrame;
47123     if( isCommit ){
47124       pWal->hdr.iChange++;
47125       pWal->hdr.nPage = nTruncate;
47126     }
47127     /* If this is a commit, update the wal-index header too. */
47128     if( isCommit ){
47129       walIndexWriteHdr(pWal);
47130       pWal->iCallback = iFrame;
47131     }
47132   }
47133 
47134   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
47135   return rc;
47136 }
47137 
47138 /*
47139 ** This routine is called to implement sqlite3_wal_checkpoint() and
47140 ** related interfaces.
47141 **
47142 ** Obtain a CHECKPOINT lock and then backfill as much information as
47143 ** we can from WAL into the database.
47144 **
47145 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
47146 ** callback. In this case this function runs a blocking checkpoint.
47147 */
47148 SQLITE_PRIVATE int sqlite3WalCheckpoint(
47149   Wal *pWal,                      /* Wal connection */
47150   int eMode,                      /* PASSIVE, FULL or RESTART */
47151   int (*xBusy)(void*),            /* Function to call when busy */
47152   void *pBusyArg,                 /* Context argument for xBusyHandler */
47153   int sync_flags,                 /* Flags to sync db file with (or 0) */
47154   int nBuf,                       /* Size of temporary buffer */
47155   u8 *zBuf,                       /* Temporary buffer to use */
47156   int *pnLog,                     /* OUT: Number of frames in WAL */
47157   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
47158 ){
47159   int rc;                         /* Return code */
47160   int isChanged = 0;              /* True if a new wal-index header is loaded */
47161   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
47162 
47163   assert( pWal->ckptLock==0 );
47164   assert( pWal->writeLock==0 );
47165 
47166   if( pWal->readOnly ) return SQLITE_READONLY;
47167   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
47168   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
47169   if( rc ){
47170     /* Usually this is SQLITE_BUSY meaning that another thread or process
47171     ** is already running a checkpoint, or maybe a recovery.  But it might
47172     ** also be SQLITE_IOERR. */
47173     return rc;
47174   }
47175   pWal->ckptLock = 1;
47176 
47177   /* If this is a blocking-checkpoint, then obtain the write-lock as well
47178   ** to prevent any writers from running while the checkpoint is underway.
47179   ** This has to be done before the call to walIndexReadHdr() below.
47180   **
47181   ** If the writer lock cannot be obtained, then a passive checkpoint is
47182   ** run instead. Since the checkpointer is not holding the writer lock,
47183   ** there is no point in blocking waiting for any readers. Assuming no
47184   ** other error occurs, this function will return SQLITE_BUSY to the caller.
47185   */
47186   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47187     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
47188     if( rc==SQLITE_OK ){
47189       pWal->writeLock = 1;
47190     }else if( rc==SQLITE_BUSY ){
47191       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
47192       rc = SQLITE_OK;
47193     }
47194   }
47195 
47196   /* Read the wal-index header. */
47197   if( rc==SQLITE_OK ){
47198     rc = walIndexReadHdr(pWal, &isChanged);
47199   }
47200 
47201   /* Copy data from the log to the database file. */
47202   if( rc==SQLITE_OK ){
47203     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
47204       rc = SQLITE_CORRUPT_BKPT;
47205     }else{
47206       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
47207     }
47208 
47209     /* If no error occurred, set the output variables. */
47210     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
47211       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
47212       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
47213     }
47214   }
47215 
47216   if( isChanged ){
47217     /* If a new wal-index header was loaded before the checkpoint was
47218     ** performed, then the pager-cache associated with pWal is now
47219     ** out of date. So zero the cached wal-index header to ensure that
47220     ** next time the pager opens a snapshot on this database it knows that
47221     ** the cache needs to be reset.
47222     */
47223     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
47224   }
47225 
47226   /* Release the locks. */
47227   sqlite3WalEndWriteTransaction(pWal);
47228   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
47229   pWal->ckptLock = 0;
47230   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
47231   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
47232 }
47233 
47234 /* Return the value to pass to a sqlite3_wal_hook callback, the
47235 ** number of frames in the WAL at the point of the last commit since
47236 ** sqlite3WalCallback() was called.  If no commits have occurred since
47237 ** the last call, then return 0.
47238 */
47239 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
47240   u32 ret = 0;
47241   if( pWal ){
47242     ret = pWal->iCallback;
47243     pWal->iCallback = 0;
47244   }
47245   return (int)ret;
47246 }
47247 
47248 /*
47249 ** This function is called to change the WAL subsystem into or out
47250 ** of locking_mode=EXCLUSIVE.
47251 **
47252 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
47253 ** into locking_mode=NORMAL.  This means that we must acquire a lock
47254 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
47255 ** or if the acquisition of the lock fails, then return 0.  If the
47256 ** transition out of exclusive-mode is successful, return 1.  This
47257 ** operation must occur while the pager is still holding the exclusive
47258 ** lock on the main database file.
47259 **
47260 ** If op is one, then change from locking_mode=NORMAL into
47261 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
47262 ** be released.  Return 1 if the transition is made and 0 if the
47263 ** WAL is already in exclusive-locking mode - meaning that this
47264 ** routine is a no-op.  The pager must already hold the exclusive lock
47265 ** on the main database file before invoking this operation.
47266 **
47267 ** If op is negative, then do a dry-run of the op==1 case but do
47268 ** not actually change anything. The pager uses this to see if it
47269 ** should acquire the database exclusive lock prior to invoking
47270 ** the op==1 case.
47271 */
47272 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
47273   int rc;
47274   assert( pWal->writeLock==0 );
47275   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
47276 
47277   /* pWal->readLock is usually set, but might be -1 if there was a
47278   ** prior error while attempting to acquire are read-lock. This cannot
47279   ** happen if the connection is actually in exclusive mode (as no xShmLock
47280   ** locks are taken in this case). Nor should the pager attempt to
47281   ** upgrade to exclusive-mode following such an error.
47282   */
47283   assert( pWal->readLock>=0 || pWal->lockError );
47284   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
47285 
47286   if( op==0 ){
47287     if( pWal->exclusiveMode ){
47288       pWal->exclusiveMode = 0;
47289       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
47290         pWal->exclusiveMode = 1;
47291       }
47292       rc = pWal->exclusiveMode==0;
47293     }else{
47294       /* Already in locking_mode=NORMAL */
47295       rc = 0;
47296     }
47297   }else if( op>0 ){
47298     assert( pWal->exclusiveMode==0 );
47299     assert( pWal->readLock>=0 );
47300     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47301     pWal->exclusiveMode = 1;
47302     rc = 1;
47303   }else{
47304     rc = pWal->exclusiveMode==0;
47305   }
47306   return rc;
47307 }
47308 
47309 /*
47310 ** Return true if the argument is non-NULL and the WAL module is using
47311 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
47312 ** WAL module is using shared-memory, return false.
47313 */
47314 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
47315   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
47316 }
47317 
47318 #endif /* #ifndef SQLITE_OMIT_WAL */
47319 
47320 /************** End of wal.c *************************************************/
47321 /************** Begin file btmutex.c *****************************************/
47322 /*
47323 ** 2007 August 27
47324 **
47325 ** The author disclaims copyright to this source code.  In place of
47326 ** a legal notice, here is a blessing:
47327 **
47328 **    May you do good and not evil.
47329 **    May you find forgiveness for yourself and forgive others.
47330 **    May you share freely, never taking more than you give.
47331 **
47332 *************************************************************************
47333 **
47334 ** This file contains code used to implement mutexes on Btree objects.
47335 ** This code really belongs in btree.c.  But btree.c is getting too
47336 ** big and we want to break it down some.  This packaged seemed like
47337 ** a good breakout.
47338 */
47339 /************** Include btreeInt.h in the middle of btmutex.c ****************/
47340 /************** Begin file btreeInt.h ****************************************/
47341 /*
47342 ** 2004 April 6
47343 **
47344 ** The author disclaims copyright to this source code.  In place of
47345 ** a legal notice, here is a blessing:
47346 **
47347 **    May you do good and not evil.
47348 **    May you find forgiveness for yourself and forgive others.
47349 **    May you share freely, never taking more than you give.
47350 **
47351 *************************************************************************
47352 ** This file implements a external (disk-based) database using BTrees.
47353 ** For a detailed discussion of BTrees, refer to
47354 **
47355 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
47356 **     "Sorting And Searching", pages 473-480. Addison-Wesley
47357 **     Publishing Company, Reading, Massachusetts.
47358 **
47359 ** The basic idea is that each page of the file contains N database
47360 ** entries and N+1 pointers to subpages.
47361 **
47362 **   ----------------------------------------------------------------
47363 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
47364 **   ----------------------------------------------------------------
47365 **
47366 ** All of the keys on the page that Ptr(0) points to have values less
47367 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
47368 ** values greater than Key(0) and less than Key(1).  All of the keys
47369 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
47370 ** so forth.
47371 **
47372 ** Finding a particular key requires reading O(log(M)) pages from the
47373 ** disk where M is the number of entries in the tree.
47374 **
47375 ** In this implementation, a single file can hold one or more separate
47376 ** BTrees.  Each BTree is identified by the index of its root page.  The
47377 ** key and data for any entry are combined to form the "payload".  A
47378 ** fixed amount of payload can be carried directly on the database
47379 ** page.  If the payload is larger than the preset amount then surplus
47380 ** bytes are stored on overflow pages.  The payload for an entry
47381 ** and the preceding pointer are combined to form a "Cell".  Each
47382 ** page has a small header which contains the Ptr(N) pointer and other
47383 ** information such as the size of key and data.
47384 **
47385 ** FORMAT DETAILS
47386 **
47387 ** The file is divided into pages.  The first page is called page 1,
47388 ** the second is page 2, and so forth.  A page number of zero indicates
47389 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
47390 ** Each page can be either a btree page, a freelist page, an overflow
47391 ** page, or a pointer-map page.
47392 **
47393 ** The first page is always a btree page.  The first 100 bytes of the first
47394 ** page contain a special header (the "file header") that describes the file.
47395 ** The format of the file header is as follows:
47396 **
47397 **   OFFSET   SIZE    DESCRIPTION
47398 **      0      16     Header string: "SQLite format 3\000"
47399 **     16       2     Page size in bytes.
47400 **     18       1     File format write version
47401 **     19       1     File format read version
47402 **     20       1     Bytes of unused space at the end of each page
47403 **     21       1     Max embedded payload fraction
47404 **     22       1     Min embedded payload fraction
47405 **     23       1     Min leaf payload fraction
47406 **     24       4     File change counter
47407 **     28       4     Reserved for future use
47408 **     32       4     First freelist page
47409 **     36       4     Number of freelist pages in the file
47410 **     40      60     15 4-byte meta values passed to higher layers
47411 **
47412 **     40       4     Schema cookie
47413 **     44       4     File format of schema layer
47414 **     48       4     Size of page cache
47415 **     52       4     Largest root-page (auto/incr_vacuum)
47416 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
47417 **     60       4     User version
47418 **     64       4     Incremental vacuum mode
47419 **     68       4     unused
47420 **     72       4     unused
47421 **     76       4     unused
47422 **
47423 ** All of the integer values are big-endian (most significant byte first).
47424 **
47425 ** The file change counter is incremented when the database is changed
47426 ** This counter allows other processes to know when the file has changed
47427 ** and thus when they need to flush their cache.
47428 **
47429 ** The max embedded payload fraction is the amount of the total usable
47430 ** space in a page that can be consumed by a single cell for standard
47431 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
47432 ** is to limit the maximum cell size so that at least 4 cells will fit
47433 ** on one page.  Thus the default max embedded payload fraction is 64.
47434 **
47435 ** If the payload for a cell is larger than the max payload, then extra
47436 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
47437 ** as many bytes as possible are moved into the overflow pages without letting
47438 ** the cell size drop below the min embedded payload fraction.
47439 **
47440 ** The min leaf payload fraction is like the min embedded payload fraction
47441 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
47442 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
47443 ** not specified in the header.
47444 **
47445 ** Each btree pages is divided into three sections:  The header, the
47446 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
47447 ** file header that occurs before the page header.
47448 **
47449 **      |----------------|
47450 **      | file header    |   100 bytes.  Page 1 only.
47451 **      |----------------|
47452 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
47453 **      |----------------|
47454 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
47455 **      | array          |   |  Grows downward
47456 **      |                |   v
47457 **      |----------------|
47458 **      | unallocated    |
47459 **      | space          |
47460 **      |----------------|   ^  Grows upwards
47461 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
47462 **      | area           |   |  and free space fragments.
47463 **      |----------------|
47464 **
47465 ** The page headers looks like this:
47466 **
47467 **   OFFSET   SIZE     DESCRIPTION
47468 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
47469 **      1       2      byte offset to the first freeblock
47470 **      3       2      number of cells on this page
47471 **      5       2      first byte of the cell content area
47472 **      7       1      number of fragmented free bytes
47473 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
47474 **
47475 ** The flags define the format of this btree page.  The leaf flag means that
47476 ** this page has no children.  The zerodata flag means that this page carries
47477 ** only keys and no data.  The intkey flag means that the key is a integer
47478 ** which is stored in the key size entry of the cell header rather than in
47479 ** the payload area.
47480 **
47481 ** The cell pointer array begins on the first byte after the page header.
47482 ** The cell pointer array contains zero or more 2-byte numbers which are
47483 ** offsets from the beginning of the page to the cell content in the cell
47484 ** content area.  The cell pointers occur in sorted order.  The system strives
47485 ** to keep free space after the last cell pointer so that new cells can
47486 ** be easily added without having to defragment the page.
47487 **
47488 ** Cell content is stored at the very end of the page and grows toward the
47489 ** beginning of the page.
47490 **
47491 ** Unused space within the cell content area is collected into a linked list of
47492 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
47493 ** to the first freeblock is given in the header.  Freeblocks occur in
47494 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
47495 ** any group of 3 or fewer unused bytes in the cell content area cannot
47496 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
47497 ** a fragment.  The total number of bytes in all fragments is recorded.
47498 ** in the page header at offset 7.
47499 **
47500 **    SIZE    DESCRIPTION
47501 **      2     Byte offset of the next freeblock
47502 **      2     Bytes in this freeblock
47503 **
47504 ** Cells are of variable length.  Cells are stored in the cell content area at
47505 ** the end of the page.  Pointers to the cells are in the cell pointer array
47506 ** that immediately follows the page header.  Cells is not necessarily
47507 ** contiguous or in order, but cell pointers are contiguous and in order.
47508 **
47509 ** Cell content makes use of variable length integers.  A variable
47510 ** length integer is 1 to 9 bytes where the lower 7 bits of each
47511 ** byte are used.  The integer consists of all bytes that have bit 8 set and
47512 ** the first byte with bit 8 clear.  The most significant byte of the integer
47513 ** appears first.  A variable-length integer may not be more than 9 bytes long.
47514 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
47515 ** allows a 64-bit integer to be encoded in 9 bytes.
47516 **
47517 **    0x00                      becomes  0x00000000
47518 **    0x7f                      becomes  0x0000007f
47519 **    0x81 0x00                 becomes  0x00000080
47520 **    0x82 0x00                 becomes  0x00000100
47521 **    0x80 0x7f                 becomes  0x0000007f
47522 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
47523 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
47524 **
47525 ** Variable length integers are used for rowids and to hold the number of
47526 ** bytes of key and data in a btree cell.
47527 **
47528 ** The content of a cell looks like this:
47529 **
47530 **    SIZE    DESCRIPTION
47531 **      4     Page number of the left child. Omitted if leaf flag is set.
47532 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
47533 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
47534 **      *     Payload
47535 **      4     First page of the overflow chain.  Omitted if no overflow
47536 **
47537 ** Overflow pages form a linked list.  Each page except the last is completely
47538 ** filled with data (pagesize - 4 bytes).  The last page can have as little
47539 ** as 1 byte of data.
47540 **
47541 **    SIZE    DESCRIPTION
47542 **      4     Page number of next overflow page
47543 **      *     Data
47544 **
47545 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
47546 ** file header points to the first in a linked list of trunk page.  Each trunk
47547 ** page points to multiple leaf pages.  The content of a leaf page is
47548 ** unspecified.  A trunk page looks like this:
47549 **
47550 **    SIZE    DESCRIPTION
47551 **      4     Page number of next trunk page
47552 **      4     Number of leaf pointers on this page
47553 **      *     zero or more pages numbers of leaves
47554 */
47555 
47556 
47557 /* The following value is the maximum cell size assuming a maximum page
47558 ** size give above.
47559 */
47560 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
47561 
47562 /* The maximum number of cells on a single page of the database.  This
47563 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
47564 ** plus 2 bytes for the index to the cell in the page header).  Such
47565 ** small cells will be rare, but they are possible.
47566 */
47567 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
47568 
47569 /* Forward declarations */
47570 typedef struct MemPage MemPage;
47571 typedef struct BtLock BtLock;
47572 
47573 /*
47574 ** This is a magic string that appears at the beginning of every
47575 ** SQLite database in order to identify the file as a real database.
47576 **
47577 ** You can change this value at compile-time by specifying a
47578 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
47579 ** header must be exactly 16 bytes including the zero-terminator so
47580 ** the string itself should be 15 characters long.  If you change
47581 ** the header, then your custom library will not be able to read
47582 ** databases generated by the standard tools and the standard tools
47583 ** will not be able to read databases created by your custom library.
47584 */
47585 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
47586 #  define SQLITE_FILE_HEADER "SQLite format 3"
47587 #endif
47588 
47589 /*
47590 ** Page type flags.  An ORed combination of these flags appear as the
47591 ** first byte of on-disk image of every BTree page.
47592 */
47593 #define PTF_INTKEY    0x01
47594 #define PTF_ZERODATA  0x02
47595 #define PTF_LEAFDATA  0x04
47596 #define PTF_LEAF      0x08
47597 
47598 /*
47599 ** As each page of the file is loaded into memory, an instance of the following
47600 ** structure is appended and initialized to zero.  This structure stores
47601 ** information about the page that is decoded from the raw file page.
47602 **
47603 ** The pParent field points back to the parent page.  This allows us to
47604 ** walk up the BTree from any leaf to the root.  Care must be taken to
47605 ** unref() the parent page pointer when this page is no longer referenced.
47606 ** The pageDestructor() routine handles that chore.
47607 **
47608 ** Access to all fields of this structure is controlled by the mutex
47609 ** stored in MemPage.pBt->mutex.
47610 */
47611 struct MemPage {
47612   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
47613   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
47614   u8 intKey;           /* True if intkey flag is set */
47615   u8 leaf;             /* True if leaf flag is set */
47616   u8 hasData;          /* True if this page stores data */
47617   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
47618   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
47619   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
47620   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
47621   u16 cellOffset;      /* Index in aData of first cell pointer */
47622   u16 nFree;           /* Number of free bytes on the page */
47623   u16 nCell;           /* Number of cells on this page, local and ovfl */
47624   u16 maskPage;        /* Mask for page offset */
47625   struct _OvflCell {   /* Cells that will not fit on aData[] */
47626     u8 *pCell;          /* Pointers to the body of the overflow cell */
47627     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
47628   } aOvfl[5];
47629   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
47630   u8 *aData;           /* Pointer to disk image of the page data */
47631   DbPage *pDbPage;     /* Pager page handle */
47632   Pgno pgno;           /* Page number for this page */
47633 };
47634 
47635 /*
47636 ** The in-memory image of a disk page has the auxiliary information appended
47637 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
47638 ** that extra information.
47639 */
47640 #define EXTRA_SIZE sizeof(MemPage)
47641 
47642 /*
47643 ** A linked list of the following structures is stored at BtShared.pLock.
47644 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
47645 ** is opened on the table with root page BtShared.iTable. Locks are removed
47646 ** from this list when a transaction is committed or rolled back, or when
47647 ** a btree handle is closed.
47648 */
47649 struct BtLock {
47650   Btree *pBtree;        /* Btree handle holding this lock */
47651   Pgno iTable;          /* Root page of table */
47652   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
47653   BtLock *pNext;        /* Next in BtShared.pLock list */
47654 };
47655 
47656 /* Candidate values for BtLock.eLock */
47657 #define READ_LOCK     1
47658 #define WRITE_LOCK    2
47659 
47660 /* A Btree handle
47661 **
47662 ** A database connection contains a pointer to an instance of
47663 ** this object for every database file that it has open.  This structure
47664 ** is opaque to the database connection.  The database connection cannot
47665 ** see the internals of this structure and only deals with pointers to
47666 ** this structure.
47667 **
47668 ** For some database files, the same underlying database cache might be
47669 ** shared between multiple connections.  In that case, each connection
47670 ** has it own instance of this object.  But each instance of this object
47671 ** points to the same BtShared object.  The database cache and the
47672 ** schema associated with the database file are all contained within
47673 ** the BtShared object.
47674 **
47675 ** All fields in this structure are accessed under sqlite3.mutex.
47676 ** The pBt pointer itself may not be changed while there exists cursors
47677 ** in the referenced BtShared that point back to this Btree since those
47678 ** cursors have to go through this Btree to find their BtShared and
47679 ** they often do so without holding sqlite3.mutex.
47680 */
47681 struct Btree {
47682   sqlite3 *db;       /* The database connection holding this btree */
47683   BtShared *pBt;     /* Sharable content of this btree */
47684   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
47685   u8 sharable;       /* True if we can share pBt with another db */
47686   u8 locked;         /* True if db currently has pBt locked */
47687   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
47688   int nBackup;       /* Number of backup operations reading this btree */
47689   Btree *pNext;      /* List of other sharable Btrees from the same db */
47690   Btree *pPrev;      /* Back pointer of the same list */
47691 #ifndef SQLITE_OMIT_SHARED_CACHE
47692   BtLock lock;       /* Object used to lock page 1 */
47693 #endif
47694 };
47695 
47696 /*
47697 ** Btree.inTrans may take one of the following values.
47698 **
47699 ** If the shared-data extension is enabled, there may be multiple users
47700 ** of the Btree structure. At most one of these may open a write transaction,
47701 ** but any number may have active read transactions.
47702 */
47703 #define TRANS_NONE  0
47704 #define TRANS_READ  1
47705 #define TRANS_WRITE 2
47706 
47707 /*
47708 ** An instance of this object represents a single database file.
47709 **
47710 ** A single database file can be in use as the same time by two
47711 ** or more database connections.  When two or more connections are
47712 ** sharing the same database file, each connection has it own
47713 ** private Btree object for the file and each of those Btrees points
47714 ** to this one BtShared object.  BtShared.nRef is the number of
47715 ** connections currently sharing this database file.
47716 **
47717 ** Fields in this structure are accessed under the BtShared.mutex
47718 ** mutex, except for nRef and pNext which are accessed under the
47719 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
47720 ** may not be modified once it is initially set as long as nRef>0.
47721 ** The pSchema field may be set once under BtShared.mutex and
47722 ** thereafter is unchanged as long as nRef>0.
47723 **
47724 ** isPending:
47725 **
47726 **   If a BtShared client fails to obtain a write-lock on a database
47727 **   table (because there exists one or more read-locks on the table),
47728 **   the shared-cache enters 'pending-lock' state and isPending is
47729 **   set to true.
47730 **
47731 **   The shared-cache leaves the 'pending lock' state when either of
47732 **   the following occur:
47733 **
47734 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
47735 **     2) The number of locks held by other connections drops to zero.
47736 **
47737 **   while in the 'pending-lock' state, no connection may start a new
47738 **   transaction.
47739 **
47740 **   This feature is included to help prevent writer-starvation.
47741 */
47742 struct BtShared {
47743   Pager *pPager;        /* The page cache */
47744   sqlite3 *db;          /* Database connection currently using this Btree */
47745   BtCursor *pCursor;    /* A list of all open cursors */
47746   MemPage *pPage1;      /* First page of the database */
47747   u8 readOnly;          /* True if the underlying file is readonly */
47748   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
47749   u8 secureDelete;      /* True if secure_delete is enabled */
47750   u8 initiallyEmpty;    /* Database is empty at start of transaction */
47751   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
47752 #ifndef SQLITE_OMIT_AUTOVACUUM
47753   u8 autoVacuum;        /* True if auto-vacuum is enabled */
47754   u8 incrVacuum;        /* True if incr-vacuum is enabled */
47755 #endif
47756   u8 inTransaction;     /* Transaction state */
47757   u8 doNotUseWAL;       /* If true, do not open write-ahead-log file */
47758   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
47759   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
47760   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
47761   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
47762   u32 pageSize;         /* Total number of bytes on a page */
47763   u32 usableSize;       /* Number of usable bytes on each page */
47764   int nTransaction;     /* Number of open transactions (read + write) */
47765   u32 nPage;            /* Number of pages in the database */
47766   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
47767   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
47768   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
47769   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
47770 #ifndef SQLITE_OMIT_SHARED_CACHE
47771   int nRef;             /* Number of references to this structure */
47772   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
47773   BtLock *pLock;        /* List of locks held on this shared-btree struct */
47774   Btree *pWriter;       /* Btree with currently open write transaction */
47775   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
47776   u8 isPending;         /* If waiting for read-locks to clear */
47777 #endif
47778   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
47779 };
47780 
47781 /*
47782 ** An instance of the following structure is used to hold information
47783 ** about a cell.  The parseCellPtr() function fills in this structure
47784 ** based on information extract from the raw disk page.
47785 */
47786 typedef struct CellInfo CellInfo;
47787 struct CellInfo {
47788   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
47789   u8 *pCell;     /* Pointer to the start of cell content */
47790   u32 nData;     /* Number of bytes of data */
47791   u32 nPayload;  /* Total amount of payload */
47792   u16 nHeader;   /* Size of the cell content header in bytes */
47793   u16 nLocal;    /* Amount of payload held locally */
47794   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
47795   u16 nSize;     /* Size of the cell content on the main b-tree page */
47796 };
47797 
47798 /*
47799 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
47800 ** this will be declared corrupt. This value is calculated based on a
47801 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
47802 ** root-node and 3 for all other internal nodes.
47803 **
47804 ** If a tree that appears to be taller than this is encountered, it is
47805 ** assumed that the database is corrupt.
47806 */
47807 #define BTCURSOR_MAX_DEPTH 20
47808 
47809 /*
47810 ** A cursor is a pointer to a particular entry within a particular
47811 ** b-tree within a database file.
47812 **
47813 ** The entry is identified by its MemPage and the index in
47814 ** MemPage.aCell[] of the entry.
47815 **
47816 ** A single database file can shared by two more database connections,
47817 ** but cursors cannot be shared.  Each cursor is associated with a
47818 ** particular database connection identified BtCursor.pBtree.db.
47819 **
47820 ** Fields in this structure are accessed under the BtShared.mutex
47821 ** found at self->pBt->mutex.
47822 */
47823 struct BtCursor {
47824   Btree *pBtree;            /* The Btree to which this cursor belongs */
47825   BtShared *pBt;            /* The BtShared this cursor points to */
47826   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
47827   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
47828   Pgno pgnoRoot;            /* The root page of this tree */
47829   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
47830   CellInfo info;            /* A parse of the cell we are pointing at */
47831   i64 nKey;        /* Size of pKey, or last integer key */
47832   void *pKey;      /* Saved key that was cursor's last known position */
47833   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
47834   u8 wrFlag;                /* True if writable */
47835   u8 atLast;                /* Cursor pointing to the last entry */
47836   u8 validNKey;             /* True if info.nKey is valid */
47837   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
47838 #ifndef SQLITE_OMIT_INCRBLOB
47839   Pgno *aOverflow;          /* Cache of overflow page locations */
47840   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
47841 #endif
47842   i16 iPage;                            /* Index of current page in apPage */
47843   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
47844   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
47845 };
47846 
47847 /*
47848 ** Potential values for BtCursor.eState.
47849 **
47850 ** CURSOR_VALID:
47851 **   Cursor points to a valid entry. getPayload() etc. may be called.
47852 **
47853 ** CURSOR_INVALID:
47854 **   Cursor does not point to a valid entry. This can happen (for example)
47855 **   because the table is empty or because BtreeCursorFirst() has not been
47856 **   called.
47857 **
47858 ** CURSOR_REQUIRESEEK:
47859 **   The table that this cursor was opened on still exists, but has been
47860 **   modified since the cursor was last used. The cursor position is saved
47861 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
47862 **   this state, restoreCursorPosition() can be called to attempt to
47863 **   seek the cursor to the saved position.
47864 **
47865 ** CURSOR_FAULT:
47866 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
47867 **   on a different connection that shares the BtShared cache with this
47868 **   cursor.  The error has left the cache in an inconsistent state.
47869 **   Do nothing else with this cursor.  Any attempt to use the cursor
47870 **   should return the error code stored in BtCursor.skip
47871 */
47872 #define CURSOR_INVALID           0
47873 #define CURSOR_VALID             1
47874 #define CURSOR_REQUIRESEEK       2
47875 #define CURSOR_FAULT             3
47876 
47877 /*
47878 ** The database page the PENDING_BYTE occupies. This page is never used.
47879 */
47880 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
47881 
47882 /*
47883 ** These macros define the location of the pointer-map entry for a
47884 ** database page. The first argument to each is the number of usable
47885 ** bytes on each page of the database (often 1024). The second is the
47886 ** page number to look up in the pointer map.
47887 **
47888 ** PTRMAP_PAGENO returns the database page number of the pointer-map
47889 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
47890 ** the offset of the requested map entry.
47891 **
47892 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
47893 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
47894 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
47895 ** this test.
47896 */
47897 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
47898 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
47899 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
47900 
47901 /*
47902 ** The pointer map is a lookup table that identifies the parent page for
47903 ** each child page in the database file.  The parent page is the page that
47904 ** contains a pointer to the child.  Every page in the database contains
47905 ** 0 or 1 parent pages.  (In this context 'database page' refers
47906 ** to any page that is not part of the pointer map itself.)  Each pointer map
47907 ** entry consists of a single byte 'type' and a 4 byte parent page number.
47908 ** The PTRMAP_XXX identifiers below are the valid types.
47909 **
47910 ** The purpose of the pointer map is to facility moving pages from one
47911 ** position in the file to another as part of autovacuum.  When a page
47912 ** is moved, the pointer in its parent must be updated to point to the
47913 ** new location.  The pointer map is used to locate the parent page quickly.
47914 **
47915 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
47916 **                  used in this case.
47917 **
47918 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
47919 **                  is not used in this case.
47920 **
47921 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
47922 **                   overflow pages. The page number identifies the page that
47923 **                   contains the cell with a pointer to this overflow page.
47924 **
47925 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
47926 **                   overflow pages. The page-number identifies the previous
47927 **                   page in the overflow page list.
47928 **
47929 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
47930 **               identifies the parent page in the btree.
47931 */
47932 #define PTRMAP_ROOTPAGE 1
47933 #define PTRMAP_FREEPAGE 2
47934 #define PTRMAP_OVERFLOW1 3
47935 #define PTRMAP_OVERFLOW2 4
47936 #define PTRMAP_BTREE 5
47937 
47938 /* A bunch of assert() statements to check the transaction state variables
47939 ** of handle p (type Btree*) are internally consistent.
47940 */
47941 #define btreeIntegrity(p) \
47942   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
47943   assert( p->pBt->inTransaction>=p->inTrans );
47944 
47945 
47946 /*
47947 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
47948 ** if the database supports auto-vacuum or not. Because it is used
47949 ** within an expression that is an argument to another macro
47950 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
47951 ** So, this macro is defined instead.
47952 */
47953 #ifndef SQLITE_OMIT_AUTOVACUUM
47954 #define ISAUTOVACUUM (pBt->autoVacuum)
47955 #else
47956 #define ISAUTOVACUUM 0
47957 #endif
47958 
47959 
47960 /*
47961 ** This structure is passed around through all the sanity checking routines
47962 ** in order to keep track of some global state information.
47963 */
47964 typedef struct IntegrityCk IntegrityCk;
47965 struct IntegrityCk {
47966   BtShared *pBt;    /* The tree being checked out */
47967   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
47968   Pgno nPage;       /* Number of pages in the database */
47969   int *anRef;       /* Number of times each page is referenced */
47970   int mxErr;        /* Stop accumulating errors when this reaches zero */
47971   int nErr;         /* Number of messages written to zErrMsg so far */
47972   int mallocFailed; /* A memory allocation error has occurred */
47973   StrAccum errMsg;  /* Accumulate the error message text here */
47974 };
47975 
47976 /*
47977 ** Read or write a two- and four-byte big-endian integer values.
47978 */
47979 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
47980 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
47981 #define get4byte sqlite3Get4byte
47982 #define put4byte sqlite3Put4byte
47983 
47984 /************** End of btreeInt.h ********************************************/
47985 /************** Continuing where we left off in btmutex.c ********************/
47986 #ifndef SQLITE_OMIT_SHARED_CACHE
47987 #if SQLITE_THREADSAFE
47988 
47989 /*
47990 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
47991 ** set BtShared.db to the database handle associated with p and the
47992 ** p->locked boolean to true.
47993 */
47994 static void lockBtreeMutex(Btree *p){
47995   assert( p->locked==0 );
47996   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
47997   assert( sqlite3_mutex_held(p->db->mutex) );
47998 
47999   sqlite3_mutex_enter(p->pBt->mutex);
48000   p->pBt->db = p->db;
48001   p->locked = 1;
48002 }
48003 
48004 /*
48005 ** Release the BtShared mutex associated with B-Tree handle p and
48006 ** clear the p->locked boolean.
48007 */
48008 static void unlockBtreeMutex(Btree *p){
48009   BtShared *pBt = p->pBt;
48010   assert( p->locked==1 );
48011   assert( sqlite3_mutex_held(pBt->mutex) );
48012   assert( sqlite3_mutex_held(p->db->mutex) );
48013   assert( p->db==pBt->db );
48014 
48015   sqlite3_mutex_leave(pBt->mutex);
48016   p->locked = 0;
48017 }
48018 
48019 /*
48020 ** Enter a mutex on the given BTree object.
48021 **
48022 ** If the object is not sharable, then no mutex is ever required
48023 ** and this routine is a no-op.  The underlying mutex is non-recursive.
48024 ** But we keep a reference count in Btree.wantToLock so the behavior
48025 ** of this interface is recursive.
48026 **
48027 ** To avoid deadlocks, multiple Btrees are locked in the same order
48028 ** by all database connections.  The p->pNext is a list of other
48029 ** Btrees belonging to the same database connection as the p Btree
48030 ** which need to be locked after p.  If we cannot get a lock on
48031 ** p, then first unlock all of the others on p->pNext, then wait
48032 ** for the lock to become available on p, then relock all of the
48033 ** subsequent Btrees that desire a lock.
48034 */
48035 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48036   Btree *pLater;
48037 
48038   /* Some basic sanity checking on the Btree.  The list of Btrees
48039   ** connected by pNext and pPrev should be in sorted order by
48040   ** Btree.pBt value. All elements of the list should belong to
48041   ** the same connection. Only shared Btrees are on the list. */
48042   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
48043   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
48044   assert( p->pNext==0 || p->pNext->db==p->db );
48045   assert( p->pPrev==0 || p->pPrev->db==p->db );
48046   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
48047 
48048   /* Check for locking consistency */
48049   assert( !p->locked || p->wantToLock>0 );
48050   assert( p->sharable || p->wantToLock==0 );
48051 
48052   /* We should already hold a lock on the database connection */
48053   assert( sqlite3_mutex_held(p->db->mutex) );
48054 
48055   /* Unless the database is sharable and unlocked, then BtShared.db
48056   ** should already be set correctly. */
48057   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
48058 
48059   if( !p->sharable ) return;
48060   p->wantToLock++;
48061   if( p->locked ) return;
48062 
48063   /* In most cases, we should be able to acquire the lock we
48064   ** want without having to go throught the ascending lock
48065   ** procedure that follows.  Just be sure not to block.
48066   */
48067   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
48068     p->pBt->db = p->db;
48069     p->locked = 1;
48070     return;
48071   }
48072 
48073   /* To avoid deadlock, first release all locks with a larger
48074   ** BtShared address.  Then acquire our lock.  Then reacquire
48075   ** the other BtShared locks that we used to hold in ascending
48076   ** order.
48077   */
48078   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48079     assert( pLater->sharable );
48080     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
48081     assert( !pLater->locked || pLater->wantToLock>0 );
48082     if( pLater->locked ){
48083       unlockBtreeMutex(pLater);
48084     }
48085   }
48086   lockBtreeMutex(p);
48087   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
48088     if( pLater->wantToLock ){
48089       lockBtreeMutex(pLater);
48090     }
48091   }
48092 }
48093 
48094 /*
48095 ** Exit the recursive mutex on a Btree.
48096 */
48097 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
48098   if( p->sharable ){
48099     assert( p->wantToLock>0 );
48100     p->wantToLock--;
48101     if( p->wantToLock==0 ){
48102       unlockBtreeMutex(p);
48103     }
48104   }
48105 }
48106 
48107 #ifndef NDEBUG
48108 /*
48109 ** Return true if the BtShared mutex is held on the btree, or if the
48110 ** B-Tree is not marked as sharable.
48111 **
48112 ** This routine is used only from within assert() statements.
48113 */
48114 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
48115   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
48116   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
48117   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
48118   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
48119 
48120   return (p->sharable==0 || p->locked);
48121 }
48122 #endif
48123 
48124 
48125 #ifndef SQLITE_OMIT_INCRBLOB
48126 /*
48127 ** Enter and leave a mutex on a Btree given a cursor owned by that
48128 ** Btree.  These entry points are used by incremental I/O and can be
48129 ** omitted if that module is not used.
48130 */
48131 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
48132   sqlite3BtreeEnter(pCur->pBtree);
48133 }
48134 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
48135   sqlite3BtreeLeave(pCur->pBtree);
48136 }
48137 #endif /* SQLITE_OMIT_INCRBLOB */
48138 
48139 
48140 /*
48141 ** Enter the mutex on every Btree associated with a database
48142 ** connection.  This is needed (for example) prior to parsing
48143 ** a statement since we will be comparing table and column names
48144 ** against all schemas and we do not want those schemas being
48145 ** reset out from under us.
48146 **
48147 ** There is a corresponding leave-all procedures.
48148 **
48149 ** Enter the mutexes in accending order by BtShared pointer address
48150 ** to avoid the possibility of deadlock when two threads with
48151 ** two or more btrees in common both try to lock all their btrees
48152 ** at the same instant.
48153 */
48154 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48155   int i;
48156   Btree *p;
48157   assert( sqlite3_mutex_held(db->mutex) );
48158   for(i=0; i<db->nDb; i++){
48159     p = db->aDb[i].pBt;
48160     if( p ) sqlite3BtreeEnter(p);
48161   }
48162 }
48163 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
48164   int i;
48165   Btree *p;
48166   assert( sqlite3_mutex_held(db->mutex) );
48167   for(i=0; i<db->nDb; i++){
48168     p = db->aDb[i].pBt;
48169     if( p ) sqlite3BtreeLeave(p);
48170   }
48171 }
48172 
48173 /*
48174 ** Return true if a particular Btree requires a lock.  Return FALSE if
48175 ** no lock is ever required since it is not sharable.
48176 */
48177 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
48178   return p->sharable;
48179 }
48180 
48181 #ifndef NDEBUG
48182 /*
48183 ** Return true if the current thread holds the database connection
48184 ** mutex and all required BtShared mutexes.
48185 **
48186 ** This routine is used inside assert() statements only.
48187 */
48188 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
48189   int i;
48190   if( !sqlite3_mutex_held(db->mutex) ){
48191     return 0;
48192   }
48193   for(i=0; i<db->nDb; i++){
48194     Btree *p;
48195     p = db->aDb[i].pBt;
48196     if( p && p->sharable &&
48197          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
48198       return 0;
48199     }
48200   }
48201   return 1;
48202 }
48203 #endif /* NDEBUG */
48204 
48205 #ifndef NDEBUG
48206 /*
48207 ** Return true if the correct mutexes are held for accessing the
48208 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
48209 ** access are:
48210 **
48211 **   (1) The mutex on db
48212 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
48213 **
48214 ** If pSchema is not NULL, then iDb is computed from pSchema and
48215 ** db using sqlite3SchemaToIndex().
48216 */
48217 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
48218   Btree *p;
48219   assert( db!=0 );
48220   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
48221   assert( iDb>=0 && iDb<db->nDb );
48222   if( !sqlite3_mutex_held(db->mutex) ) return 0;
48223   if( iDb==1 ) return 1;
48224   p = db->aDb[iDb].pBt;
48225   assert( p!=0 );
48226   return p->sharable==0 || p->locked==1;
48227 }
48228 #endif /* NDEBUG */
48229 
48230 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
48231 /*
48232 ** The following are special cases for mutex enter routines for use
48233 ** in single threaded applications that use shared cache.  Except for
48234 ** these two routines, all mutex operations are no-ops in that case and
48235 ** are null #defines in btree.h.
48236 **
48237 ** If shared cache is disabled, then all btree mutex routines, including
48238 ** the ones below, are no-ops and are null #defines in btree.h.
48239 */
48240 
48241 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
48242   p->pBt->db = p->db;
48243 }
48244 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
48245   int i;
48246   for(i=0; i<db->nDb; i++){
48247     Btree *p = db->aDb[i].pBt;
48248     if( p ){
48249       p->pBt->db = p->db;
48250     }
48251   }
48252 }
48253 #endif /* if SQLITE_THREADSAFE */
48254 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
48255 
48256 /************** End of btmutex.c *********************************************/
48257 /************** Begin file btree.c *******************************************/
48258 /*
48259 ** 2004 April 6
48260 **
48261 ** The author disclaims copyright to this source code.  In place of
48262 ** a legal notice, here is a blessing:
48263 **
48264 **    May you do good and not evil.
48265 **    May you find forgiveness for yourself and forgive others.
48266 **    May you share freely, never taking more than you give.
48267 **
48268 *************************************************************************
48269 ** This file implements a external (disk-based) database using BTrees.
48270 ** See the header comment on "btreeInt.h" for additional information.
48271 ** Including a description of file format and an overview of operation.
48272 */
48273 
48274 /*
48275 ** The header string that appears at the beginning of every
48276 ** SQLite database.
48277 */
48278 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
48279 
48280 /*
48281 ** Set this global variable to 1 to enable tracing using the TRACE
48282 ** macro.
48283 */
48284 #if 0
48285 int sqlite3BtreeTrace=1;  /* True to enable tracing */
48286 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
48287 #else
48288 # define TRACE(X)
48289 #endif
48290 
48291 /*
48292 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
48293 ** But if the value is zero, make it 65536.
48294 **
48295 ** This routine is used to extract the "offset to cell content area" value
48296 ** from the header of a btree page.  If the page size is 65536 and the page
48297 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
48298 ** This routine makes the necessary adjustment to 65536.
48299 */
48300 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
48301 
48302 #ifndef SQLITE_OMIT_SHARED_CACHE
48303 /*
48304 ** A list of BtShared objects that are eligible for participation
48305 ** in shared cache.  This variable has file scope during normal builds,
48306 ** but the test harness needs to access it so we make it global for
48307 ** test builds.
48308 **
48309 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
48310 */
48311 #ifdef SQLITE_TEST
48312 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48313 #else
48314 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
48315 #endif
48316 #endif /* SQLITE_OMIT_SHARED_CACHE */
48317 
48318 #ifndef SQLITE_OMIT_SHARED_CACHE
48319 /*
48320 ** Enable or disable the shared pager and schema features.
48321 **
48322 ** This routine has no effect on existing database connections.
48323 ** The shared cache setting effects only future calls to
48324 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
48325 */
48326 SQLITE_API int sqlite3_enable_shared_cache(int enable){
48327   sqlite3GlobalConfig.sharedCacheEnabled = enable;
48328   return SQLITE_OK;
48329 }
48330 #endif
48331 
48332 
48333 
48334 #ifdef SQLITE_OMIT_SHARED_CACHE
48335   /*
48336   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
48337   ** and clearAllSharedCacheTableLocks()
48338   ** manipulate entries in the BtShared.pLock linked list used to store
48339   ** shared-cache table level locks. If the library is compiled with the
48340   ** shared-cache feature disabled, then there is only ever one user
48341   ** of each BtShared structure and so this locking is not necessary.
48342   ** So define the lock related functions as no-ops.
48343   */
48344   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
48345   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
48346   #define clearAllSharedCacheTableLocks(a)
48347   #define downgradeAllSharedCacheTableLocks(a)
48348   #define hasSharedCacheTableLock(a,b,c,d) 1
48349   #define hasReadConflicts(a, b) 0
48350 #endif
48351 
48352 #ifndef SQLITE_OMIT_SHARED_CACHE
48353 
48354 #ifdef SQLITE_DEBUG
48355 /*
48356 **** This function is only used as part of an assert() statement. ***
48357 **
48358 ** Check to see if pBtree holds the required locks to read or write to the
48359 ** table with root page iRoot.   Return 1 if it does and 0 if not.
48360 **
48361 ** For example, when writing to a table with root-page iRoot via
48362 ** Btree connection pBtree:
48363 **
48364 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
48365 **
48366 ** When writing to an index that resides in a sharable database, the
48367 ** caller should have first obtained a lock specifying the root page of
48368 ** the corresponding table. This makes things a bit more complicated,
48369 ** as this module treats each table as a separate structure. To determine
48370 ** the table corresponding to the index being written, this
48371 ** function has to search through the database schema.
48372 **
48373 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
48374 ** hold a write-lock on the schema table (root page 1). This is also
48375 ** acceptable.
48376 */
48377 static int hasSharedCacheTableLock(
48378   Btree *pBtree,         /* Handle that must hold lock */
48379   Pgno iRoot,            /* Root page of b-tree */
48380   int isIndex,           /* True if iRoot is the root of an index b-tree */
48381   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
48382 ){
48383   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
48384   Pgno iTab = 0;
48385   BtLock *pLock;
48386 
48387   /* If this database is not shareable, or if the client is reading
48388   ** and has the read-uncommitted flag set, then no lock is required.
48389   ** Return true immediately.
48390   */
48391   if( (pBtree->sharable==0)
48392    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
48393   ){
48394     return 1;
48395   }
48396 
48397   /* If the client is reading  or writing an index and the schema is
48398   ** not loaded, then it is too difficult to actually check to see if
48399   ** the correct locks are held.  So do not bother - just return true.
48400   ** This case does not come up very often anyhow.
48401   */
48402   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
48403     return 1;
48404   }
48405 
48406   /* Figure out the root-page that the lock should be held on. For table
48407   ** b-trees, this is just the root page of the b-tree being read or
48408   ** written. For index b-trees, it is the root page of the associated
48409   ** table.  */
48410   if( isIndex ){
48411     HashElem *p;
48412     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
48413       Index *pIdx = (Index *)sqliteHashData(p);
48414       if( pIdx->tnum==(int)iRoot ){
48415         iTab = pIdx->pTable->tnum;
48416       }
48417     }
48418   }else{
48419     iTab = iRoot;
48420   }
48421 
48422   /* Search for the required lock. Either a write-lock on root-page iTab, a
48423   ** write-lock on the schema table, or (if the client is reading) a
48424   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
48425   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
48426     if( pLock->pBtree==pBtree
48427      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
48428      && pLock->eLock>=eLockType
48429     ){
48430       return 1;
48431     }
48432   }
48433 
48434   /* Failed to find the required lock. */
48435   return 0;
48436 }
48437 #endif /* SQLITE_DEBUG */
48438 
48439 #ifdef SQLITE_DEBUG
48440 /*
48441 **** This function may be used as part of assert() statements only. ****
48442 **
48443 ** Return true if it would be illegal for pBtree to write into the
48444 ** table or index rooted at iRoot because other shared connections are
48445 ** simultaneously reading that same table or index.
48446 **
48447 ** It is illegal for pBtree to write if some other Btree object that
48448 ** shares the same BtShared object is currently reading or writing
48449 ** the iRoot table.  Except, if the other Btree object has the
48450 ** read-uncommitted flag set, then it is OK for the other object to
48451 ** have a read cursor.
48452 **
48453 ** For example, before writing to any part of the table or index
48454 ** rooted at page iRoot, one should call:
48455 **
48456 **    assert( !hasReadConflicts(pBtree, iRoot) );
48457 */
48458 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
48459   BtCursor *p;
48460   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
48461     if( p->pgnoRoot==iRoot
48462      && p->pBtree!=pBtree
48463      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
48464     ){
48465       return 1;
48466     }
48467   }
48468   return 0;
48469 }
48470 #endif    /* #ifdef SQLITE_DEBUG */
48471 
48472 /*
48473 ** Query to see if Btree handle p may obtain a lock of type eLock
48474 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
48475 ** SQLITE_OK if the lock may be obtained (by calling
48476 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
48477 */
48478 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
48479   BtShared *pBt = p->pBt;
48480   BtLock *pIter;
48481 
48482   assert( sqlite3BtreeHoldsMutex(p) );
48483   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48484   assert( p->db!=0 );
48485   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
48486 
48487   /* If requesting a write-lock, then the Btree must have an open write
48488   ** transaction on this file. And, obviously, for this to be so there
48489   ** must be an open write transaction on the file itself.
48490   */
48491   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
48492   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
48493 
48494   /* This routine is a no-op if the shared-cache is not enabled */
48495   if( !p->sharable ){
48496     return SQLITE_OK;
48497   }
48498 
48499   /* If some other connection is holding an exclusive lock, the
48500   ** requested lock may not be obtained.
48501   */
48502   if( pBt->pWriter!=p && pBt->isExclusive ){
48503     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
48504     return SQLITE_LOCKED_SHAREDCACHE;
48505   }
48506 
48507   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48508     /* The condition (pIter->eLock!=eLock) in the following if(...)
48509     ** statement is a simplification of:
48510     **
48511     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
48512     **
48513     ** since we know that if eLock==WRITE_LOCK, then no other connection
48514     ** may hold a WRITE_LOCK on any table in this file (since there can
48515     ** only be a single writer).
48516     */
48517     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
48518     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
48519     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
48520       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
48521       if( eLock==WRITE_LOCK ){
48522         assert( p==pBt->pWriter );
48523         pBt->isPending = 1;
48524       }
48525       return SQLITE_LOCKED_SHAREDCACHE;
48526     }
48527   }
48528   return SQLITE_OK;
48529 }
48530 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48531 
48532 #ifndef SQLITE_OMIT_SHARED_CACHE
48533 /*
48534 ** Add a lock on the table with root-page iTable to the shared-btree used
48535 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
48536 ** WRITE_LOCK.
48537 **
48538 ** This function assumes the following:
48539 **
48540 **   (a) The specified Btree object p is connected to a sharable
48541 **       database (one with the BtShared.sharable flag set), and
48542 **
48543 **   (b) No other Btree objects hold a lock that conflicts
48544 **       with the requested lock (i.e. querySharedCacheTableLock() has
48545 **       already been called and returned SQLITE_OK).
48546 **
48547 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
48548 ** is returned if a malloc attempt fails.
48549 */
48550 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
48551   BtShared *pBt = p->pBt;
48552   BtLock *pLock = 0;
48553   BtLock *pIter;
48554 
48555   assert( sqlite3BtreeHoldsMutex(p) );
48556   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
48557   assert( p->db!=0 );
48558 
48559   /* A connection with the read-uncommitted flag set will never try to
48560   ** obtain a read-lock using this function. The only read-lock obtained
48561   ** by a connection in read-uncommitted mode is on the sqlite_master
48562   ** table, and that lock is obtained in BtreeBeginTrans().  */
48563   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
48564 
48565   /* This function should only be called on a sharable b-tree after it
48566   ** has been determined that no other b-tree holds a conflicting lock.  */
48567   assert( p->sharable );
48568   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
48569 
48570   /* First search the list for an existing lock on this table. */
48571   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
48572     if( pIter->iTable==iTable && pIter->pBtree==p ){
48573       pLock = pIter;
48574       break;
48575     }
48576   }
48577 
48578   /* If the above search did not find a BtLock struct associating Btree p
48579   ** with table iTable, allocate one and link it into the list.
48580   */
48581   if( !pLock ){
48582     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
48583     if( !pLock ){
48584       return SQLITE_NOMEM;
48585     }
48586     pLock->iTable = iTable;
48587     pLock->pBtree = p;
48588     pLock->pNext = pBt->pLock;
48589     pBt->pLock = pLock;
48590   }
48591 
48592   /* Set the BtLock.eLock variable to the maximum of the current lock
48593   ** and the requested lock. This means if a write-lock was already held
48594   ** and a read-lock requested, we don't incorrectly downgrade the lock.
48595   */
48596   assert( WRITE_LOCK>READ_LOCK );
48597   if( eLock>pLock->eLock ){
48598     pLock->eLock = eLock;
48599   }
48600 
48601   return SQLITE_OK;
48602 }
48603 #endif /* !SQLITE_OMIT_SHARED_CACHE */
48604 
48605 #ifndef SQLITE_OMIT_SHARED_CACHE
48606 /*
48607 ** Release all the table locks (locks obtained via calls to
48608 ** the setSharedCacheTableLock() procedure) held by Btree object p.
48609 **
48610 ** This function assumes that Btree p has an open read or write
48611 ** transaction. If it does not, then the BtShared.isPending variable
48612 ** may be incorrectly cleared.
48613 */
48614 static void clearAllSharedCacheTableLocks(Btree *p){
48615   BtShared *pBt = p->pBt;
48616   BtLock **ppIter = &pBt->pLock;
48617 
48618   assert( sqlite3BtreeHoldsMutex(p) );
48619   assert( p->sharable || 0==*ppIter );
48620   assert( p->inTrans>0 );
48621 
48622   while( *ppIter ){
48623     BtLock *pLock = *ppIter;
48624     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
48625     assert( pLock->pBtree->inTrans>=pLock->eLock );
48626     if( pLock->pBtree==p ){
48627       *ppIter = pLock->pNext;
48628       assert( pLock->iTable!=1 || pLock==&p->lock );
48629       if( pLock->iTable!=1 ){
48630         sqlite3_free(pLock);
48631       }
48632     }else{
48633       ppIter = &pLock->pNext;
48634     }
48635   }
48636 
48637   assert( pBt->isPending==0 || pBt->pWriter );
48638   if( pBt->pWriter==p ){
48639     pBt->pWriter = 0;
48640     pBt->isExclusive = 0;
48641     pBt->isPending = 0;
48642   }else if( pBt->nTransaction==2 ){
48643     /* This function is called when Btree p is concluding its
48644     ** transaction. If there currently exists a writer, and p is not
48645     ** that writer, then the number of locks held by connections other
48646     ** than the writer must be about to drop to zero. In this case
48647     ** set the isPending flag to 0.
48648     **
48649     ** If there is not currently a writer, then BtShared.isPending must
48650     ** be zero already. So this next line is harmless in that case.
48651     */
48652     pBt->isPending = 0;
48653   }
48654 }
48655 
48656 /*
48657 ** This function changes all write-locks held by Btree p into read-locks.
48658 */
48659 static void downgradeAllSharedCacheTableLocks(Btree *p){
48660   BtShared *pBt = p->pBt;
48661   if( pBt->pWriter==p ){
48662     BtLock *pLock;
48663     pBt->pWriter = 0;
48664     pBt->isExclusive = 0;
48665     pBt->isPending = 0;
48666     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
48667       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
48668       pLock->eLock = READ_LOCK;
48669     }
48670   }
48671 }
48672 
48673 #endif /* SQLITE_OMIT_SHARED_CACHE */
48674 
48675 static void releasePage(MemPage *pPage);  /* Forward reference */
48676 
48677 /*
48678 ***** This routine is used inside of assert() only ****
48679 **
48680 ** Verify that the cursor holds the mutex on its BtShared
48681 */
48682 #ifdef SQLITE_DEBUG
48683 static int cursorHoldsMutex(BtCursor *p){
48684   return sqlite3_mutex_held(p->pBt->mutex);
48685 }
48686 #endif
48687 
48688 
48689 #ifndef SQLITE_OMIT_INCRBLOB
48690 /*
48691 ** Invalidate the overflow page-list cache for cursor pCur, if any.
48692 */
48693 static void invalidateOverflowCache(BtCursor *pCur){
48694   assert( cursorHoldsMutex(pCur) );
48695   sqlite3_free(pCur->aOverflow);
48696   pCur->aOverflow = 0;
48697 }
48698 
48699 /*
48700 ** Invalidate the overflow page-list cache for all cursors opened
48701 ** on the shared btree structure pBt.
48702 */
48703 static void invalidateAllOverflowCache(BtShared *pBt){
48704   BtCursor *p;
48705   assert( sqlite3_mutex_held(pBt->mutex) );
48706   for(p=pBt->pCursor; p; p=p->pNext){
48707     invalidateOverflowCache(p);
48708   }
48709 }
48710 
48711 /*
48712 ** This function is called before modifying the contents of a table
48713 ** to invalidate any incrblob cursors that are open on the
48714 ** row or one of the rows being modified.
48715 **
48716 ** If argument isClearTable is true, then the entire contents of the
48717 ** table is about to be deleted. In this case invalidate all incrblob
48718 ** cursors open on any row within the table with root-page pgnoRoot.
48719 **
48720 ** Otherwise, if argument isClearTable is false, then the row with
48721 ** rowid iRow is being replaced or deleted. In this case invalidate
48722 ** only those incrblob cursors open on that specific row.
48723 */
48724 static void invalidateIncrblobCursors(
48725   Btree *pBtree,          /* The database file to check */
48726   i64 iRow,               /* The rowid that might be changing */
48727   int isClearTable        /* True if all rows are being deleted */
48728 ){
48729   BtCursor *p;
48730   BtShared *pBt = pBtree->pBt;
48731   assert( sqlite3BtreeHoldsMutex(pBtree) );
48732   for(p=pBt->pCursor; p; p=p->pNext){
48733     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
48734       p->eState = CURSOR_INVALID;
48735     }
48736   }
48737 }
48738 
48739 #else
48740   /* Stub functions when INCRBLOB is omitted */
48741   #define invalidateOverflowCache(x)
48742   #define invalidateAllOverflowCache(x)
48743   #define invalidateIncrblobCursors(x,y,z)
48744 #endif /* SQLITE_OMIT_INCRBLOB */
48745 
48746 /*
48747 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
48748 ** when a page that previously contained data becomes a free-list leaf
48749 ** page.
48750 **
48751 ** The BtShared.pHasContent bitvec exists to work around an obscure
48752 ** bug caused by the interaction of two useful IO optimizations surrounding
48753 ** free-list leaf pages:
48754 **
48755 **   1) When all data is deleted from a page and the page becomes
48756 **      a free-list leaf page, the page is not written to the database
48757 **      (as free-list leaf pages contain no meaningful data). Sometimes
48758 **      such a page is not even journalled (as it will not be modified,
48759 **      why bother journalling it?).
48760 **
48761 **   2) When a free-list leaf page is reused, its content is not read
48762 **      from the database or written to the journal file (why should it
48763 **      be, if it is not at all meaningful?).
48764 **
48765 ** By themselves, these optimizations work fine and provide a handy
48766 ** performance boost to bulk delete or insert operations. However, if
48767 ** a page is moved to the free-list and then reused within the same
48768 ** transaction, a problem comes up. If the page is not journalled when
48769 ** it is moved to the free-list and it is also not journalled when it
48770 ** is extracted from the free-list and reused, then the original data
48771 ** may be lost. In the event of a rollback, it may not be possible
48772 ** to restore the database to its original configuration.
48773 **
48774 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
48775 ** moved to become a free-list leaf page, the corresponding bit is
48776 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
48777 ** optimization 2 above is omitted if the corresponding bit is already
48778 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
48779 ** at the end of every transaction.
48780 */
48781 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
48782   int rc = SQLITE_OK;
48783   if( !pBt->pHasContent ){
48784     assert( pgno<=pBt->nPage );
48785     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
48786     if( !pBt->pHasContent ){
48787       rc = SQLITE_NOMEM;
48788     }
48789   }
48790   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
48791     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
48792   }
48793   return rc;
48794 }
48795 
48796 /*
48797 ** Query the BtShared.pHasContent vector.
48798 **
48799 ** This function is called when a free-list leaf page is removed from the
48800 ** free-list for reuse. It returns false if it is safe to retrieve the
48801 ** page from the pager layer with the 'no-content' flag set. True otherwise.
48802 */
48803 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
48804   Bitvec *p = pBt->pHasContent;
48805   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
48806 }
48807 
48808 /*
48809 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
48810 ** invoked at the conclusion of each write-transaction.
48811 */
48812 static void btreeClearHasContent(BtShared *pBt){
48813   sqlite3BitvecDestroy(pBt->pHasContent);
48814   pBt->pHasContent = 0;
48815 }
48816 
48817 /*
48818 ** Save the current cursor position in the variables BtCursor.nKey
48819 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
48820 **
48821 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
48822 ** prior to calling this routine.
48823 */
48824 static int saveCursorPosition(BtCursor *pCur){
48825   int rc;
48826 
48827   assert( CURSOR_VALID==pCur->eState );
48828   assert( 0==pCur->pKey );
48829   assert( cursorHoldsMutex(pCur) );
48830 
48831   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
48832   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
48833 
48834   /* If this is an intKey table, then the above call to BtreeKeySize()
48835   ** stores the integer key in pCur->nKey. In this case this value is
48836   ** all that is required. Otherwise, if pCur is not open on an intKey
48837   ** table, then malloc space for and store the pCur->nKey bytes of key
48838   ** data.
48839   */
48840   if( 0==pCur->apPage[0]->intKey ){
48841     void *pKey = sqlite3Malloc( (int)pCur->nKey );
48842     if( pKey ){
48843       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
48844       if( rc==SQLITE_OK ){
48845         pCur->pKey = pKey;
48846       }else{
48847         sqlite3_free(pKey);
48848       }
48849     }else{
48850       rc = SQLITE_NOMEM;
48851     }
48852   }
48853   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
48854 
48855   if( rc==SQLITE_OK ){
48856     int i;
48857     for(i=0; i<=pCur->iPage; i++){
48858       releasePage(pCur->apPage[i]);
48859       pCur->apPage[i] = 0;
48860     }
48861     pCur->iPage = -1;
48862     pCur->eState = CURSOR_REQUIRESEEK;
48863   }
48864 
48865   invalidateOverflowCache(pCur);
48866   return rc;
48867 }
48868 
48869 /*
48870 ** Save the positions of all cursors (except pExcept) that are open on
48871 ** the table  with root-page iRoot. Usually, this is called just before cursor
48872 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
48873 */
48874 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
48875   BtCursor *p;
48876   assert( sqlite3_mutex_held(pBt->mutex) );
48877   assert( pExcept==0 || pExcept->pBt==pBt );
48878   for(p=pBt->pCursor; p; p=p->pNext){
48879     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
48880         p->eState==CURSOR_VALID ){
48881       int rc = saveCursorPosition(p);
48882       if( SQLITE_OK!=rc ){
48883         return rc;
48884       }
48885     }
48886   }
48887   return SQLITE_OK;
48888 }
48889 
48890 /*
48891 ** Clear the current cursor position.
48892 */
48893 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
48894   assert( cursorHoldsMutex(pCur) );
48895   sqlite3_free(pCur->pKey);
48896   pCur->pKey = 0;
48897   pCur->eState = CURSOR_INVALID;
48898 }
48899 
48900 /*
48901 ** In this version of BtreeMoveto, pKey is a packed index record
48902 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
48903 ** record and then call BtreeMovetoUnpacked() to do the work.
48904 */
48905 static int btreeMoveto(
48906   BtCursor *pCur,     /* Cursor open on the btree to be searched */
48907   const void *pKey,   /* Packed key if the btree is an index */
48908   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
48909   int bias,           /* Bias search to the high end */
48910   int *pRes           /* Write search results here */
48911 ){
48912   int rc;                    /* Status code */
48913   UnpackedRecord *pIdxKey;   /* Unpacked index key */
48914   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
48915   char *pFree = 0;
48916 
48917   if( pKey ){
48918     assert( nKey==(i64)(int)nKey );
48919     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
48920         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
48921     );
48922     if( pIdxKey==0 ) return SQLITE_NOMEM;
48923     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
48924   }else{
48925     pIdxKey = 0;
48926   }
48927   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
48928   if( pFree ){
48929     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
48930   }
48931   return rc;
48932 }
48933 
48934 /*
48935 ** Restore the cursor to the position it was in (or as close to as possible)
48936 ** when saveCursorPosition() was called. Note that this call deletes the
48937 ** saved position info stored by saveCursorPosition(), so there can be
48938 ** at most one effective restoreCursorPosition() call after each
48939 ** saveCursorPosition().
48940 */
48941 static int btreeRestoreCursorPosition(BtCursor *pCur){
48942   int rc;
48943   assert( cursorHoldsMutex(pCur) );
48944   assert( pCur->eState>=CURSOR_REQUIRESEEK );
48945   if( pCur->eState==CURSOR_FAULT ){
48946     return pCur->skipNext;
48947   }
48948   pCur->eState = CURSOR_INVALID;
48949   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
48950   if( rc==SQLITE_OK ){
48951     sqlite3_free(pCur->pKey);
48952     pCur->pKey = 0;
48953     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
48954   }
48955   return rc;
48956 }
48957 
48958 #define restoreCursorPosition(p) \
48959   (p->eState>=CURSOR_REQUIRESEEK ? \
48960          btreeRestoreCursorPosition(p) : \
48961          SQLITE_OK)
48962 
48963 /*
48964 ** Determine whether or not a cursor has moved from the position it
48965 ** was last placed at.  Cursors can move when the row they are pointing
48966 ** at is deleted out from under them.
48967 **
48968 ** This routine returns an error code if something goes wrong.  The
48969 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
48970 */
48971 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
48972   int rc;
48973 
48974   rc = restoreCursorPosition(pCur);
48975   if( rc ){
48976     *pHasMoved = 1;
48977     return rc;
48978   }
48979   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
48980     *pHasMoved = 1;
48981   }else{
48982     *pHasMoved = 0;
48983   }
48984   return SQLITE_OK;
48985 }
48986 
48987 #ifndef SQLITE_OMIT_AUTOVACUUM
48988 /*
48989 ** Given a page number of a regular database page, return the page
48990 ** number for the pointer-map page that contains the entry for the
48991 ** input page number.
48992 **
48993 ** Return 0 (not a valid page) for pgno==1 since there is
48994 ** no pointer map associated with page 1.  The integrity_check logic
48995 ** requires that ptrmapPageno(*,1)!=1.
48996 */
48997 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
48998   int nPagesPerMapPage;
48999   Pgno iPtrMap, ret;
49000   assert( sqlite3_mutex_held(pBt->mutex) );
49001   if( pgno<2 ) return 0;
49002   nPagesPerMapPage = (pBt->usableSize/5)+1;
49003   iPtrMap = (pgno-2)/nPagesPerMapPage;
49004   ret = (iPtrMap*nPagesPerMapPage) + 2;
49005   if( ret==PENDING_BYTE_PAGE(pBt) ){
49006     ret++;
49007   }
49008   return ret;
49009 }
49010 
49011 /*
49012 ** Write an entry into the pointer map.
49013 **
49014 ** This routine updates the pointer map entry for page number 'key'
49015 ** so that it maps to type 'eType' and parent page number 'pgno'.
49016 **
49017 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
49018 ** a no-op.  If an error occurs, the appropriate error code is written
49019 ** into *pRC.
49020 */
49021 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
49022   DbPage *pDbPage;  /* The pointer map page */
49023   u8 *pPtrmap;      /* The pointer map data */
49024   Pgno iPtrmap;     /* The pointer map page number */
49025   int offset;       /* Offset in pointer map page */
49026   int rc;           /* Return code from subfunctions */
49027 
49028   if( *pRC ) return;
49029 
49030   assert( sqlite3_mutex_held(pBt->mutex) );
49031   /* The master-journal page number must never be used as a pointer map page */
49032   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
49033 
49034   assert( pBt->autoVacuum );
49035   if( key==0 ){
49036     *pRC = SQLITE_CORRUPT_BKPT;
49037     return;
49038   }
49039   iPtrmap = PTRMAP_PAGENO(pBt, key);
49040   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49041   if( rc!=SQLITE_OK ){
49042     *pRC = rc;
49043     return;
49044   }
49045   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49046   if( offset<0 ){
49047     *pRC = SQLITE_CORRUPT_BKPT;
49048     goto ptrmap_exit;
49049   }
49050   assert( offset <= (int)pBt->usableSize-5 );
49051   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49052 
49053   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
49054     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
49055     *pRC= rc = sqlite3PagerWrite(pDbPage);
49056     if( rc==SQLITE_OK ){
49057       pPtrmap[offset] = eType;
49058       put4byte(&pPtrmap[offset+1], parent);
49059     }
49060   }
49061 
49062 ptrmap_exit:
49063   sqlite3PagerUnref(pDbPage);
49064 }
49065 
49066 /*
49067 ** Read an entry from the pointer map.
49068 **
49069 ** This routine retrieves the pointer map entry for page 'key', writing
49070 ** the type and parent page number to *pEType and *pPgno respectively.
49071 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
49072 */
49073 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
49074   DbPage *pDbPage;   /* The pointer map page */
49075   int iPtrmap;       /* Pointer map page index */
49076   u8 *pPtrmap;       /* Pointer map page data */
49077   int offset;        /* Offset of entry in pointer map */
49078   int rc;
49079 
49080   assert( sqlite3_mutex_held(pBt->mutex) );
49081 
49082   iPtrmap = PTRMAP_PAGENO(pBt, key);
49083   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
49084   if( rc!=0 ){
49085     return rc;
49086   }
49087   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
49088 
49089   offset = PTRMAP_PTROFFSET(iPtrmap, key);
49090   if( offset<0 ){
49091     sqlite3PagerUnref(pDbPage);
49092     return SQLITE_CORRUPT_BKPT;
49093   }
49094   assert( offset <= (int)pBt->usableSize-5 );
49095   assert( pEType!=0 );
49096   *pEType = pPtrmap[offset];
49097   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
49098 
49099   sqlite3PagerUnref(pDbPage);
49100   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
49101   return SQLITE_OK;
49102 }
49103 
49104 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
49105   #define ptrmapPut(w,x,y,z,rc)
49106   #define ptrmapGet(w,x,y,z) SQLITE_OK
49107   #define ptrmapPutOvflPtr(x, y, rc)
49108 #endif
49109 
49110 /*
49111 ** Given a btree page and a cell index (0 means the first cell on
49112 ** the page, 1 means the second cell, and so forth) return a pointer
49113 ** to the cell content.
49114 **
49115 ** This routine works only for pages that do not contain overflow cells.
49116 */
49117 #define findCell(P,I) \
49118   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
49119 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
49120 
49121 
49122 /*
49123 ** This a more complex version of findCell() that works for
49124 ** pages that do contain overflow cells.
49125 */
49126 static u8 *findOverflowCell(MemPage *pPage, int iCell){
49127   int i;
49128   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49129   for(i=pPage->nOverflow-1; i>=0; i--){
49130     int k;
49131     struct _OvflCell *pOvfl;
49132     pOvfl = &pPage->aOvfl[i];
49133     k = pOvfl->idx;
49134     if( k<=iCell ){
49135       if( k==iCell ){
49136         return pOvfl->pCell;
49137       }
49138       iCell--;
49139     }
49140   }
49141   return findCell(pPage, iCell);
49142 }
49143 
49144 /*
49145 ** Parse a cell content block and fill in the CellInfo structure.  There
49146 ** are two versions of this function.  btreeParseCell() takes a
49147 ** cell index as the second argument and btreeParseCellPtr()
49148 ** takes a pointer to the body of the cell as its second argument.
49149 **
49150 ** Within this file, the parseCell() macro can be called instead of
49151 ** btreeParseCellPtr(). Using some compilers, this will be faster.
49152 */
49153 static void btreeParseCellPtr(
49154   MemPage *pPage,         /* Page containing the cell */
49155   u8 *pCell,              /* Pointer to the cell text. */
49156   CellInfo *pInfo         /* Fill in this structure */
49157 ){
49158   u16 n;                  /* Number bytes in cell content header */
49159   u32 nPayload;           /* Number of bytes of cell payload */
49160 
49161   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49162 
49163   pInfo->pCell = pCell;
49164   assert( pPage->leaf==0 || pPage->leaf==1 );
49165   n = pPage->childPtrSize;
49166   assert( n==4-4*pPage->leaf );
49167   if( pPage->intKey ){
49168     if( pPage->hasData ){
49169       n += getVarint32(&pCell[n], nPayload);
49170     }else{
49171       nPayload = 0;
49172     }
49173     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
49174     pInfo->nData = nPayload;
49175   }else{
49176     pInfo->nData = 0;
49177     n += getVarint32(&pCell[n], nPayload);
49178     pInfo->nKey = nPayload;
49179   }
49180   pInfo->nPayload = nPayload;
49181   pInfo->nHeader = n;
49182   testcase( nPayload==pPage->maxLocal );
49183   testcase( nPayload==pPage->maxLocal+1 );
49184   if( likely(nPayload<=pPage->maxLocal) ){
49185     /* This is the (easy) common case where the entire payload fits
49186     ** on the local page.  No overflow is required.
49187     */
49188     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
49189     pInfo->nLocal = (u16)nPayload;
49190     pInfo->iOverflow = 0;
49191   }else{
49192     /* If the payload will not fit completely on the local page, we have
49193     ** to decide how much to store locally and how much to spill onto
49194     ** overflow pages.  The strategy is to minimize the amount of unused
49195     ** space on overflow pages while keeping the amount of local storage
49196     ** in between minLocal and maxLocal.
49197     **
49198     ** Warning:  changing the way overflow payload is distributed in any
49199     ** way will result in an incompatible file format.
49200     */
49201     int minLocal;  /* Minimum amount of payload held locally */
49202     int maxLocal;  /* Maximum amount of payload held locally */
49203     int surplus;   /* Overflow payload available for local storage */
49204 
49205     minLocal = pPage->minLocal;
49206     maxLocal = pPage->maxLocal;
49207     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
49208     testcase( surplus==maxLocal );
49209     testcase( surplus==maxLocal+1 );
49210     if( surplus <= maxLocal ){
49211       pInfo->nLocal = (u16)surplus;
49212     }else{
49213       pInfo->nLocal = (u16)minLocal;
49214     }
49215     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
49216     pInfo->nSize = pInfo->iOverflow + 4;
49217   }
49218 }
49219 #define parseCell(pPage, iCell, pInfo) \
49220   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
49221 static void btreeParseCell(
49222   MemPage *pPage,         /* Page containing the cell */
49223   int iCell,              /* The cell index.  First cell is 0 */
49224   CellInfo *pInfo         /* Fill in this structure */
49225 ){
49226   parseCell(pPage, iCell, pInfo);
49227 }
49228 
49229 /*
49230 ** Compute the total number of bytes that a Cell needs in the cell
49231 ** data area of the btree-page.  The return number includes the cell
49232 ** data header and the local payload, but not any overflow page or
49233 ** the space used by the cell pointer.
49234 */
49235 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
49236   u8 *pIter = &pCell[pPage->childPtrSize];
49237   u32 nSize;
49238 
49239 #ifdef SQLITE_DEBUG
49240   /* The value returned by this function should always be the same as
49241   ** the (CellInfo.nSize) value found by doing a full parse of the
49242   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
49243   ** this function verifies that this invariant is not violated. */
49244   CellInfo debuginfo;
49245   btreeParseCellPtr(pPage, pCell, &debuginfo);
49246 #endif
49247 
49248   if( pPage->intKey ){
49249     u8 *pEnd;
49250     if( pPage->hasData ){
49251       pIter += getVarint32(pIter, nSize);
49252     }else{
49253       nSize = 0;
49254     }
49255 
49256     /* pIter now points at the 64-bit integer key value, a variable length
49257     ** integer. The following block moves pIter to point at the first byte
49258     ** past the end of the key value. */
49259     pEnd = &pIter[9];
49260     while( (*pIter++)&0x80 && pIter<pEnd );
49261   }else{
49262     pIter += getVarint32(pIter, nSize);
49263   }
49264 
49265   testcase( nSize==pPage->maxLocal );
49266   testcase( nSize==pPage->maxLocal+1 );
49267   if( nSize>pPage->maxLocal ){
49268     int minLocal = pPage->minLocal;
49269     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
49270     testcase( nSize==pPage->maxLocal );
49271     testcase( nSize==pPage->maxLocal+1 );
49272     if( nSize>pPage->maxLocal ){
49273       nSize = minLocal;
49274     }
49275     nSize += 4;
49276   }
49277   nSize += (u32)(pIter - pCell);
49278 
49279   /* The minimum size of any cell is 4 bytes. */
49280   if( nSize<4 ){
49281     nSize = 4;
49282   }
49283 
49284   assert( nSize==debuginfo.nSize );
49285   return (u16)nSize;
49286 }
49287 
49288 #ifdef SQLITE_DEBUG
49289 /* This variation on cellSizePtr() is used inside of assert() statements
49290 ** only. */
49291 static u16 cellSize(MemPage *pPage, int iCell){
49292   return cellSizePtr(pPage, findCell(pPage, iCell));
49293 }
49294 #endif
49295 
49296 #ifndef SQLITE_OMIT_AUTOVACUUM
49297 /*
49298 ** If the cell pCell, part of page pPage contains a pointer
49299 ** to an overflow page, insert an entry into the pointer-map
49300 ** for the overflow page.
49301 */
49302 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
49303   CellInfo info;
49304   if( *pRC ) return;
49305   assert( pCell!=0 );
49306   btreeParseCellPtr(pPage, pCell, &info);
49307   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
49308   if( info.iOverflow ){
49309     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
49310     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
49311   }
49312 }
49313 #endif
49314 
49315 
49316 /*
49317 ** Defragment the page given.  All Cells are moved to the
49318 ** end of the page and all free space is collected into one
49319 ** big FreeBlk that occurs in between the header and cell
49320 ** pointer array and the cell content area.
49321 */
49322 static int defragmentPage(MemPage *pPage){
49323   int i;                     /* Loop counter */
49324   int pc;                    /* Address of a i-th cell */
49325   int hdr;                   /* Offset to the page header */
49326   int size;                  /* Size of a cell */
49327   int usableSize;            /* Number of usable bytes on a page */
49328   int cellOffset;            /* Offset to the cell pointer array */
49329   int cbrk;                  /* Offset to the cell content area */
49330   int nCell;                 /* Number of cells on the page */
49331   unsigned char *data;       /* The page data */
49332   unsigned char *temp;       /* Temp area for cell content */
49333   int iCellFirst;            /* First allowable cell index */
49334   int iCellLast;             /* Last possible cell index */
49335 
49336 
49337   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49338   assert( pPage->pBt!=0 );
49339   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
49340   assert( pPage->nOverflow==0 );
49341   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49342   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
49343   data = pPage->aData;
49344   hdr = pPage->hdrOffset;
49345   cellOffset = pPage->cellOffset;
49346   nCell = pPage->nCell;
49347   assert( nCell==get2byte(&data[hdr+3]) );
49348   usableSize = pPage->pBt->usableSize;
49349   cbrk = get2byte(&data[hdr+5]);
49350   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
49351   cbrk = usableSize;
49352   iCellFirst = cellOffset + 2*nCell;
49353   iCellLast = usableSize - 4;
49354   for(i=0; i<nCell; i++){
49355     u8 *pAddr;     /* The i-th cell pointer */
49356     pAddr = &data[cellOffset + i*2];
49357     pc = get2byte(pAddr);
49358     testcase( pc==iCellFirst );
49359     testcase( pc==iCellLast );
49360 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49361     /* These conditions have already been verified in btreeInitPage()
49362     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
49363     */
49364     if( pc<iCellFirst || pc>iCellLast ){
49365       return SQLITE_CORRUPT_BKPT;
49366     }
49367 #endif
49368     assert( pc>=iCellFirst && pc<=iCellLast );
49369     size = cellSizePtr(pPage, &temp[pc]);
49370     cbrk -= size;
49371 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49372     if( cbrk<iCellFirst ){
49373       return SQLITE_CORRUPT_BKPT;
49374     }
49375 #else
49376     if( cbrk<iCellFirst || pc+size>usableSize ){
49377       return SQLITE_CORRUPT_BKPT;
49378     }
49379 #endif
49380     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
49381     testcase( cbrk+size==usableSize );
49382     testcase( pc+size==usableSize );
49383     memcpy(&data[cbrk], &temp[pc], size);
49384     put2byte(pAddr, cbrk);
49385   }
49386   assert( cbrk>=iCellFirst );
49387   put2byte(&data[hdr+5], cbrk);
49388   data[hdr+1] = 0;
49389   data[hdr+2] = 0;
49390   data[hdr+7] = 0;
49391   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
49392   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49393   if( cbrk-iCellFirst!=pPage->nFree ){
49394     return SQLITE_CORRUPT_BKPT;
49395   }
49396   return SQLITE_OK;
49397 }
49398 
49399 /*
49400 ** Allocate nByte bytes of space from within the B-Tree page passed
49401 ** as the first argument. Write into *pIdx the index into pPage->aData[]
49402 ** of the first byte of allocated space. Return either SQLITE_OK or
49403 ** an error code (usually SQLITE_CORRUPT).
49404 **
49405 ** The caller guarantees that there is sufficient space to make the
49406 ** allocation.  This routine might need to defragment in order to bring
49407 ** all the space together, however.  This routine will avoid using
49408 ** the first two bytes past the cell pointer area since presumably this
49409 ** allocation is being made in order to insert a new cell, so we will
49410 ** also end up needing a new cell pointer.
49411 */
49412 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
49413   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
49414   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
49415   int nFrag;                           /* Number of fragmented bytes on pPage */
49416   int top;                             /* First byte of cell content area */
49417   int gap;        /* First byte of gap between cell pointers and cell content */
49418   int rc;         /* Integer return code */
49419   int usableSize; /* Usable size of the page */
49420 
49421   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49422   assert( pPage->pBt );
49423   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49424   assert( nByte>=0 );  /* Minimum cell size is 4 */
49425   assert( pPage->nFree>=nByte );
49426   assert( pPage->nOverflow==0 );
49427   usableSize = pPage->pBt->usableSize;
49428   assert( nByte < usableSize-8 );
49429 
49430   nFrag = data[hdr+7];
49431   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
49432   gap = pPage->cellOffset + 2*pPage->nCell;
49433   top = get2byteNotZero(&data[hdr+5]);
49434   if( gap>top ) return SQLITE_CORRUPT_BKPT;
49435   testcase( gap+2==top );
49436   testcase( gap+1==top );
49437   testcase( gap==top );
49438 
49439   if( nFrag>=60 ){
49440     /* Always defragment highly fragmented pages */
49441     rc = defragmentPage(pPage);
49442     if( rc ) return rc;
49443     top = get2byteNotZero(&data[hdr+5]);
49444   }else if( gap+2<=top ){
49445     /* Search the freelist looking for a free slot big enough to satisfy
49446     ** the request. The allocation is made from the first free slot in
49447     ** the list that is large enough to accomadate it.
49448     */
49449     int pc, addr;
49450     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
49451       int size;            /* Size of the free slot */
49452       if( pc>usableSize-4 || pc<addr+4 ){
49453         return SQLITE_CORRUPT_BKPT;
49454       }
49455       size = get2byte(&data[pc+2]);
49456       if( size>=nByte ){
49457         int x = size - nByte;
49458         testcase( x==4 );
49459         testcase( x==3 );
49460         if( x<4 ){
49461           /* Remove the slot from the free-list. Update the number of
49462           ** fragmented bytes within the page. */
49463           memcpy(&data[addr], &data[pc], 2);
49464           data[hdr+7] = (u8)(nFrag + x);
49465         }else if( size+pc > usableSize ){
49466           return SQLITE_CORRUPT_BKPT;
49467         }else{
49468           /* The slot remains on the free-list. Reduce its size to account
49469           ** for the portion used by the new allocation. */
49470           put2byte(&data[pc+2], x);
49471         }
49472         *pIdx = pc + x;
49473         return SQLITE_OK;
49474       }
49475     }
49476   }
49477 
49478   /* Check to make sure there is enough space in the gap to satisfy
49479   ** the allocation.  If not, defragment.
49480   */
49481   testcase( gap+2+nByte==top );
49482   if( gap+2+nByte>top ){
49483     rc = defragmentPage(pPage);
49484     if( rc ) return rc;
49485     top = get2byteNotZero(&data[hdr+5]);
49486     assert( gap+nByte<=top );
49487   }
49488 
49489 
49490   /* Allocate memory from the gap in between the cell pointer array
49491   ** and the cell content area.  The btreeInitPage() call has already
49492   ** validated the freelist.  Given that the freelist is valid, there
49493   ** is no way that the allocation can extend off the end of the page.
49494   ** The assert() below verifies the previous sentence.
49495   */
49496   top -= nByte;
49497   put2byte(&data[hdr+5], top);
49498   assert( top+nByte <= (int)pPage->pBt->usableSize );
49499   *pIdx = top;
49500   return SQLITE_OK;
49501 }
49502 
49503 /*
49504 ** Return a section of the pPage->aData to the freelist.
49505 ** The first byte of the new free block is pPage->aDisk[start]
49506 ** and the size of the block is "size" bytes.
49507 **
49508 ** Most of the effort here is involved in coalesing adjacent
49509 ** free blocks into a single big free block.
49510 */
49511 static int freeSpace(MemPage *pPage, int start, int size){
49512   int addr, pbegin, hdr;
49513   int iLast;                        /* Largest possible freeblock offset */
49514   unsigned char *data = pPage->aData;
49515 
49516   assert( pPage->pBt!=0 );
49517   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49518   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
49519   assert( (start + size) <= (int)pPage->pBt->usableSize );
49520   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49521   assert( size>=0 );   /* Minimum cell size is 4 */
49522 
49523   if( pPage->pBt->secureDelete ){
49524     /* Overwrite deleted information with zeros when the secure_delete
49525     ** option is enabled */
49526     memset(&data[start], 0, size);
49527   }
49528 
49529   /* Add the space back into the linked list of freeblocks.  Note that
49530   ** even though the freeblock list was checked by btreeInitPage(),
49531   ** btreeInitPage() did not detect overlapping cells or
49532   ** freeblocks that overlapped cells.   Nor does it detect when the
49533   ** cell content area exceeds the value in the page header.  If these
49534   ** situations arise, then subsequent insert operations might corrupt
49535   ** the freelist.  So we do need to check for corruption while scanning
49536   ** the freelist.
49537   */
49538   hdr = pPage->hdrOffset;
49539   addr = hdr + 1;
49540   iLast = pPage->pBt->usableSize - 4;
49541   assert( start<=iLast );
49542   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
49543     if( pbegin<addr+4 ){
49544       return SQLITE_CORRUPT_BKPT;
49545     }
49546     addr = pbegin;
49547   }
49548   if( pbegin>iLast ){
49549     return SQLITE_CORRUPT_BKPT;
49550   }
49551   assert( pbegin>addr || pbegin==0 );
49552   put2byte(&data[addr], start);
49553   put2byte(&data[start], pbegin);
49554   put2byte(&data[start+2], size);
49555   pPage->nFree = pPage->nFree + (u16)size;
49556 
49557   /* Coalesce adjacent free blocks */
49558   addr = hdr + 1;
49559   while( (pbegin = get2byte(&data[addr]))>0 ){
49560     int pnext, psize, x;
49561     assert( pbegin>addr );
49562     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
49563     pnext = get2byte(&data[pbegin]);
49564     psize = get2byte(&data[pbegin+2]);
49565     if( pbegin + psize + 3 >= pnext && pnext>0 ){
49566       int frag = pnext - (pbegin+psize);
49567       if( (frag<0) || (frag>(int)data[hdr+7]) ){
49568         return SQLITE_CORRUPT_BKPT;
49569       }
49570       data[hdr+7] -= (u8)frag;
49571       x = get2byte(&data[pnext]);
49572       put2byte(&data[pbegin], x);
49573       x = pnext + get2byte(&data[pnext+2]) - pbegin;
49574       put2byte(&data[pbegin+2], x);
49575     }else{
49576       addr = pbegin;
49577     }
49578   }
49579 
49580   /* If the cell content area begins with a freeblock, remove it. */
49581   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
49582     int top;
49583     pbegin = get2byte(&data[hdr+1]);
49584     memcpy(&data[hdr+1], &data[pbegin], 2);
49585     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
49586     put2byte(&data[hdr+5], top);
49587   }
49588   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49589   return SQLITE_OK;
49590 }
49591 
49592 /*
49593 ** Decode the flags byte (the first byte of the header) for a page
49594 ** and initialize fields of the MemPage structure accordingly.
49595 **
49596 ** Only the following combinations are supported.  Anything different
49597 ** indicates a corrupt database files:
49598 **
49599 **         PTF_ZERODATA
49600 **         PTF_ZERODATA | PTF_LEAF
49601 **         PTF_LEAFDATA | PTF_INTKEY
49602 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
49603 */
49604 static int decodeFlags(MemPage *pPage, int flagByte){
49605   BtShared *pBt;     /* A copy of pPage->pBt */
49606 
49607   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
49608   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49609   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
49610   flagByte &= ~PTF_LEAF;
49611   pPage->childPtrSize = 4-4*pPage->leaf;
49612   pBt = pPage->pBt;
49613   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
49614     pPage->intKey = 1;
49615     pPage->hasData = pPage->leaf;
49616     pPage->maxLocal = pBt->maxLeaf;
49617     pPage->minLocal = pBt->minLeaf;
49618   }else if( flagByte==PTF_ZERODATA ){
49619     pPage->intKey = 0;
49620     pPage->hasData = 0;
49621     pPage->maxLocal = pBt->maxLocal;
49622     pPage->minLocal = pBt->minLocal;
49623   }else{
49624     return SQLITE_CORRUPT_BKPT;
49625   }
49626   return SQLITE_OK;
49627 }
49628 
49629 /*
49630 ** Initialize the auxiliary information for a disk block.
49631 **
49632 ** Return SQLITE_OK on success.  If we see that the page does
49633 ** not contain a well-formed database page, then return
49634 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
49635 ** guarantee that the page is well-formed.  It only shows that
49636 ** we failed to detect any corruption.
49637 */
49638 static int btreeInitPage(MemPage *pPage){
49639 
49640   assert( pPage->pBt!=0 );
49641   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49642   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
49643   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
49644   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
49645 
49646   if( !pPage->isInit ){
49647     u16 pc;            /* Address of a freeblock within pPage->aData[] */
49648     u8 hdr;            /* Offset to beginning of page header */
49649     u8 *data;          /* Equal to pPage->aData */
49650     BtShared *pBt;        /* The main btree structure */
49651     int usableSize;    /* Amount of usable space on each page */
49652     u16 cellOffset;    /* Offset from start of page to first cell pointer */
49653     int nFree;         /* Number of unused bytes on the page */
49654     int top;           /* First byte of the cell content area */
49655     int iCellFirst;    /* First allowable cell or freeblock offset */
49656     int iCellLast;     /* Last possible cell or freeblock offset */
49657 
49658     pBt = pPage->pBt;
49659 
49660     hdr = pPage->hdrOffset;
49661     data = pPage->aData;
49662     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
49663     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49664     pPage->maskPage = (u16)(pBt->pageSize - 1);
49665     pPage->nOverflow = 0;
49666     usableSize = pBt->usableSize;
49667     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
49668     top = get2byteNotZero(&data[hdr+5]);
49669     pPage->nCell = get2byte(&data[hdr+3]);
49670     if( pPage->nCell>MX_CELL(pBt) ){
49671       /* To many cells for a single page.  The page must be corrupt */
49672       return SQLITE_CORRUPT_BKPT;
49673     }
49674     testcase( pPage->nCell==MX_CELL(pBt) );
49675 
49676     /* A malformed database page might cause us to read past the end
49677     ** of page when parsing a cell.
49678     **
49679     ** The following block of code checks early to see if a cell extends
49680     ** past the end of a page boundary and causes SQLITE_CORRUPT to be
49681     ** returned if it does.
49682     */
49683     iCellFirst = cellOffset + 2*pPage->nCell;
49684     iCellLast = usableSize - 4;
49685 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
49686     {
49687       int i;            /* Index into the cell pointer array */
49688       int sz;           /* Size of a cell */
49689 
49690       if( !pPage->leaf ) iCellLast--;
49691       for(i=0; i<pPage->nCell; i++){
49692         pc = get2byte(&data[cellOffset+i*2]);
49693         testcase( pc==iCellFirst );
49694         testcase( pc==iCellLast );
49695         if( pc<iCellFirst || pc>iCellLast ){
49696           return SQLITE_CORRUPT_BKPT;
49697         }
49698         sz = cellSizePtr(pPage, &data[pc]);
49699         testcase( pc+sz==usableSize );
49700         if( pc+sz>usableSize ){
49701           return SQLITE_CORRUPT_BKPT;
49702         }
49703       }
49704       if( !pPage->leaf ) iCellLast++;
49705     }
49706 #endif
49707 
49708     /* Compute the total free space on the page */
49709     pc = get2byte(&data[hdr+1]);
49710     nFree = data[hdr+7] + top;
49711     while( pc>0 ){
49712       u16 next, size;
49713       if( pc<iCellFirst || pc>iCellLast ){
49714         /* Start of free block is off the page */
49715         return SQLITE_CORRUPT_BKPT;
49716       }
49717       next = get2byte(&data[pc]);
49718       size = get2byte(&data[pc+2]);
49719       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
49720         /* Free blocks must be in ascending order. And the last byte of
49721 	** the free-block must lie on the database page.  */
49722         return SQLITE_CORRUPT_BKPT;
49723       }
49724       nFree = nFree + size;
49725       pc = next;
49726     }
49727 
49728     /* At this point, nFree contains the sum of the offset to the start
49729     ** of the cell-content area plus the number of free bytes within
49730     ** the cell-content area. If this is greater than the usable-size
49731     ** of the page, then the page must be corrupted. This check also
49732     ** serves to verify that the offset to the start of the cell-content
49733     ** area, according to the page header, lies within the page.
49734     */
49735     if( nFree>usableSize ){
49736       return SQLITE_CORRUPT_BKPT;
49737     }
49738     pPage->nFree = (u16)(nFree - iCellFirst);
49739     pPage->isInit = 1;
49740   }
49741   return SQLITE_OK;
49742 }
49743 
49744 /*
49745 ** Set up a raw page so that it looks like a database page holding
49746 ** no entries.
49747 */
49748 static void zeroPage(MemPage *pPage, int flags){
49749   unsigned char *data = pPage->aData;
49750   BtShared *pBt = pPage->pBt;
49751   u8 hdr = pPage->hdrOffset;
49752   u16 first;
49753 
49754   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
49755   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49756   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
49757   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
49758   assert( sqlite3_mutex_held(pBt->mutex) );
49759   if( pBt->secureDelete ){
49760     memset(&data[hdr], 0, pBt->usableSize - hdr);
49761   }
49762   data[hdr] = (char)flags;
49763   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
49764   memset(&data[hdr+1], 0, 4);
49765   data[hdr+7] = 0;
49766   put2byte(&data[hdr+5], pBt->usableSize);
49767   pPage->nFree = (u16)(pBt->usableSize - first);
49768   decodeFlags(pPage, flags);
49769   pPage->hdrOffset = hdr;
49770   pPage->cellOffset = first;
49771   pPage->nOverflow = 0;
49772   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
49773   pPage->maskPage = (u16)(pBt->pageSize - 1);
49774   pPage->nCell = 0;
49775   pPage->isInit = 1;
49776 }
49777 
49778 
49779 /*
49780 ** Convert a DbPage obtained from the pager into a MemPage used by
49781 ** the btree layer.
49782 */
49783 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
49784   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
49785   pPage->aData = sqlite3PagerGetData(pDbPage);
49786   pPage->pDbPage = pDbPage;
49787   pPage->pBt = pBt;
49788   pPage->pgno = pgno;
49789   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
49790   return pPage;
49791 }
49792 
49793 /*
49794 ** Get a page from the pager.  Initialize the MemPage.pBt and
49795 ** MemPage.aData elements if needed.
49796 **
49797 ** If the noContent flag is set, it means that we do not care about
49798 ** the content of the page at this time.  So do not go to the disk
49799 ** to fetch the content.  Just fill in the content with zeros for now.
49800 ** If in the future we call sqlite3PagerWrite() on this page, that
49801 ** means we have started to be concerned about content and the disk
49802 ** read should occur at that point.
49803 */
49804 static int btreeGetPage(
49805   BtShared *pBt,       /* The btree */
49806   Pgno pgno,           /* Number of the page to fetch */
49807   MemPage **ppPage,    /* Return the page in this parameter */
49808   int noContent        /* Do not load page content if true */
49809 ){
49810   int rc;
49811   DbPage *pDbPage;
49812 
49813   assert( sqlite3_mutex_held(pBt->mutex) );
49814   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
49815   if( rc ) return rc;
49816   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
49817   return SQLITE_OK;
49818 }
49819 
49820 /*
49821 ** Retrieve a page from the pager cache. If the requested page is not
49822 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
49823 ** MemPage.aData elements if needed.
49824 */
49825 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
49826   DbPage *pDbPage;
49827   assert( sqlite3_mutex_held(pBt->mutex) );
49828   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
49829   if( pDbPage ){
49830     return btreePageFromDbPage(pDbPage, pgno, pBt);
49831   }
49832   return 0;
49833 }
49834 
49835 /*
49836 ** Return the size of the database file in pages. If there is any kind of
49837 ** error, return ((unsigned int)-1).
49838 */
49839 static Pgno btreePagecount(BtShared *pBt){
49840   return pBt->nPage;
49841 }
49842 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
49843   assert( sqlite3BtreeHoldsMutex(p) );
49844   assert( ((p->pBt->nPage)&0x8000000)==0 );
49845   return (int)btreePagecount(p->pBt);
49846 }
49847 
49848 /*
49849 ** Get a page from the pager and initialize it.  This routine is just a
49850 ** convenience wrapper around separate calls to btreeGetPage() and
49851 ** btreeInitPage().
49852 **
49853 ** If an error occurs, then the value *ppPage is set to is undefined. It
49854 ** may remain unchanged, or it may be set to an invalid value.
49855 */
49856 static int getAndInitPage(
49857   BtShared *pBt,          /* The database file */
49858   Pgno pgno,           /* Number of the page to get */
49859   MemPage **ppPage     /* Write the page pointer here */
49860 ){
49861   int rc;
49862   assert( sqlite3_mutex_held(pBt->mutex) );
49863 
49864   if( pgno>btreePagecount(pBt) ){
49865     rc = SQLITE_CORRUPT_BKPT;
49866   }else{
49867     rc = btreeGetPage(pBt, pgno, ppPage, 0);
49868     if( rc==SQLITE_OK ){
49869       rc = btreeInitPage(*ppPage);
49870       if( rc!=SQLITE_OK ){
49871         releasePage(*ppPage);
49872       }
49873     }
49874   }
49875 
49876   testcase( pgno==0 );
49877   assert( pgno!=0 || rc==SQLITE_CORRUPT );
49878   return rc;
49879 }
49880 
49881 /*
49882 ** Release a MemPage.  This should be called once for each prior
49883 ** call to btreeGetPage.
49884 */
49885 static void releasePage(MemPage *pPage){
49886   if( pPage ){
49887     assert( pPage->aData );
49888     assert( pPage->pBt );
49889     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
49890     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
49891     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49892     sqlite3PagerUnref(pPage->pDbPage);
49893   }
49894 }
49895 
49896 /*
49897 ** During a rollback, when the pager reloads information into the cache
49898 ** so that the cache is restored to its original state at the start of
49899 ** the transaction, for each page restored this routine is called.
49900 **
49901 ** This routine needs to reset the extra data section at the end of the
49902 ** page to agree with the restored data.
49903 */
49904 static void pageReinit(DbPage *pData){
49905   MemPage *pPage;
49906   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
49907   assert( sqlite3PagerPageRefcount(pData)>0 );
49908   if( pPage->isInit ){
49909     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
49910     pPage->isInit = 0;
49911     if( sqlite3PagerPageRefcount(pData)>1 ){
49912       /* pPage might not be a btree page;  it might be an overflow page
49913       ** or ptrmap page or a free page.  In those cases, the following
49914       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
49915       ** But no harm is done by this.  And it is very important that
49916       ** btreeInitPage() be called on every btree page so we make
49917       ** the call for every page that comes in for re-initing. */
49918       btreeInitPage(pPage);
49919     }
49920   }
49921 }
49922 
49923 /*
49924 ** Invoke the busy handler for a btree.
49925 */
49926 static int btreeInvokeBusyHandler(void *pArg){
49927   BtShared *pBt = (BtShared*)pArg;
49928   assert( pBt->db );
49929   assert( sqlite3_mutex_held(pBt->db->mutex) );
49930   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
49931 }
49932 
49933 /*
49934 ** Open a database file.
49935 **
49936 ** zFilename is the name of the database file.  If zFilename is NULL
49937 ** then an ephemeral database is created.  The ephemeral database might
49938 ** be exclusively in memory, or it might use a disk-based memory cache.
49939 ** Either way, the ephemeral database will be automatically deleted
49940 ** when sqlite3BtreeClose() is called.
49941 **
49942 ** If zFilename is ":memory:" then an in-memory database is created
49943 ** that is automatically destroyed when it is closed.
49944 **
49945 ** The "flags" parameter is a bitmask that might contain bits
49946 ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK.  The BTREE_NO_READLOCK
49947 ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
49948 ** These flags are passed through into sqlite3PagerOpen() and must
49949 ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
49950 **
49951 ** If the database is already opened in the same database connection
49952 ** and we are in shared cache mode, then the open will fail with an
49953 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
49954 ** objects in the same database connection since doing so will lead
49955 ** to problems with locking.
49956 */
49957 SQLITE_PRIVATE int sqlite3BtreeOpen(
49958   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
49959   const char *zFilename,  /* Name of the file containing the BTree database */
49960   sqlite3 *db,            /* Associated database handle */
49961   Btree **ppBtree,        /* Pointer to new Btree object written here */
49962   int flags,              /* Options */
49963   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
49964 ){
49965   BtShared *pBt = 0;             /* Shared part of btree structure */
49966   Btree *p;                      /* Handle to return */
49967   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
49968   int rc = SQLITE_OK;            /* Result code from this function */
49969   u8 nReserve;                   /* Byte of unused space on each page */
49970   unsigned char zDbHeader[100];  /* Database header content */
49971 
49972   /* True if opening an ephemeral, temporary database */
49973   const int isTempDb = zFilename==0 || zFilename[0]==0;
49974 
49975   /* Set the variable isMemdb to true for an in-memory database, or
49976   ** false for a file-based database.
49977   */
49978 #ifdef SQLITE_OMIT_MEMORYDB
49979   const int isMemdb = 0;
49980 #else
49981   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
49982                        || (isTempDb && sqlite3TempInMemory(db));
49983 #endif
49984 
49985   assert( db!=0 );
49986   assert( pVfs!=0 );
49987   assert( sqlite3_mutex_held(db->mutex) );
49988   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
49989 
49990   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
49991   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
49992 
49993   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
49994   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
49995 
49996   if( db->flags & SQLITE_NoReadlock ){
49997     flags |= BTREE_NO_READLOCK;
49998   }
49999   if( isMemdb ){
50000     flags |= BTREE_MEMORY;
50001   }
50002   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
50003     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
50004   }
50005   p = sqlite3MallocZero(sizeof(Btree));
50006   if( !p ){
50007     return SQLITE_NOMEM;
50008   }
50009   p->inTrans = TRANS_NONE;
50010   p->db = db;
50011 #ifndef SQLITE_OMIT_SHARED_CACHE
50012   p->lock.pBtree = p;
50013   p->lock.iTable = 1;
50014 #endif
50015 
50016 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50017   /*
50018   ** If this Btree is a candidate for shared cache, try to find an
50019   ** existing BtShared object that we can share with
50020   */
50021   if( isMemdb==0 && isTempDb==0 ){
50022     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
50023       int nFullPathname = pVfs->mxPathname+1;
50024       char *zFullPathname = sqlite3Malloc(nFullPathname);
50025       sqlite3_mutex *mutexShared;
50026       p->sharable = 1;
50027       if( !zFullPathname ){
50028         sqlite3_free(p);
50029         return SQLITE_NOMEM;
50030       }
50031       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
50032       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
50033       sqlite3_mutex_enter(mutexOpen);
50034       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50035       sqlite3_mutex_enter(mutexShared);
50036       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
50037         assert( pBt->nRef>0 );
50038         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
50039                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
50040           int iDb;
50041           for(iDb=db->nDb-1; iDb>=0; iDb--){
50042             Btree *pExisting = db->aDb[iDb].pBt;
50043             if( pExisting && pExisting->pBt==pBt ){
50044               sqlite3_mutex_leave(mutexShared);
50045               sqlite3_mutex_leave(mutexOpen);
50046               sqlite3_free(zFullPathname);
50047               sqlite3_free(p);
50048               return SQLITE_CONSTRAINT;
50049             }
50050           }
50051           p->pBt = pBt;
50052           pBt->nRef++;
50053           break;
50054         }
50055       }
50056       sqlite3_mutex_leave(mutexShared);
50057       sqlite3_free(zFullPathname);
50058     }
50059 #ifdef SQLITE_DEBUG
50060     else{
50061       /* In debug mode, we mark all persistent databases as sharable
50062       ** even when they are not.  This exercises the locking code and
50063       ** gives more opportunity for asserts(sqlite3_mutex_held())
50064       ** statements to find locking problems.
50065       */
50066       p->sharable = 1;
50067     }
50068 #endif
50069   }
50070 #endif
50071   if( pBt==0 ){
50072     /*
50073     ** The following asserts make sure that structures used by the btree are
50074     ** the right size.  This is to guard against size changes that result
50075     ** when compiling on a different architecture.
50076     */
50077     assert( sizeof(i64)==8 || sizeof(i64)==4 );
50078     assert( sizeof(u64)==8 || sizeof(u64)==4 );
50079     assert( sizeof(u32)==4 );
50080     assert( sizeof(u16)==2 );
50081     assert( sizeof(Pgno)==4 );
50082 
50083     pBt = sqlite3MallocZero( sizeof(*pBt) );
50084     if( pBt==0 ){
50085       rc = SQLITE_NOMEM;
50086       goto btree_open_out;
50087     }
50088     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
50089                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
50090     if( rc==SQLITE_OK ){
50091       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
50092     }
50093     if( rc!=SQLITE_OK ){
50094       goto btree_open_out;
50095     }
50096     pBt->openFlags = (u8)flags;
50097     pBt->db = db;
50098     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
50099     p->pBt = pBt;
50100 
50101     pBt->pCursor = 0;
50102     pBt->pPage1 = 0;
50103     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
50104 #ifdef SQLITE_SECURE_DELETE
50105     pBt->secureDelete = 1;
50106 #endif
50107     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
50108     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
50109          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
50110       pBt->pageSize = 0;
50111 #ifndef SQLITE_OMIT_AUTOVACUUM
50112       /* If the magic name ":memory:" will create an in-memory database, then
50113       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
50114       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
50115       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
50116       ** regular file-name. In this case the auto-vacuum applies as per normal.
50117       */
50118       if( zFilename && !isMemdb ){
50119         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
50120         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
50121       }
50122 #endif
50123       nReserve = 0;
50124     }else{
50125       nReserve = zDbHeader[20];
50126       pBt->pageSizeFixed = 1;
50127 #ifndef SQLITE_OMIT_AUTOVACUUM
50128       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
50129       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
50130 #endif
50131     }
50132     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50133     if( rc ) goto btree_open_out;
50134     pBt->usableSize = pBt->pageSize - nReserve;
50135     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
50136 
50137 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50138     /* Add the new BtShared object to the linked list sharable BtShareds.
50139     */
50140     if( p->sharable ){
50141       sqlite3_mutex *mutexShared;
50142       pBt->nRef = 1;
50143       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50144       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
50145         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
50146         if( pBt->mutex==0 ){
50147           rc = SQLITE_NOMEM;
50148           db->mallocFailed = 0;
50149           goto btree_open_out;
50150         }
50151       }
50152       sqlite3_mutex_enter(mutexShared);
50153       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
50154       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
50155       sqlite3_mutex_leave(mutexShared);
50156     }
50157 #endif
50158   }
50159 
50160 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
50161   /* If the new Btree uses a sharable pBtShared, then link the new
50162   ** Btree into the list of all sharable Btrees for the same connection.
50163   ** The list is kept in ascending order by pBt address.
50164   */
50165   if( p->sharable ){
50166     int i;
50167     Btree *pSib;
50168     for(i=0; i<db->nDb; i++){
50169       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
50170         while( pSib->pPrev ){ pSib = pSib->pPrev; }
50171         if( p->pBt<pSib->pBt ){
50172           p->pNext = pSib;
50173           p->pPrev = 0;
50174           pSib->pPrev = p;
50175         }else{
50176           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
50177             pSib = pSib->pNext;
50178           }
50179           p->pNext = pSib->pNext;
50180           p->pPrev = pSib;
50181           if( p->pNext ){
50182             p->pNext->pPrev = p;
50183           }
50184           pSib->pNext = p;
50185         }
50186         break;
50187       }
50188     }
50189   }
50190 #endif
50191   *ppBtree = p;
50192 
50193 btree_open_out:
50194   if( rc!=SQLITE_OK ){
50195     if( pBt && pBt->pPager ){
50196       sqlite3PagerClose(pBt->pPager);
50197     }
50198     sqlite3_free(pBt);
50199     sqlite3_free(p);
50200     *ppBtree = 0;
50201   }else{
50202     /* If the B-Tree was successfully opened, set the pager-cache size to the
50203     ** default value. Except, when opening on an existing shared pager-cache,
50204     ** do not change the pager-cache size.
50205     */
50206     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
50207       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
50208     }
50209   }
50210   if( mutexOpen ){
50211     assert( sqlite3_mutex_held(mutexOpen) );
50212     sqlite3_mutex_leave(mutexOpen);
50213   }
50214   return rc;
50215 }
50216 
50217 /*
50218 ** Decrement the BtShared.nRef counter.  When it reaches zero,
50219 ** remove the BtShared structure from the sharing list.  Return
50220 ** true if the BtShared.nRef counter reaches zero and return
50221 ** false if it is still positive.
50222 */
50223 static int removeFromSharingList(BtShared *pBt){
50224 #ifndef SQLITE_OMIT_SHARED_CACHE
50225   sqlite3_mutex *pMaster;
50226   BtShared *pList;
50227   int removed = 0;
50228 
50229   assert( sqlite3_mutex_notheld(pBt->mutex) );
50230   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
50231   sqlite3_mutex_enter(pMaster);
50232   pBt->nRef--;
50233   if( pBt->nRef<=0 ){
50234     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
50235       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
50236     }else{
50237       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
50238       while( ALWAYS(pList) && pList->pNext!=pBt ){
50239         pList=pList->pNext;
50240       }
50241       if( ALWAYS(pList) ){
50242         pList->pNext = pBt->pNext;
50243       }
50244     }
50245     if( SQLITE_THREADSAFE ){
50246       sqlite3_mutex_free(pBt->mutex);
50247     }
50248     removed = 1;
50249   }
50250   sqlite3_mutex_leave(pMaster);
50251   return removed;
50252 #else
50253   return 1;
50254 #endif
50255 }
50256 
50257 /*
50258 ** Make sure pBt->pTmpSpace points to an allocation of
50259 ** MX_CELL_SIZE(pBt) bytes.
50260 */
50261 static void allocateTempSpace(BtShared *pBt){
50262   if( !pBt->pTmpSpace ){
50263     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
50264   }
50265 }
50266 
50267 /*
50268 ** Free the pBt->pTmpSpace allocation
50269 */
50270 static void freeTempSpace(BtShared *pBt){
50271   sqlite3PageFree( pBt->pTmpSpace);
50272   pBt->pTmpSpace = 0;
50273 }
50274 
50275 /*
50276 ** Close an open database and invalidate all cursors.
50277 */
50278 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
50279   BtShared *pBt = p->pBt;
50280   BtCursor *pCur;
50281 
50282   /* Close all cursors opened via this handle.  */
50283   assert( sqlite3_mutex_held(p->db->mutex) );
50284   sqlite3BtreeEnter(p);
50285   pCur = pBt->pCursor;
50286   while( pCur ){
50287     BtCursor *pTmp = pCur;
50288     pCur = pCur->pNext;
50289     if( pTmp->pBtree==p ){
50290       sqlite3BtreeCloseCursor(pTmp);
50291     }
50292   }
50293 
50294   /* Rollback any active transaction and free the handle structure.
50295   ** The call to sqlite3BtreeRollback() drops any table-locks held by
50296   ** this handle.
50297   */
50298   sqlite3BtreeRollback(p);
50299   sqlite3BtreeLeave(p);
50300 
50301   /* If there are still other outstanding references to the shared-btree
50302   ** structure, return now. The remainder of this procedure cleans
50303   ** up the shared-btree.
50304   */
50305   assert( p->wantToLock==0 && p->locked==0 );
50306   if( !p->sharable || removeFromSharingList(pBt) ){
50307     /* The pBt is no longer on the sharing list, so we can access
50308     ** it without having to hold the mutex.
50309     **
50310     ** Clean out and delete the BtShared object.
50311     */
50312     assert( !pBt->pCursor );
50313     sqlite3PagerClose(pBt->pPager);
50314     if( pBt->xFreeSchema && pBt->pSchema ){
50315       pBt->xFreeSchema(pBt->pSchema);
50316     }
50317     sqlite3DbFree(0, pBt->pSchema);
50318     freeTempSpace(pBt);
50319     sqlite3_free(pBt);
50320   }
50321 
50322 #ifndef SQLITE_OMIT_SHARED_CACHE
50323   assert( p->wantToLock==0 );
50324   assert( p->locked==0 );
50325   if( p->pPrev ) p->pPrev->pNext = p->pNext;
50326   if( p->pNext ) p->pNext->pPrev = p->pPrev;
50327 #endif
50328 
50329   sqlite3_free(p);
50330   return SQLITE_OK;
50331 }
50332 
50333 /*
50334 ** Change the limit on the number of pages allowed in the cache.
50335 **
50336 ** The maximum number of cache pages is set to the absolute
50337 ** value of mxPage.  If mxPage is negative, the pager will
50338 ** operate asynchronously - it will not stop to do fsync()s
50339 ** to insure data is written to the disk surface before
50340 ** continuing.  Transactions still work if synchronous is off,
50341 ** and the database cannot be corrupted if this program
50342 ** crashes.  But if the operating system crashes or there is
50343 ** an abrupt power failure when synchronous is off, the database
50344 ** could be left in an inconsistent and unrecoverable state.
50345 ** Synchronous is on by default so database corruption is not
50346 ** normally a worry.
50347 */
50348 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
50349   BtShared *pBt = p->pBt;
50350   assert( sqlite3_mutex_held(p->db->mutex) );
50351   sqlite3BtreeEnter(p);
50352   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
50353   sqlite3BtreeLeave(p);
50354   return SQLITE_OK;
50355 }
50356 
50357 /*
50358 ** Change the way data is synced to disk in order to increase or decrease
50359 ** how well the database resists damage due to OS crashes and power
50360 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
50361 ** there is a high probability of damage)  Level 2 is the default.  There
50362 ** is a very low but non-zero probability of damage.  Level 3 reduces the
50363 ** probability of damage to near zero but with a write performance reduction.
50364 */
50365 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
50366 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
50367   Btree *p,              /* The btree to set the safety level on */
50368   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
50369   int fullSync,          /* PRAGMA fullfsync. */
50370   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
50371 ){
50372   BtShared *pBt = p->pBt;
50373   assert( sqlite3_mutex_held(p->db->mutex) );
50374   assert( level>=1 && level<=3 );
50375   sqlite3BtreeEnter(p);
50376   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
50377   sqlite3BtreeLeave(p);
50378   return SQLITE_OK;
50379 }
50380 #endif
50381 
50382 /*
50383 ** Return TRUE if the given btree is set to safety level 1.  In other
50384 ** words, return TRUE if no sync() occurs on the disk files.
50385 */
50386 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
50387   BtShared *pBt = p->pBt;
50388   int rc;
50389   assert( sqlite3_mutex_held(p->db->mutex) );
50390   sqlite3BtreeEnter(p);
50391   assert( pBt && pBt->pPager );
50392   rc = sqlite3PagerNosync(pBt->pPager);
50393   sqlite3BtreeLeave(p);
50394   return rc;
50395 }
50396 
50397 /*
50398 ** Change the default pages size and the number of reserved bytes per page.
50399 ** Or, if the page size has already been fixed, return SQLITE_READONLY
50400 ** without changing anything.
50401 **
50402 ** The page size must be a power of 2 between 512 and 65536.  If the page
50403 ** size supplied does not meet this constraint then the page size is not
50404 ** changed.
50405 **
50406 ** Page sizes are constrained to be a power of two so that the region
50407 ** of the database file used for locking (beginning at PENDING_BYTE,
50408 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
50409 ** at the beginning of a page.
50410 **
50411 ** If parameter nReserve is less than zero, then the number of reserved
50412 ** bytes per page is left unchanged.
50413 **
50414 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
50415 ** and autovacuum mode can no longer be changed.
50416 */
50417 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
50418   int rc = SQLITE_OK;
50419   BtShared *pBt = p->pBt;
50420   assert( nReserve>=-1 && nReserve<=255 );
50421   sqlite3BtreeEnter(p);
50422   if( pBt->pageSizeFixed ){
50423     sqlite3BtreeLeave(p);
50424     return SQLITE_READONLY;
50425   }
50426   if( nReserve<0 ){
50427     nReserve = pBt->pageSize - pBt->usableSize;
50428   }
50429   assert( nReserve>=0 && nReserve<=255 );
50430   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
50431         ((pageSize-1)&pageSize)==0 ){
50432     assert( (pageSize & 7)==0 );
50433     assert( !pBt->pPage1 && !pBt->pCursor );
50434     pBt->pageSize = (u32)pageSize;
50435     freeTempSpace(pBt);
50436   }
50437   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
50438   pBt->usableSize = pBt->pageSize - (u16)nReserve;
50439   if( iFix ) pBt->pageSizeFixed = 1;
50440   sqlite3BtreeLeave(p);
50441   return rc;
50442 }
50443 
50444 /*
50445 ** Return the currently defined page size
50446 */
50447 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
50448   return p->pBt->pageSize;
50449 }
50450 
50451 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
50452 /*
50453 ** Return the number of bytes of space at the end of every page that
50454 ** are intentually left unused.  This is the "reserved" space that is
50455 ** sometimes used by extensions.
50456 */
50457 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
50458   int n;
50459   sqlite3BtreeEnter(p);
50460   n = p->pBt->pageSize - p->pBt->usableSize;
50461   sqlite3BtreeLeave(p);
50462   return n;
50463 }
50464 
50465 /*
50466 ** Set the maximum page count for a database if mxPage is positive.
50467 ** No changes are made if mxPage is 0 or negative.
50468 ** Regardless of the value of mxPage, return the maximum page count.
50469 */
50470 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
50471   int n;
50472   sqlite3BtreeEnter(p);
50473   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
50474   sqlite3BtreeLeave(p);
50475   return n;
50476 }
50477 
50478 /*
50479 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
50480 ** then make no changes.  Always return the value of the secureDelete
50481 ** setting after the change.
50482 */
50483 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
50484   int b;
50485   if( p==0 ) return 0;
50486   sqlite3BtreeEnter(p);
50487   if( newFlag>=0 ){
50488     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
50489   }
50490   b = p->pBt->secureDelete;
50491   sqlite3BtreeLeave(p);
50492   return b;
50493 }
50494 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
50495 
50496 /*
50497 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
50498 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
50499 ** is disabled. The default value for the auto-vacuum property is
50500 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
50501 */
50502 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
50503 #ifdef SQLITE_OMIT_AUTOVACUUM
50504   return SQLITE_READONLY;
50505 #else
50506   BtShared *pBt = p->pBt;
50507   int rc = SQLITE_OK;
50508   u8 av = (u8)autoVacuum;
50509 
50510   sqlite3BtreeEnter(p);
50511   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
50512     rc = SQLITE_READONLY;
50513   }else{
50514     pBt->autoVacuum = av ?1:0;
50515     pBt->incrVacuum = av==2 ?1:0;
50516   }
50517   sqlite3BtreeLeave(p);
50518   return rc;
50519 #endif
50520 }
50521 
50522 /*
50523 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
50524 ** enabled 1 is returned. Otherwise 0.
50525 */
50526 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
50527 #ifdef SQLITE_OMIT_AUTOVACUUM
50528   return BTREE_AUTOVACUUM_NONE;
50529 #else
50530   int rc;
50531   sqlite3BtreeEnter(p);
50532   rc = (
50533     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
50534     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
50535     BTREE_AUTOVACUUM_INCR
50536   );
50537   sqlite3BtreeLeave(p);
50538   return rc;
50539 #endif
50540 }
50541 
50542 
50543 /*
50544 ** Get a reference to pPage1 of the database file.  This will
50545 ** also acquire a readlock on that file.
50546 **
50547 ** SQLITE_OK is returned on success.  If the file is not a
50548 ** well-formed database file, then SQLITE_CORRUPT is returned.
50549 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
50550 ** is returned if we run out of memory.
50551 */
50552 static int lockBtree(BtShared *pBt){
50553   int rc;              /* Result code from subfunctions */
50554   MemPage *pPage1;     /* Page 1 of the database file */
50555   int nPage;           /* Number of pages in the database */
50556   int nPageFile = 0;   /* Number of pages in the database file */
50557   int nPageHeader;     /* Number of pages in the database according to hdr */
50558 
50559   assert( sqlite3_mutex_held(pBt->mutex) );
50560   assert( pBt->pPage1==0 );
50561   rc = sqlite3PagerSharedLock(pBt->pPager);
50562   if( rc!=SQLITE_OK ) return rc;
50563   rc = btreeGetPage(pBt, 1, &pPage1, 0);
50564   if( rc!=SQLITE_OK ) return rc;
50565 
50566   /* Do some checking to help insure the file we opened really is
50567   ** a valid database file.
50568   */
50569   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
50570   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
50571   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
50572     nPage = nPageFile;
50573   }
50574   if( nPage>0 ){
50575     u32 pageSize;
50576     u32 usableSize;
50577     u8 *page1 = pPage1->aData;
50578     rc = SQLITE_NOTADB;
50579     if( memcmp(page1, zMagicHeader, 16)!=0 ){
50580       goto page1_init_failed;
50581     }
50582 
50583 #ifdef SQLITE_OMIT_WAL
50584     if( page1[18]>1 ){
50585       pBt->readOnly = 1;
50586     }
50587     if( page1[19]>1 ){
50588       goto page1_init_failed;
50589     }
50590 #else
50591     if( page1[18]>2 ){
50592       pBt->readOnly = 1;
50593     }
50594     if( page1[19]>2 ){
50595       goto page1_init_failed;
50596     }
50597 
50598     /* If the write version is set to 2, this database should be accessed
50599     ** in WAL mode. If the log is not already open, open it now. Then
50600     ** return SQLITE_OK and return without populating BtShared.pPage1.
50601     ** The caller detects this and calls this function again. This is
50602     ** required as the version of page 1 currently in the page1 buffer
50603     ** may not be the latest version - there may be a newer one in the log
50604     ** file.
50605     */
50606     if( page1[19]==2 && pBt->doNotUseWAL==0 ){
50607       int isOpen = 0;
50608       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
50609       if( rc!=SQLITE_OK ){
50610         goto page1_init_failed;
50611       }else if( isOpen==0 ){
50612         releasePage(pPage1);
50613         return SQLITE_OK;
50614       }
50615       rc = SQLITE_NOTADB;
50616     }
50617 #endif
50618 
50619     /* The maximum embedded fraction must be exactly 25%.  And the minimum
50620     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
50621     ** The original design allowed these amounts to vary, but as of
50622     ** version 3.6.0, we require them to be fixed.
50623     */
50624     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
50625       goto page1_init_failed;
50626     }
50627     pageSize = (page1[16]<<8) | (page1[17]<<16);
50628     if( ((pageSize-1)&pageSize)!=0
50629      || pageSize>SQLITE_MAX_PAGE_SIZE
50630      || pageSize<=256
50631     ){
50632       goto page1_init_failed;
50633     }
50634     assert( (pageSize & 7)==0 );
50635     usableSize = pageSize - page1[20];
50636     if( (u32)pageSize!=pBt->pageSize ){
50637       /* After reading the first page of the database assuming a page size
50638       ** of BtShared.pageSize, we have discovered that the page-size is
50639       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
50640       ** zero and return SQLITE_OK. The caller will call this function
50641       ** again with the correct page-size.
50642       */
50643       releasePage(pPage1);
50644       pBt->usableSize = usableSize;
50645       pBt->pageSize = pageSize;
50646       freeTempSpace(pBt);
50647       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
50648                                    pageSize-usableSize);
50649       return rc;
50650     }
50651     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
50652       rc = SQLITE_CORRUPT_BKPT;
50653       goto page1_init_failed;
50654     }
50655     if( usableSize<480 ){
50656       goto page1_init_failed;
50657     }
50658     pBt->pageSize = pageSize;
50659     pBt->usableSize = usableSize;
50660 #ifndef SQLITE_OMIT_AUTOVACUUM
50661     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
50662     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
50663 #endif
50664   }
50665 
50666   /* maxLocal is the maximum amount of payload to store locally for
50667   ** a cell.  Make sure it is small enough so that at least minFanout
50668   ** cells can will fit on one page.  We assume a 10-byte page header.
50669   ** Besides the payload, the cell must store:
50670   **     2-byte pointer to the cell
50671   **     4-byte child pointer
50672   **     9-byte nKey value
50673   **     4-byte nData value
50674   **     4-byte overflow page pointer
50675   ** So a cell consists of a 2-byte pointer, a header which is as much as
50676   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
50677   ** page pointer.
50678   */
50679   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
50680   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
50681   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
50682   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
50683   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
50684   pBt->pPage1 = pPage1;
50685   pBt->nPage = nPage;
50686   return SQLITE_OK;
50687 
50688 page1_init_failed:
50689   releasePage(pPage1);
50690   pBt->pPage1 = 0;
50691   return rc;
50692 }
50693 
50694 /*
50695 ** If there are no outstanding cursors and we are not in the middle
50696 ** of a transaction but there is a read lock on the database, then
50697 ** this routine unrefs the first page of the database file which
50698 ** has the effect of releasing the read lock.
50699 **
50700 ** If there is a transaction in progress, this routine is a no-op.
50701 */
50702 static void unlockBtreeIfUnused(BtShared *pBt){
50703   assert( sqlite3_mutex_held(pBt->mutex) );
50704   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
50705   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
50706     assert( pBt->pPage1->aData );
50707     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
50708     assert( pBt->pPage1->aData );
50709     releasePage(pBt->pPage1);
50710     pBt->pPage1 = 0;
50711   }
50712 }
50713 
50714 /*
50715 ** If pBt points to an empty file then convert that empty file
50716 ** into a new empty database by initializing the first page of
50717 ** the database.
50718 */
50719 static int newDatabase(BtShared *pBt){
50720   MemPage *pP1;
50721   unsigned char *data;
50722   int rc;
50723 
50724   assert( sqlite3_mutex_held(pBt->mutex) );
50725   if( pBt->nPage>0 ){
50726     return SQLITE_OK;
50727   }
50728   pP1 = pBt->pPage1;
50729   assert( pP1!=0 );
50730   data = pP1->aData;
50731   rc = sqlite3PagerWrite(pP1->pDbPage);
50732   if( rc ) return rc;
50733   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
50734   assert( sizeof(zMagicHeader)==16 );
50735   data[16] = (u8)((pBt->pageSize>>8)&0xff);
50736   data[17] = (u8)((pBt->pageSize>>16)&0xff);
50737   data[18] = 1;
50738   data[19] = 1;
50739   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
50740   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
50741   data[21] = 64;
50742   data[22] = 32;
50743   data[23] = 32;
50744   memset(&data[24], 0, 100-24);
50745   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
50746   pBt->pageSizeFixed = 1;
50747 #ifndef SQLITE_OMIT_AUTOVACUUM
50748   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
50749   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
50750   put4byte(&data[36 + 4*4], pBt->autoVacuum);
50751   put4byte(&data[36 + 7*4], pBt->incrVacuum);
50752 #endif
50753   pBt->nPage = 1;
50754   data[31] = 1;
50755   return SQLITE_OK;
50756 }
50757 
50758 /*
50759 ** Attempt to start a new transaction. A write-transaction
50760 ** is started if the second argument is nonzero, otherwise a read-
50761 ** transaction.  If the second argument is 2 or more and exclusive
50762 ** transaction is started, meaning that no other process is allowed
50763 ** to access the database.  A preexisting transaction may not be
50764 ** upgraded to exclusive by calling this routine a second time - the
50765 ** exclusivity flag only works for a new transaction.
50766 **
50767 ** A write-transaction must be started before attempting any
50768 ** changes to the database.  None of the following routines
50769 ** will work unless a transaction is started first:
50770 **
50771 **      sqlite3BtreeCreateTable()
50772 **      sqlite3BtreeCreateIndex()
50773 **      sqlite3BtreeClearTable()
50774 **      sqlite3BtreeDropTable()
50775 **      sqlite3BtreeInsert()
50776 **      sqlite3BtreeDelete()
50777 **      sqlite3BtreeUpdateMeta()
50778 **
50779 ** If an initial attempt to acquire the lock fails because of lock contention
50780 ** and the database was previously unlocked, then invoke the busy handler
50781 ** if there is one.  But if there was previously a read-lock, do not
50782 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
50783 ** returned when there is already a read-lock in order to avoid a deadlock.
50784 **
50785 ** Suppose there are two processes A and B.  A has a read lock and B has
50786 ** a reserved lock.  B tries to promote to exclusive but is blocked because
50787 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
50788 ** One or the other of the two processes must give way or there can be
50789 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
50790 ** when A already has a read lock, we encourage A to give up and let B
50791 ** proceed.
50792 */
50793 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
50794   sqlite3 *pBlock = 0;
50795   BtShared *pBt = p->pBt;
50796   int rc = SQLITE_OK;
50797 
50798   sqlite3BtreeEnter(p);
50799   btreeIntegrity(p);
50800 
50801   /* If the btree is already in a write-transaction, or it
50802   ** is already in a read-transaction and a read-transaction
50803   ** is requested, this is a no-op.
50804   */
50805   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
50806     goto trans_begun;
50807   }
50808 
50809   /* Write transactions are not possible on a read-only database */
50810   if( pBt->readOnly && wrflag ){
50811     rc = SQLITE_READONLY;
50812     goto trans_begun;
50813   }
50814 
50815 #ifndef SQLITE_OMIT_SHARED_CACHE
50816   /* If another database handle has already opened a write transaction
50817   ** on this shared-btree structure and a second write transaction is
50818   ** requested, return SQLITE_LOCKED.
50819   */
50820   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
50821     pBlock = pBt->pWriter->db;
50822   }else if( wrflag>1 ){
50823     BtLock *pIter;
50824     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
50825       if( pIter->pBtree!=p ){
50826         pBlock = pIter->pBtree->db;
50827         break;
50828       }
50829     }
50830   }
50831   if( pBlock ){
50832     sqlite3ConnectionBlocked(p->db, pBlock);
50833     rc = SQLITE_LOCKED_SHAREDCACHE;
50834     goto trans_begun;
50835   }
50836 #endif
50837 
50838   /* Any read-only or read-write transaction implies a read-lock on
50839   ** page 1. So if some other shared-cache client already has a write-lock
50840   ** on page 1, the transaction cannot be opened. */
50841   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
50842   if( SQLITE_OK!=rc ) goto trans_begun;
50843 
50844   pBt->initiallyEmpty = (u8)(pBt->nPage==0);
50845   do {
50846     /* Call lockBtree() until either pBt->pPage1 is populated or
50847     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
50848     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
50849     ** reading page 1 it discovers that the page-size of the database
50850     ** file is not pBt->pageSize. In this case lockBtree() will update
50851     ** pBt->pageSize to the page-size of the file on disk.
50852     */
50853     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
50854 
50855     if( rc==SQLITE_OK && wrflag ){
50856       if( pBt->readOnly ){
50857         rc = SQLITE_READONLY;
50858       }else{
50859         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
50860         if( rc==SQLITE_OK ){
50861           rc = newDatabase(pBt);
50862         }
50863       }
50864     }
50865 
50866     if( rc!=SQLITE_OK ){
50867       unlockBtreeIfUnused(pBt);
50868     }
50869   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
50870           btreeInvokeBusyHandler(pBt) );
50871 
50872   if( rc==SQLITE_OK ){
50873     if( p->inTrans==TRANS_NONE ){
50874       pBt->nTransaction++;
50875 #ifndef SQLITE_OMIT_SHARED_CACHE
50876       if( p->sharable ){
50877 	assert( p->lock.pBtree==p && p->lock.iTable==1 );
50878         p->lock.eLock = READ_LOCK;
50879         p->lock.pNext = pBt->pLock;
50880         pBt->pLock = &p->lock;
50881       }
50882 #endif
50883     }
50884     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
50885     if( p->inTrans>pBt->inTransaction ){
50886       pBt->inTransaction = p->inTrans;
50887     }
50888     if( wrflag ){
50889       MemPage *pPage1 = pBt->pPage1;
50890 #ifndef SQLITE_OMIT_SHARED_CACHE
50891       assert( !pBt->pWriter );
50892       pBt->pWriter = p;
50893       pBt->isExclusive = (u8)(wrflag>1);
50894 #endif
50895 
50896       /* If the db-size header field is incorrect (as it may be if an old
50897       ** client has been writing the database file), update it now. Doing
50898       ** this sooner rather than later means the database size can safely
50899       ** re-read the database size from page 1 if a savepoint or transaction
50900       ** rollback occurs within the transaction.
50901       */
50902       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
50903         rc = sqlite3PagerWrite(pPage1->pDbPage);
50904         if( rc==SQLITE_OK ){
50905           put4byte(&pPage1->aData[28], pBt->nPage);
50906         }
50907       }
50908     }
50909   }
50910 
50911 
50912 trans_begun:
50913   if( rc==SQLITE_OK && wrflag ){
50914     /* This call makes sure that the pager has the correct number of
50915     ** open savepoints. If the second parameter is greater than 0 and
50916     ** the sub-journal is not already open, then it will be opened here.
50917     */
50918     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
50919   }
50920 
50921   btreeIntegrity(p);
50922   sqlite3BtreeLeave(p);
50923   return rc;
50924 }
50925 
50926 #ifndef SQLITE_OMIT_AUTOVACUUM
50927 
50928 /*
50929 ** Set the pointer-map entries for all children of page pPage. Also, if
50930 ** pPage contains cells that point to overflow pages, set the pointer
50931 ** map entries for the overflow pages as well.
50932 */
50933 static int setChildPtrmaps(MemPage *pPage){
50934   int i;                             /* Counter variable */
50935   int nCell;                         /* Number of cells in page pPage */
50936   int rc;                            /* Return code */
50937   BtShared *pBt = pPage->pBt;
50938   u8 isInitOrig = pPage->isInit;
50939   Pgno pgno = pPage->pgno;
50940 
50941   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50942   rc = btreeInitPage(pPage);
50943   if( rc!=SQLITE_OK ){
50944     goto set_child_ptrmaps_out;
50945   }
50946   nCell = pPage->nCell;
50947 
50948   for(i=0; i<nCell; i++){
50949     u8 *pCell = findCell(pPage, i);
50950 
50951     ptrmapPutOvflPtr(pPage, pCell, &rc);
50952 
50953     if( !pPage->leaf ){
50954       Pgno childPgno = get4byte(pCell);
50955       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50956     }
50957   }
50958 
50959   if( !pPage->leaf ){
50960     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
50961     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
50962   }
50963 
50964 set_child_ptrmaps_out:
50965   pPage->isInit = isInitOrig;
50966   return rc;
50967 }
50968 
50969 /*
50970 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
50971 ** that it points to iTo. Parameter eType describes the type of pointer to
50972 ** be modified, as  follows:
50973 **
50974 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
50975 **                   page of pPage.
50976 **
50977 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
50978 **                   page pointed to by one of the cells on pPage.
50979 **
50980 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
50981 **                   overflow page in the list.
50982 */
50983 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
50984   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50985   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50986   if( eType==PTRMAP_OVERFLOW2 ){
50987     /* The pointer is always the first 4 bytes of the page in this case.  */
50988     if( get4byte(pPage->aData)!=iFrom ){
50989       return SQLITE_CORRUPT_BKPT;
50990     }
50991     put4byte(pPage->aData, iTo);
50992   }else{
50993     u8 isInitOrig = pPage->isInit;
50994     int i;
50995     int nCell;
50996 
50997     btreeInitPage(pPage);
50998     nCell = pPage->nCell;
50999 
51000     for(i=0; i<nCell; i++){
51001       u8 *pCell = findCell(pPage, i);
51002       if( eType==PTRMAP_OVERFLOW1 ){
51003         CellInfo info;
51004         btreeParseCellPtr(pPage, pCell, &info);
51005         if( info.iOverflow
51006          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
51007          && iFrom==get4byte(&pCell[info.iOverflow])
51008         ){
51009           put4byte(&pCell[info.iOverflow], iTo);
51010           break;
51011         }
51012       }else{
51013         if( get4byte(pCell)==iFrom ){
51014           put4byte(pCell, iTo);
51015           break;
51016         }
51017       }
51018     }
51019 
51020     if( i==nCell ){
51021       if( eType!=PTRMAP_BTREE ||
51022           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
51023         return SQLITE_CORRUPT_BKPT;
51024       }
51025       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
51026     }
51027 
51028     pPage->isInit = isInitOrig;
51029   }
51030   return SQLITE_OK;
51031 }
51032 
51033 
51034 /*
51035 ** Move the open database page pDbPage to location iFreePage in the
51036 ** database. The pDbPage reference remains valid.
51037 **
51038 ** The isCommit flag indicates that there is no need to remember that
51039 ** the journal needs to be sync()ed before database page pDbPage->pgno
51040 ** can be written to. The caller has already promised not to write to that
51041 ** page.
51042 */
51043 static int relocatePage(
51044   BtShared *pBt,           /* Btree */
51045   MemPage *pDbPage,        /* Open page to move */
51046   u8 eType,                /* Pointer map 'type' entry for pDbPage */
51047   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
51048   Pgno iFreePage,          /* The location to move pDbPage to */
51049   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
51050 ){
51051   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
51052   Pgno iDbPage = pDbPage->pgno;
51053   Pager *pPager = pBt->pPager;
51054   int rc;
51055 
51056   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
51057       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
51058   assert( sqlite3_mutex_held(pBt->mutex) );
51059   assert( pDbPage->pBt==pBt );
51060 
51061   /* Move page iDbPage from its current location to page number iFreePage */
51062   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
51063       iDbPage, iFreePage, iPtrPage, eType));
51064   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
51065   if( rc!=SQLITE_OK ){
51066     return rc;
51067   }
51068   pDbPage->pgno = iFreePage;
51069 
51070   /* If pDbPage was a btree-page, then it may have child pages and/or cells
51071   ** that point to overflow pages. The pointer map entries for all these
51072   ** pages need to be changed.
51073   **
51074   ** If pDbPage is an overflow page, then the first 4 bytes may store a
51075   ** pointer to a subsequent overflow page. If this is the case, then
51076   ** the pointer map needs to be updated for the subsequent overflow page.
51077   */
51078   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
51079     rc = setChildPtrmaps(pDbPage);
51080     if( rc!=SQLITE_OK ){
51081       return rc;
51082     }
51083   }else{
51084     Pgno nextOvfl = get4byte(pDbPage->aData);
51085     if( nextOvfl!=0 ){
51086       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
51087       if( rc!=SQLITE_OK ){
51088         return rc;
51089       }
51090     }
51091   }
51092 
51093   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
51094   ** that it points at iFreePage. Also fix the pointer map entry for
51095   ** iPtrPage.
51096   */
51097   if( eType!=PTRMAP_ROOTPAGE ){
51098     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
51099     if( rc!=SQLITE_OK ){
51100       return rc;
51101     }
51102     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
51103     if( rc!=SQLITE_OK ){
51104       releasePage(pPtrPage);
51105       return rc;
51106     }
51107     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
51108     releasePage(pPtrPage);
51109     if( rc==SQLITE_OK ){
51110       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
51111     }
51112   }
51113   return rc;
51114 }
51115 
51116 /* Forward declaration required by incrVacuumStep(). */
51117 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
51118 
51119 /*
51120 ** Perform a single step of an incremental-vacuum. If successful,
51121 ** return SQLITE_OK. If there is no work to do (and therefore no
51122 ** point in calling this function again), return SQLITE_DONE.
51123 **
51124 ** More specificly, this function attempts to re-organize the
51125 ** database so that the last page of the file currently in use
51126 ** is no longer in use.
51127 **
51128 ** If the nFin parameter is non-zero, this function assumes
51129 ** that the caller will keep calling incrVacuumStep() until
51130 ** it returns SQLITE_DONE or an error, and that nFin is the
51131 ** number of pages the database file will contain after this
51132 ** process is complete.  If nFin is zero, it is assumed that
51133 ** incrVacuumStep() will be called a finite amount of times
51134 ** which may or may not empty the freelist.  A full autovacuum
51135 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
51136 */
51137 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
51138   Pgno nFreeList;           /* Number of pages still on the free-list */
51139   int rc;
51140 
51141   assert( sqlite3_mutex_held(pBt->mutex) );
51142   assert( iLastPg>nFin );
51143 
51144   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
51145     u8 eType;
51146     Pgno iPtrPage;
51147 
51148     nFreeList = get4byte(&pBt->pPage1->aData[36]);
51149     if( nFreeList==0 ){
51150       return SQLITE_DONE;
51151     }
51152 
51153     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
51154     if( rc!=SQLITE_OK ){
51155       return rc;
51156     }
51157     if( eType==PTRMAP_ROOTPAGE ){
51158       return SQLITE_CORRUPT_BKPT;
51159     }
51160 
51161     if( eType==PTRMAP_FREEPAGE ){
51162       if( nFin==0 ){
51163         /* Remove the page from the files free-list. This is not required
51164         ** if nFin is non-zero. In that case, the free-list will be
51165         ** truncated to zero after this function returns, so it doesn't
51166         ** matter if it still contains some garbage entries.
51167         */
51168         Pgno iFreePg;
51169         MemPage *pFreePg;
51170         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
51171         if( rc!=SQLITE_OK ){
51172           return rc;
51173         }
51174         assert( iFreePg==iLastPg );
51175         releasePage(pFreePg);
51176       }
51177     } else {
51178       Pgno iFreePg;             /* Index of free page to move pLastPg to */
51179       MemPage *pLastPg;
51180 
51181       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
51182       if( rc!=SQLITE_OK ){
51183         return rc;
51184       }
51185 
51186       /* If nFin is zero, this loop runs exactly once and page pLastPg
51187       ** is swapped with the first free page pulled off the free list.
51188       **
51189       ** On the other hand, if nFin is greater than zero, then keep
51190       ** looping until a free-page located within the first nFin pages
51191       ** of the file is found.
51192       */
51193       do {
51194         MemPage *pFreePg;
51195         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
51196         if( rc!=SQLITE_OK ){
51197           releasePage(pLastPg);
51198           return rc;
51199         }
51200         releasePage(pFreePg);
51201       }while( nFin!=0 && iFreePg>nFin );
51202       assert( iFreePg<iLastPg );
51203 
51204       rc = sqlite3PagerWrite(pLastPg->pDbPage);
51205       if( rc==SQLITE_OK ){
51206         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
51207       }
51208       releasePage(pLastPg);
51209       if( rc!=SQLITE_OK ){
51210         return rc;
51211       }
51212     }
51213   }
51214 
51215   if( nFin==0 ){
51216     iLastPg--;
51217     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
51218       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
51219         MemPage *pPg;
51220         rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
51221         if( rc!=SQLITE_OK ){
51222           return rc;
51223         }
51224         rc = sqlite3PagerWrite(pPg->pDbPage);
51225         releasePage(pPg);
51226         if( rc!=SQLITE_OK ){
51227           return rc;
51228         }
51229       }
51230       iLastPg--;
51231     }
51232     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
51233     pBt->nPage = iLastPg;
51234   }
51235   return SQLITE_OK;
51236 }
51237 
51238 /*
51239 ** A write-transaction must be opened before calling this function.
51240 ** It performs a single unit of work towards an incremental vacuum.
51241 **
51242 ** If the incremental vacuum is finished after this function has run,
51243 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
51244 ** SQLITE_OK is returned. Otherwise an SQLite error code.
51245 */
51246 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
51247   int rc;
51248   BtShared *pBt = p->pBt;
51249 
51250   sqlite3BtreeEnter(p);
51251   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
51252   if( !pBt->autoVacuum ){
51253     rc = SQLITE_DONE;
51254   }else{
51255     invalidateAllOverflowCache(pBt);
51256     rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
51257     if( rc==SQLITE_OK ){
51258       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51259       put4byte(&pBt->pPage1->aData[28], pBt->nPage);
51260     }
51261   }
51262   sqlite3BtreeLeave(p);
51263   return rc;
51264 }
51265 
51266 /*
51267 ** This routine is called prior to sqlite3PagerCommit when a transaction
51268 ** is commited for an auto-vacuum database.
51269 **
51270 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
51271 ** the database file should be truncated to during the commit process.
51272 ** i.e. the database has been reorganized so that only the first *pnTrunc
51273 ** pages are in use.
51274 */
51275 static int autoVacuumCommit(BtShared *pBt){
51276   int rc = SQLITE_OK;
51277   Pager *pPager = pBt->pPager;
51278   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
51279 
51280   assert( sqlite3_mutex_held(pBt->mutex) );
51281   invalidateAllOverflowCache(pBt);
51282   assert(pBt->autoVacuum);
51283   if( !pBt->incrVacuum ){
51284     Pgno nFin;         /* Number of pages in database after autovacuuming */
51285     Pgno nFree;        /* Number of pages on the freelist initially */
51286     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
51287     Pgno iFree;        /* The next page to be freed */
51288     int nEntry;        /* Number of entries on one ptrmap page */
51289     Pgno nOrig;        /* Database size before freeing */
51290 
51291     nOrig = btreePagecount(pBt);
51292     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
51293       /* It is not possible to create a database for which the final page
51294       ** is either a pointer-map page or the pending-byte page. If one
51295       ** is encountered, this indicates corruption.
51296       */
51297       return SQLITE_CORRUPT_BKPT;
51298     }
51299 
51300     nFree = get4byte(&pBt->pPage1->aData[36]);
51301     nEntry = pBt->usableSize/5;
51302     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
51303     nFin = nOrig - nFree - nPtrmap;
51304     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
51305       nFin--;
51306     }
51307     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
51308       nFin--;
51309     }
51310     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
51311 
51312     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
51313       rc = incrVacuumStep(pBt, nFin, iFree);
51314     }
51315     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
51316       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
51317       put4byte(&pBt->pPage1->aData[32], 0);
51318       put4byte(&pBt->pPage1->aData[36], 0);
51319       put4byte(&pBt->pPage1->aData[28], nFin);
51320       sqlite3PagerTruncateImage(pBt->pPager, nFin);
51321       pBt->nPage = nFin;
51322     }
51323     if( rc!=SQLITE_OK ){
51324       sqlite3PagerRollback(pPager);
51325     }
51326   }
51327 
51328   assert( nRef==sqlite3PagerRefcount(pPager) );
51329   return rc;
51330 }
51331 
51332 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
51333 # define setChildPtrmaps(x) SQLITE_OK
51334 #endif
51335 
51336 /*
51337 ** This routine does the first phase of a two-phase commit.  This routine
51338 ** causes a rollback journal to be created (if it does not already exist)
51339 ** and populated with enough information so that if a power loss occurs
51340 ** the database can be restored to its original state by playing back
51341 ** the journal.  Then the contents of the journal are flushed out to
51342 ** the disk.  After the journal is safely on oxide, the changes to the
51343 ** database are written into the database file and flushed to oxide.
51344 ** At the end of this call, the rollback journal still exists on the
51345 ** disk and we are still holding all locks, so the transaction has not
51346 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
51347 ** commit process.
51348 **
51349 ** This call is a no-op if no write-transaction is currently active on pBt.
51350 **
51351 ** Otherwise, sync the database file for the btree pBt. zMaster points to
51352 ** the name of a master journal file that should be written into the
51353 ** individual journal file, or is NULL, indicating no master journal file
51354 ** (single database transaction).
51355 **
51356 ** When this is called, the master journal should already have been
51357 ** created, populated with this journal pointer and synced to disk.
51358 **
51359 ** Once this is routine has returned, the only thing required to commit
51360 ** the write-transaction for this database file is to delete the journal.
51361 */
51362 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
51363   int rc = SQLITE_OK;
51364   if( p->inTrans==TRANS_WRITE ){
51365     BtShared *pBt = p->pBt;
51366     sqlite3BtreeEnter(p);
51367 #ifndef SQLITE_OMIT_AUTOVACUUM
51368     if( pBt->autoVacuum ){
51369       rc = autoVacuumCommit(pBt);
51370       if( rc!=SQLITE_OK ){
51371         sqlite3BtreeLeave(p);
51372         return rc;
51373       }
51374     }
51375 #endif
51376     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
51377     sqlite3BtreeLeave(p);
51378   }
51379   return rc;
51380 }
51381 
51382 /*
51383 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
51384 ** at the conclusion of a transaction.
51385 */
51386 static void btreeEndTransaction(Btree *p){
51387   BtShared *pBt = p->pBt;
51388   assert( sqlite3BtreeHoldsMutex(p) );
51389 
51390   btreeClearHasContent(pBt);
51391   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
51392     /* If there are other active statements that belong to this database
51393     ** handle, downgrade to a read-only transaction. The other statements
51394     ** may still be reading from the database.  */
51395     downgradeAllSharedCacheTableLocks(p);
51396     p->inTrans = TRANS_READ;
51397   }else{
51398     /* If the handle had any kind of transaction open, decrement the
51399     ** transaction count of the shared btree. If the transaction count
51400     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
51401     ** call below will unlock the pager.  */
51402     if( p->inTrans!=TRANS_NONE ){
51403       clearAllSharedCacheTableLocks(p);
51404       pBt->nTransaction--;
51405       if( 0==pBt->nTransaction ){
51406         pBt->inTransaction = TRANS_NONE;
51407       }
51408     }
51409 
51410     /* Set the current transaction state to TRANS_NONE and unlock the
51411     ** pager if this call closed the only read or write transaction.  */
51412     p->inTrans = TRANS_NONE;
51413     unlockBtreeIfUnused(pBt);
51414   }
51415 
51416   btreeIntegrity(p);
51417 }
51418 
51419 /*
51420 ** Commit the transaction currently in progress.
51421 **
51422 ** This routine implements the second phase of a 2-phase commit.  The
51423 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
51424 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
51425 ** routine did all the work of writing information out to disk and flushing the
51426 ** contents so that they are written onto the disk platter.  All this
51427 ** routine has to do is delete or truncate or zero the header in the
51428 ** the rollback journal (which causes the transaction to commit) and
51429 ** drop locks.
51430 **
51431 ** Normally, if an error occurs while the pager layer is attempting to
51432 ** finalize the underlying journal file, this function returns an error and
51433 ** the upper layer will attempt a rollback. However, if the second argument
51434 ** is non-zero then this b-tree transaction is part of a multi-file
51435 ** transaction. In this case, the transaction has already been committed
51436 ** (by deleting a master journal file) and the caller will ignore this
51437 ** functions return code. So, even if an error occurs in the pager layer,
51438 ** reset the b-tree objects internal state to indicate that the write
51439 ** transaction has been closed. This is quite safe, as the pager will have
51440 ** transitioned to the error state.
51441 **
51442 ** This will release the write lock on the database file.  If there
51443 ** are no active cursors, it also releases the read lock.
51444 */
51445 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
51446 
51447   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
51448   sqlite3BtreeEnter(p);
51449   btreeIntegrity(p);
51450 
51451   /* If the handle has a write-transaction open, commit the shared-btrees
51452   ** transaction and set the shared state to TRANS_READ.
51453   */
51454   if( p->inTrans==TRANS_WRITE ){
51455     int rc;
51456     BtShared *pBt = p->pBt;
51457     assert( pBt->inTransaction==TRANS_WRITE );
51458     assert( pBt->nTransaction>0 );
51459     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
51460     if( rc!=SQLITE_OK && bCleanup==0 ){
51461       sqlite3BtreeLeave(p);
51462       return rc;
51463     }
51464     pBt->inTransaction = TRANS_READ;
51465   }
51466 
51467   btreeEndTransaction(p);
51468   sqlite3BtreeLeave(p);
51469   return SQLITE_OK;
51470 }
51471 
51472 /*
51473 ** Do both phases of a commit.
51474 */
51475 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
51476   int rc;
51477   sqlite3BtreeEnter(p);
51478   rc = sqlite3BtreeCommitPhaseOne(p, 0);
51479   if( rc==SQLITE_OK ){
51480     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
51481   }
51482   sqlite3BtreeLeave(p);
51483   return rc;
51484 }
51485 
51486 #ifndef NDEBUG
51487 /*
51488 ** Return the number of write-cursors open on this handle. This is for use
51489 ** in assert() expressions, so it is only compiled if NDEBUG is not
51490 ** defined.
51491 **
51492 ** For the purposes of this routine, a write-cursor is any cursor that
51493 ** is capable of writing to the databse.  That means the cursor was
51494 ** originally opened for writing and the cursor has not be disabled
51495 ** by having its state changed to CURSOR_FAULT.
51496 */
51497 static int countWriteCursors(BtShared *pBt){
51498   BtCursor *pCur;
51499   int r = 0;
51500   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
51501     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
51502   }
51503   return r;
51504 }
51505 #endif
51506 
51507 /*
51508 ** This routine sets the state to CURSOR_FAULT and the error
51509 ** code to errCode for every cursor on BtShared that pBtree
51510 ** references.
51511 **
51512 ** Every cursor is tripped, including cursors that belong
51513 ** to other database connections that happen to be sharing
51514 ** the cache with pBtree.
51515 **
51516 ** This routine gets called when a rollback occurs.
51517 ** All cursors using the same cache must be tripped
51518 ** to prevent them from trying to use the btree after
51519 ** the rollback.  The rollback may have deleted tables
51520 ** or moved root pages, so it is not sufficient to
51521 ** save the state of the cursor.  The cursor must be
51522 ** invalidated.
51523 */
51524 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
51525   BtCursor *p;
51526   sqlite3BtreeEnter(pBtree);
51527   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
51528     int i;
51529     sqlite3BtreeClearCursor(p);
51530     p->eState = CURSOR_FAULT;
51531     p->skipNext = errCode;
51532     for(i=0; i<=p->iPage; i++){
51533       releasePage(p->apPage[i]);
51534       p->apPage[i] = 0;
51535     }
51536   }
51537   sqlite3BtreeLeave(pBtree);
51538 }
51539 
51540 /*
51541 ** Rollback the transaction in progress.  All cursors will be
51542 ** invalided by this operation.  Any attempt to use a cursor
51543 ** that was open at the beginning of this operation will result
51544 ** in an error.
51545 **
51546 ** This will release the write lock on the database file.  If there
51547 ** are no active cursors, it also releases the read lock.
51548 */
51549 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
51550   int rc;
51551   BtShared *pBt = p->pBt;
51552   MemPage *pPage1;
51553 
51554   sqlite3BtreeEnter(p);
51555   rc = saveAllCursors(pBt, 0, 0);
51556 #ifndef SQLITE_OMIT_SHARED_CACHE
51557   if( rc!=SQLITE_OK ){
51558     /* This is a horrible situation. An IO or malloc() error occurred whilst
51559     ** trying to save cursor positions. If this is an automatic rollback (as
51560     ** the result of a constraint, malloc() failure or IO error) then
51561     ** the cache may be internally inconsistent (not contain valid trees) so
51562     ** we cannot simply return the error to the caller. Instead, abort
51563     ** all queries that may be using any of the cursors that failed to save.
51564     */
51565     sqlite3BtreeTripAllCursors(p, rc);
51566   }
51567 #endif
51568   btreeIntegrity(p);
51569 
51570   if( p->inTrans==TRANS_WRITE ){
51571     int rc2;
51572 
51573     assert( TRANS_WRITE==pBt->inTransaction );
51574     rc2 = sqlite3PagerRollback(pBt->pPager);
51575     if( rc2!=SQLITE_OK ){
51576       rc = rc2;
51577     }
51578 
51579     /* The rollback may have destroyed the pPage1->aData value.  So
51580     ** call btreeGetPage() on page 1 again to make
51581     ** sure pPage1->aData is set correctly. */
51582     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
51583       int nPage = get4byte(28+(u8*)pPage1->aData);
51584       testcase( nPage==0 );
51585       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
51586       testcase( pBt->nPage!=nPage );
51587       pBt->nPage = nPage;
51588       releasePage(pPage1);
51589     }
51590     assert( countWriteCursors(pBt)==0 );
51591     pBt->inTransaction = TRANS_READ;
51592   }
51593 
51594   btreeEndTransaction(p);
51595   sqlite3BtreeLeave(p);
51596   return rc;
51597 }
51598 
51599 /*
51600 ** Start a statement subtransaction. The subtransaction can can be rolled
51601 ** back independently of the main transaction. You must start a transaction
51602 ** before starting a subtransaction. The subtransaction is ended automatically
51603 ** if the main transaction commits or rolls back.
51604 **
51605 ** Statement subtransactions are used around individual SQL statements
51606 ** that are contained within a BEGIN...COMMIT block.  If a constraint
51607 ** error occurs within the statement, the effect of that one statement
51608 ** can be rolled back without having to rollback the entire transaction.
51609 **
51610 ** A statement sub-transaction is implemented as an anonymous savepoint. The
51611 ** value passed as the second parameter is the total number of savepoints,
51612 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
51613 ** are no active savepoints and no other statement-transactions open,
51614 ** iStatement is 1. This anonymous savepoint can be released or rolled back
51615 ** using the sqlite3BtreeSavepoint() function.
51616 */
51617 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
51618   int rc;
51619   BtShared *pBt = p->pBt;
51620   sqlite3BtreeEnter(p);
51621   assert( p->inTrans==TRANS_WRITE );
51622   assert( pBt->readOnly==0 );
51623   assert( iStatement>0 );
51624   assert( iStatement>p->db->nSavepoint );
51625   assert( pBt->inTransaction==TRANS_WRITE );
51626   /* At the pager level, a statement transaction is a savepoint with
51627   ** an index greater than all savepoints created explicitly using
51628   ** SQL statements. It is illegal to open, release or rollback any
51629   ** such savepoints while the statement transaction savepoint is active.
51630   */
51631   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
51632   sqlite3BtreeLeave(p);
51633   return rc;
51634 }
51635 
51636 /*
51637 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
51638 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
51639 ** savepoint identified by parameter iSavepoint, depending on the value
51640 ** of op.
51641 **
51642 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
51643 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
51644 ** contents of the entire transaction are rolled back. This is different
51645 ** from a normal transaction rollback, as no locks are released and the
51646 ** transaction remains open.
51647 */
51648 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
51649   int rc = SQLITE_OK;
51650   if( p && p->inTrans==TRANS_WRITE ){
51651     BtShared *pBt = p->pBt;
51652     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
51653     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
51654     sqlite3BtreeEnter(p);
51655     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
51656     if( rc==SQLITE_OK ){
51657       if( iSavepoint<0 && pBt->initiallyEmpty ) pBt->nPage = 0;
51658       rc = newDatabase(pBt);
51659       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
51660 
51661       /* The database size was written into the offset 28 of the header
51662       ** when the transaction started, so we know that the value at offset
51663       ** 28 is nonzero. */
51664       assert( pBt->nPage>0 );
51665     }
51666     sqlite3BtreeLeave(p);
51667   }
51668   return rc;
51669 }
51670 
51671 /*
51672 ** Create a new cursor for the BTree whose root is on the page
51673 ** iTable. If a read-only cursor is requested, it is assumed that
51674 ** the caller already has at least a read-only transaction open
51675 ** on the database already. If a write-cursor is requested, then
51676 ** the caller is assumed to have an open write transaction.
51677 **
51678 ** If wrFlag==0, then the cursor can only be used for reading.
51679 ** If wrFlag==1, then the cursor can be used for reading or for
51680 ** writing if other conditions for writing are also met.  These
51681 ** are the conditions that must be met in order for writing to
51682 ** be allowed:
51683 **
51684 ** 1:  The cursor must have been opened with wrFlag==1
51685 **
51686 ** 2:  Other database connections that share the same pager cache
51687 **     but which are not in the READ_UNCOMMITTED state may not have
51688 **     cursors open with wrFlag==0 on the same table.  Otherwise
51689 **     the changes made by this write cursor would be visible to
51690 **     the read cursors in the other database connection.
51691 **
51692 ** 3:  The database must be writable (not on read-only media)
51693 **
51694 ** 4:  There must be an active transaction.
51695 **
51696 ** No checking is done to make sure that page iTable really is the
51697 ** root page of a b-tree.  If it is not, then the cursor acquired
51698 ** will not work correctly.
51699 **
51700 ** It is assumed that the sqlite3BtreeCursorZero() has been called
51701 ** on pCur to initialize the memory space prior to invoking this routine.
51702 */
51703 static int btreeCursor(
51704   Btree *p,                              /* The btree */
51705   int iTable,                            /* Root page of table to open */
51706   int wrFlag,                            /* 1 to write. 0 read-only */
51707   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
51708   BtCursor *pCur                         /* Space for new cursor */
51709 ){
51710   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
51711 
51712   assert( sqlite3BtreeHoldsMutex(p) );
51713   assert( wrFlag==0 || wrFlag==1 );
51714 
51715   /* The following assert statements verify that if this is a sharable
51716   ** b-tree database, the connection is holding the required table locks,
51717   ** and that no other connection has any open cursor that conflicts with
51718   ** this lock.  */
51719   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
51720   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
51721 
51722   /* Assert that the caller has opened the required transaction. */
51723   assert( p->inTrans>TRANS_NONE );
51724   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
51725   assert( pBt->pPage1 && pBt->pPage1->aData );
51726 
51727   if( NEVER(wrFlag && pBt->readOnly) ){
51728     return SQLITE_READONLY;
51729   }
51730   if( iTable==1 && btreePagecount(pBt)==0 ){
51731     assert( wrFlag==0 );
51732     iTable = 0;
51733   }
51734 
51735   /* Now that no other errors can occur, finish filling in the BtCursor
51736   ** variables and link the cursor into the BtShared list.  */
51737   pCur->pgnoRoot = (Pgno)iTable;
51738   pCur->iPage = -1;
51739   pCur->pKeyInfo = pKeyInfo;
51740   pCur->pBtree = p;
51741   pCur->pBt = pBt;
51742   pCur->wrFlag = (u8)wrFlag;
51743   pCur->pNext = pBt->pCursor;
51744   if( pCur->pNext ){
51745     pCur->pNext->pPrev = pCur;
51746   }
51747   pBt->pCursor = pCur;
51748   pCur->eState = CURSOR_INVALID;
51749   pCur->cachedRowid = 0;
51750   return SQLITE_OK;
51751 }
51752 SQLITE_PRIVATE int sqlite3BtreeCursor(
51753   Btree *p,                                   /* The btree */
51754   int iTable,                                 /* Root page of table to open */
51755   int wrFlag,                                 /* 1 to write. 0 read-only */
51756   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
51757   BtCursor *pCur                              /* Write new cursor here */
51758 ){
51759   int rc;
51760   sqlite3BtreeEnter(p);
51761   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
51762   sqlite3BtreeLeave(p);
51763   return rc;
51764 }
51765 
51766 /*
51767 ** Return the size of a BtCursor object in bytes.
51768 **
51769 ** This interfaces is needed so that users of cursors can preallocate
51770 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
51771 ** to users so they cannot do the sizeof() themselves - they must call
51772 ** this routine.
51773 */
51774 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
51775   return ROUND8(sizeof(BtCursor));
51776 }
51777 
51778 /*
51779 ** Initialize memory that will be converted into a BtCursor object.
51780 **
51781 ** The simple approach here would be to memset() the entire object
51782 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
51783 ** do not need to be zeroed and they are large, so we can save a lot
51784 ** of run-time by skipping the initialization of those elements.
51785 */
51786 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
51787   memset(p, 0, offsetof(BtCursor, iPage));
51788 }
51789 
51790 /*
51791 ** Set the cached rowid value of every cursor in the same database file
51792 ** as pCur and having the same root page number as pCur.  The value is
51793 ** set to iRowid.
51794 **
51795 ** Only positive rowid values are considered valid for this cache.
51796 ** The cache is initialized to zero, indicating an invalid cache.
51797 ** A btree will work fine with zero or negative rowids.  We just cannot
51798 ** cache zero or negative rowids, which means tables that use zero or
51799 ** negative rowids might run a little slower.  But in practice, zero
51800 ** or negative rowids are very uncommon so this should not be a problem.
51801 */
51802 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
51803   BtCursor *p;
51804   for(p=pCur->pBt->pCursor; p; p=p->pNext){
51805     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
51806   }
51807   assert( pCur->cachedRowid==iRowid );
51808 }
51809 
51810 /*
51811 ** Return the cached rowid for the given cursor.  A negative or zero
51812 ** return value indicates that the rowid cache is invalid and should be
51813 ** ignored.  If the rowid cache has never before been set, then a
51814 ** zero is returned.
51815 */
51816 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
51817   return pCur->cachedRowid;
51818 }
51819 
51820 /*
51821 ** Close a cursor.  The read lock on the database file is released
51822 ** when the last cursor is closed.
51823 */
51824 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
51825   Btree *pBtree = pCur->pBtree;
51826   if( pBtree ){
51827     int i;
51828     BtShared *pBt = pCur->pBt;
51829     sqlite3BtreeEnter(pBtree);
51830     sqlite3BtreeClearCursor(pCur);
51831     if( pCur->pPrev ){
51832       pCur->pPrev->pNext = pCur->pNext;
51833     }else{
51834       pBt->pCursor = pCur->pNext;
51835     }
51836     if( pCur->pNext ){
51837       pCur->pNext->pPrev = pCur->pPrev;
51838     }
51839     for(i=0; i<=pCur->iPage; i++){
51840       releasePage(pCur->apPage[i]);
51841     }
51842     unlockBtreeIfUnused(pBt);
51843     invalidateOverflowCache(pCur);
51844     /* sqlite3_free(pCur); */
51845     sqlite3BtreeLeave(pBtree);
51846   }
51847   return SQLITE_OK;
51848 }
51849 
51850 /*
51851 ** Make sure the BtCursor* given in the argument has a valid
51852 ** BtCursor.info structure.  If it is not already valid, call
51853 ** btreeParseCell() to fill it in.
51854 **
51855 ** BtCursor.info is a cache of the information in the current cell.
51856 ** Using this cache reduces the number of calls to btreeParseCell().
51857 **
51858 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
51859 ** compiler to crash when getCellInfo() is implemented as a macro.
51860 ** But there is a measureable speed advantage to using the macro on gcc
51861 ** (when less compiler optimizations like -Os or -O0 are used and the
51862 ** compiler is not doing agressive inlining.)  So we use a real function
51863 ** for MSVC and a macro for everything else.  Ticket #2457.
51864 */
51865 #ifndef NDEBUG
51866   static void assertCellInfo(BtCursor *pCur){
51867     CellInfo info;
51868     int iPage = pCur->iPage;
51869     memset(&info, 0, sizeof(info));
51870     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
51871     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
51872   }
51873 #else
51874   #define assertCellInfo(x)
51875 #endif
51876 #ifdef _MSC_VER
51877   /* Use a real function in MSVC to work around bugs in that compiler. */
51878   static void getCellInfo(BtCursor *pCur){
51879     if( pCur->info.nSize==0 ){
51880       int iPage = pCur->iPage;
51881       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
51882       pCur->validNKey = 1;
51883     }else{
51884       assertCellInfo(pCur);
51885     }
51886   }
51887 #else /* if not _MSC_VER */
51888   /* Use a macro in all other compilers so that the function is inlined */
51889 #define getCellInfo(pCur)                                                      \
51890   if( pCur->info.nSize==0 ){                                                   \
51891     int iPage = pCur->iPage;                                                   \
51892     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
51893     pCur->validNKey = 1;                                                       \
51894   }else{                                                                       \
51895     assertCellInfo(pCur);                                                      \
51896   }
51897 #endif /* _MSC_VER */
51898 
51899 #ifndef NDEBUG  /* The next routine used only within assert() statements */
51900 /*
51901 ** Return true if the given BtCursor is valid.  A valid cursor is one
51902 ** that is currently pointing to a row in a (non-empty) table.
51903 ** This is a verification routine is used only within assert() statements.
51904 */
51905 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
51906   return pCur && pCur->eState==CURSOR_VALID;
51907 }
51908 #endif /* NDEBUG */
51909 
51910 /*
51911 ** Set *pSize to the size of the buffer needed to hold the value of
51912 ** the key for the current entry.  If the cursor is not pointing
51913 ** to a valid entry, *pSize is set to 0.
51914 **
51915 ** For a table with the INTKEY flag set, this routine returns the key
51916 ** itself, not the number of bytes in the key.
51917 **
51918 ** The caller must position the cursor prior to invoking this routine.
51919 **
51920 ** This routine cannot fail.  It always returns SQLITE_OK.
51921 */
51922 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
51923   assert( cursorHoldsMutex(pCur) );
51924   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
51925   if( pCur->eState!=CURSOR_VALID ){
51926     *pSize = 0;
51927   }else{
51928     getCellInfo(pCur);
51929     *pSize = pCur->info.nKey;
51930   }
51931   return SQLITE_OK;
51932 }
51933 
51934 /*
51935 ** Set *pSize to the number of bytes of data in the entry the
51936 ** cursor currently points to.
51937 **
51938 ** The caller must guarantee that the cursor is pointing to a non-NULL
51939 ** valid entry.  In other words, the calling procedure must guarantee
51940 ** that the cursor has Cursor.eState==CURSOR_VALID.
51941 **
51942 ** Failure is not possible.  This function always returns SQLITE_OK.
51943 ** It might just as well be a procedure (returning void) but we continue
51944 ** to return an integer result code for historical reasons.
51945 */
51946 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
51947   assert( cursorHoldsMutex(pCur) );
51948   assert( pCur->eState==CURSOR_VALID );
51949   getCellInfo(pCur);
51950   *pSize = pCur->info.nData;
51951   return SQLITE_OK;
51952 }
51953 
51954 /*
51955 ** Given the page number of an overflow page in the database (parameter
51956 ** ovfl), this function finds the page number of the next page in the
51957 ** linked list of overflow pages. If possible, it uses the auto-vacuum
51958 ** pointer-map data instead of reading the content of page ovfl to do so.
51959 **
51960 ** If an error occurs an SQLite error code is returned. Otherwise:
51961 **
51962 ** The page number of the next overflow page in the linked list is
51963 ** written to *pPgnoNext. If page ovfl is the last page in its linked
51964 ** list, *pPgnoNext is set to zero.
51965 **
51966 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
51967 ** to page number pOvfl was obtained, then *ppPage is set to point to that
51968 ** reference. It is the responsibility of the caller to call releasePage()
51969 ** on *ppPage to free the reference. In no reference was obtained (because
51970 ** the pointer-map was used to obtain the value for *pPgnoNext), then
51971 ** *ppPage is set to zero.
51972 */
51973 static int getOverflowPage(
51974   BtShared *pBt,               /* The database file */
51975   Pgno ovfl,                   /* Current overflow page number */
51976   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
51977   Pgno *pPgnoNext              /* OUT: Next overflow page number */
51978 ){
51979   Pgno next = 0;
51980   MemPage *pPage = 0;
51981   int rc = SQLITE_OK;
51982 
51983   assert( sqlite3_mutex_held(pBt->mutex) );
51984   assert(pPgnoNext);
51985 
51986 #ifndef SQLITE_OMIT_AUTOVACUUM
51987   /* Try to find the next page in the overflow list using the
51988   ** autovacuum pointer-map pages. Guess that the next page in
51989   ** the overflow list is page number (ovfl+1). If that guess turns
51990   ** out to be wrong, fall back to loading the data of page
51991   ** number ovfl to determine the next page number.
51992   */
51993   if( pBt->autoVacuum ){
51994     Pgno pgno;
51995     Pgno iGuess = ovfl+1;
51996     u8 eType;
51997 
51998     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
51999       iGuess++;
52000     }
52001 
52002     if( iGuess<=btreePagecount(pBt) ){
52003       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
52004       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
52005         next = iGuess;
52006         rc = SQLITE_DONE;
52007       }
52008     }
52009   }
52010 #endif
52011 
52012   assert( next==0 || rc==SQLITE_DONE );
52013   if( rc==SQLITE_OK ){
52014     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
52015     assert( rc==SQLITE_OK || pPage==0 );
52016     if( rc==SQLITE_OK ){
52017       next = get4byte(pPage->aData);
52018     }
52019   }
52020 
52021   *pPgnoNext = next;
52022   if( ppPage ){
52023     *ppPage = pPage;
52024   }else{
52025     releasePage(pPage);
52026   }
52027   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
52028 }
52029 
52030 /*
52031 ** Copy data from a buffer to a page, or from a page to a buffer.
52032 **
52033 ** pPayload is a pointer to data stored on database page pDbPage.
52034 ** If argument eOp is false, then nByte bytes of data are copied
52035 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
52036 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
52037 ** of data are copied from the buffer pBuf to pPayload.
52038 **
52039 ** SQLITE_OK is returned on success, otherwise an error code.
52040 */
52041 static int copyPayload(
52042   void *pPayload,           /* Pointer to page data */
52043   void *pBuf,               /* Pointer to buffer */
52044   int nByte,                /* Number of bytes to copy */
52045   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
52046   DbPage *pDbPage           /* Page containing pPayload */
52047 ){
52048   if( eOp ){
52049     /* Copy data from buffer to page (a write operation) */
52050     int rc = sqlite3PagerWrite(pDbPage);
52051     if( rc!=SQLITE_OK ){
52052       return rc;
52053     }
52054     memcpy(pPayload, pBuf, nByte);
52055   }else{
52056     /* Copy data from page to buffer (a read operation) */
52057     memcpy(pBuf, pPayload, nByte);
52058   }
52059   return SQLITE_OK;
52060 }
52061 
52062 /*
52063 ** This function is used to read or overwrite payload information
52064 ** for the entry that the pCur cursor is pointing to. If the eOp
52065 ** parameter is 0, this is a read operation (data copied into
52066 ** buffer pBuf). If it is non-zero, a write (data copied from
52067 ** buffer pBuf).
52068 **
52069 ** A total of "amt" bytes are read or written beginning at "offset".
52070 ** Data is read to or from the buffer pBuf.
52071 **
52072 ** The content being read or written might appear on the main page
52073 ** or be scattered out on multiple overflow pages.
52074 **
52075 ** If the BtCursor.isIncrblobHandle flag is set, and the current
52076 ** cursor entry uses one or more overflow pages, this function
52077 ** allocates space for and lazily popluates the overflow page-list
52078 ** cache array (BtCursor.aOverflow). Subsequent calls use this
52079 ** cache to make seeking to the supplied offset more efficient.
52080 **
52081 ** Once an overflow page-list cache has been allocated, it may be
52082 ** invalidated if some other cursor writes to the same table, or if
52083 ** the cursor is moved to a different row. Additionally, in auto-vacuum
52084 ** mode, the following events may invalidate an overflow page-list cache.
52085 **
52086 **   * An incremental vacuum,
52087 **   * A commit in auto_vacuum="full" mode,
52088 **   * Creating a table (may require moving an overflow page).
52089 */
52090 static int accessPayload(
52091   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52092   u32 offset,          /* Begin reading this far into payload */
52093   u32 amt,             /* Read this many bytes */
52094   unsigned char *pBuf, /* Write the bytes into this buffer */
52095   int eOp              /* zero to read. non-zero to write. */
52096 ){
52097   unsigned char *aPayload;
52098   int rc = SQLITE_OK;
52099   u32 nKey;
52100   int iIdx = 0;
52101   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
52102   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
52103 
52104   assert( pPage );
52105   assert( pCur->eState==CURSOR_VALID );
52106   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52107   assert( cursorHoldsMutex(pCur) );
52108 
52109   getCellInfo(pCur);
52110   aPayload = pCur->info.pCell + pCur->info.nHeader;
52111   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
52112 
52113   if( NEVER(offset+amt > nKey+pCur->info.nData)
52114    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
52115   ){
52116     /* Trying to read or write past the end of the data is an error */
52117     return SQLITE_CORRUPT_BKPT;
52118   }
52119 
52120   /* Check if data must be read/written to/from the btree page itself. */
52121   if( offset<pCur->info.nLocal ){
52122     int a = amt;
52123     if( a+offset>pCur->info.nLocal ){
52124       a = pCur->info.nLocal - offset;
52125     }
52126     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
52127     offset = 0;
52128     pBuf += a;
52129     amt -= a;
52130   }else{
52131     offset -= pCur->info.nLocal;
52132   }
52133 
52134   if( rc==SQLITE_OK && amt>0 ){
52135     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
52136     Pgno nextPage;
52137 
52138     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
52139 
52140 #ifndef SQLITE_OMIT_INCRBLOB
52141     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
52142     ** has not been allocated, allocate it now. The array is sized at
52143     ** one entry for each overflow page in the overflow chain. The
52144     ** page number of the first overflow page is stored in aOverflow[0],
52145     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
52146     ** (the cache is lazily populated).
52147     */
52148     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
52149       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
52150       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
52151       /* nOvfl is always positive.  If it were zero, fetchPayload would have
52152       ** been used instead of this routine. */
52153       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
52154         rc = SQLITE_NOMEM;
52155       }
52156     }
52157 
52158     /* If the overflow page-list cache has been allocated and the
52159     ** entry for the first required overflow page is valid, skip
52160     ** directly to it.
52161     */
52162     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
52163       iIdx = (offset/ovflSize);
52164       nextPage = pCur->aOverflow[iIdx];
52165       offset = (offset%ovflSize);
52166     }
52167 #endif
52168 
52169     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
52170 
52171 #ifndef SQLITE_OMIT_INCRBLOB
52172       /* If required, populate the overflow page-list cache. */
52173       if( pCur->aOverflow ){
52174         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
52175         pCur->aOverflow[iIdx] = nextPage;
52176       }
52177 #endif
52178 
52179       if( offset>=ovflSize ){
52180         /* The only reason to read this page is to obtain the page
52181         ** number for the next page in the overflow chain. The page
52182         ** data is not required. So first try to lookup the overflow
52183         ** page-list cache, if any, then fall back to the getOverflowPage()
52184         ** function.
52185         */
52186 #ifndef SQLITE_OMIT_INCRBLOB
52187         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
52188           nextPage = pCur->aOverflow[iIdx+1];
52189         } else
52190 #endif
52191           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
52192         offset -= ovflSize;
52193       }else{
52194         /* Need to read this page properly. It contains some of the
52195         ** range of data that is being read (eOp==0) or written (eOp!=0).
52196         */
52197         DbPage *pDbPage;
52198         int a = amt;
52199         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
52200         if( rc==SQLITE_OK ){
52201           aPayload = sqlite3PagerGetData(pDbPage);
52202           nextPage = get4byte(aPayload);
52203           if( a + offset > ovflSize ){
52204             a = ovflSize - offset;
52205           }
52206           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
52207           sqlite3PagerUnref(pDbPage);
52208           offset = 0;
52209           amt -= a;
52210           pBuf += a;
52211         }
52212       }
52213     }
52214   }
52215 
52216   if( rc==SQLITE_OK && amt>0 ){
52217     return SQLITE_CORRUPT_BKPT;
52218   }
52219   return rc;
52220 }
52221 
52222 /*
52223 ** Read part of the key associated with cursor pCur.  Exactly
52224 ** "amt" bytes will be transfered into pBuf[].  The transfer
52225 ** begins at "offset".
52226 **
52227 ** The caller must ensure that pCur is pointing to a valid row
52228 ** in the table.
52229 **
52230 ** Return SQLITE_OK on success or an error code if anything goes
52231 ** wrong.  An error is returned if "offset+amt" is larger than
52232 ** the available payload.
52233 */
52234 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52235   assert( cursorHoldsMutex(pCur) );
52236   assert( pCur->eState==CURSOR_VALID );
52237   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52238   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52239   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
52240 }
52241 
52242 /*
52243 ** Read part of the data associated with cursor pCur.  Exactly
52244 ** "amt" bytes will be transfered into pBuf[].  The transfer
52245 ** begins at "offset".
52246 **
52247 ** Return SQLITE_OK on success or an error code if anything goes
52248 ** wrong.  An error is returned if "offset+amt" is larger than
52249 ** the available payload.
52250 */
52251 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
52252   int rc;
52253 
52254 #ifndef SQLITE_OMIT_INCRBLOB
52255   if ( pCur->eState==CURSOR_INVALID ){
52256     return SQLITE_ABORT;
52257   }
52258 #endif
52259 
52260   assert( cursorHoldsMutex(pCur) );
52261   rc = restoreCursorPosition(pCur);
52262   if( rc==SQLITE_OK ){
52263     assert( pCur->eState==CURSOR_VALID );
52264     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
52265     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52266     rc = accessPayload(pCur, offset, amt, pBuf, 0);
52267   }
52268   return rc;
52269 }
52270 
52271 /*
52272 ** Return a pointer to payload information from the entry that the
52273 ** pCur cursor is pointing to.  The pointer is to the beginning of
52274 ** the key if skipKey==0 and it points to the beginning of data if
52275 ** skipKey==1.  The number of bytes of available key/data is written
52276 ** into *pAmt.  If *pAmt==0, then the value returned will not be
52277 ** a valid pointer.
52278 **
52279 ** This routine is an optimization.  It is common for the entire key
52280 ** and data to fit on the local page and for there to be no overflow
52281 ** pages.  When that is so, this routine can be used to access the
52282 ** key and data without making a copy.  If the key and/or data spills
52283 ** onto overflow pages, then accessPayload() must be used to reassemble
52284 ** the key/data and copy it into a preallocated buffer.
52285 **
52286 ** The pointer returned by this routine looks directly into the cached
52287 ** page of the database.  The data might change or move the next time
52288 ** any btree routine is called.
52289 */
52290 static const unsigned char *fetchPayload(
52291   BtCursor *pCur,      /* Cursor pointing to entry to read from */
52292   int *pAmt,           /* Write the number of available bytes here */
52293   int skipKey          /* read beginning at data if this is true */
52294 ){
52295   unsigned char *aPayload;
52296   MemPage *pPage;
52297   u32 nKey;
52298   u32 nLocal;
52299 
52300   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
52301   assert( pCur->eState==CURSOR_VALID );
52302   assert( cursorHoldsMutex(pCur) );
52303   pPage = pCur->apPage[pCur->iPage];
52304   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52305   if( NEVER(pCur->info.nSize==0) ){
52306     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
52307                    &pCur->info);
52308   }
52309   aPayload = pCur->info.pCell;
52310   aPayload += pCur->info.nHeader;
52311   if( pPage->intKey ){
52312     nKey = 0;
52313   }else{
52314     nKey = (int)pCur->info.nKey;
52315   }
52316   if( skipKey ){
52317     aPayload += nKey;
52318     nLocal = pCur->info.nLocal - nKey;
52319   }else{
52320     nLocal = pCur->info.nLocal;
52321     assert( nLocal<=nKey );
52322   }
52323   *pAmt = nLocal;
52324   return aPayload;
52325 }
52326 
52327 
52328 /*
52329 ** For the entry that cursor pCur is point to, return as
52330 ** many bytes of the key or data as are available on the local
52331 ** b-tree page.  Write the number of available bytes into *pAmt.
52332 **
52333 ** The pointer returned is ephemeral.  The key/data may move
52334 ** or be destroyed on the next call to any Btree routine,
52335 ** including calls from other threads against the same cache.
52336 ** Hence, a mutex on the BtShared should be held prior to calling
52337 ** this routine.
52338 **
52339 ** These routines is used to get quick access to key and data
52340 ** in the common case where no overflow pages are used.
52341 */
52342 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
52343   const void *p = 0;
52344   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52345   assert( cursorHoldsMutex(pCur) );
52346   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52347     p = (const void*)fetchPayload(pCur, pAmt, 0);
52348   }
52349   return p;
52350 }
52351 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
52352   const void *p = 0;
52353   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52354   assert( cursorHoldsMutex(pCur) );
52355   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
52356     p = (const void*)fetchPayload(pCur, pAmt, 1);
52357   }
52358   return p;
52359 }
52360 
52361 
52362 /*
52363 ** Move the cursor down to a new child page.  The newPgno argument is the
52364 ** page number of the child page to move to.
52365 **
52366 ** This function returns SQLITE_CORRUPT if the page-header flags field of
52367 ** the new child page does not match the flags field of the parent (i.e.
52368 ** if an intkey page appears to be the parent of a non-intkey page, or
52369 ** vice-versa).
52370 */
52371 static int moveToChild(BtCursor *pCur, u32 newPgno){
52372   int rc;
52373   int i = pCur->iPage;
52374   MemPage *pNewPage;
52375   BtShared *pBt = pCur->pBt;
52376 
52377   assert( cursorHoldsMutex(pCur) );
52378   assert( pCur->eState==CURSOR_VALID );
52379   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
52380   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
52381     return SQLITE_CORRUPT_BKPT;
52382   }
52383   rc = getAndInitPage(pBt, newPgno, &pNewPage);
52384   if( rc ) return rc;
52385   pCur->apPage[i+1] = pNewPage;
52386   pCur->aiIdx[i+1] = 0;
52387   pCur->iPage++;
52388 
52389   pCur->info.nSize = 0;
52390   pCur->validNKey = 0;
52391   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
52392     return SQLITE_CORRUPT_BKPT;
52393   }
52394   return SQLITE_OK;
52395 }
52396 
52397 #ifndef NDEBUG
52398 /*
52399 ** Page pParent is an internal (non-leaf) tree page. This function
52400 ** asserts that page number iChild is the left-child if the iIdx'th
52401 ** cell in page pParent. Or, if iIdx is equal to the total number of
52402 ** cells in pParent, that page number iChild is the right-child of
52403 ** the page.
52404 */
52405 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
52406   assert( iIdx<=pParent->nCell );
52407   if( iIdx==pParent->nCell ){
52408     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
52409   }else{
52410     assert( get4byte(findCell(pParent, iIdx))==iChild );
52411   }
52412 }
52413 #else
52414 #  define assertParentIndex(x,y,z)
52415 #endif
52416 
52417 /*
52418 ** Move the cursor up to the parent page.
52419 **
52420 ** pCur->idx is set to the cell index that contains the pointer
52421 ** to the page we are coming from.  If we are coming from the
52422 ** right-most child page then pCur->idx is set to one more than
52423 ** the largest cell index.
52424 */
52425 static void moveToParent(BtCursor *pCur){
52426   assert( cursorHoldsMutex(pCur) );
52427   assert( pCur->eState==CURSOR_VALID );
52428   assert( pCur->iPage>0 );
52429   assert( pCur->apPage[pCur->iPage] );
52430   assertParentIndex(
52431     pCur->apPage[pCur->iPage-1],
52432     pCur->aiIdx[pCur->iPage-1],
52433     pCur->apPage[pCur->iPage]->pgno
52434   );
52435   releasePage(pCur->apPage[pCur->iPage]);
52436   pCur->iPage--;
52437   pCur->info.nSize = 0;
52438   pCur->validNKey = 0;
52439 }
52440 
52441 /*
52442 ** Move the cursor to point to the root page of its b-tree structure.
52443 **
52444 ** If the table has a virtual root page, then the cursor is moved to point
52445 ** to the virtual root page instead of the actual root page. A table has a
52446 ** virtual root page when the actual root page contains no cells and a
52447 ** single child page. This can only happen with the table rooted at page 1.
52448 **
52449 ** If the b-tree structure is empty, the cursor state is set to
52450 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
52451 ** cell located on the root (or virtual root) page and the cursor state
52452 ** is set to CURSOR_VALID.
52453 **
52454 ** If this function returns successfully, it may be assumed that the
52455 ** page-header flags indicate that the [virtual] root-page is the expected
52456 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
52457 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
52458 ** indicating a table b-tree, or if the caller did specify a KeyInfo
52459 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
52460 ** b-tree).
52461 */
52462 static int moveToRoot(BtCursor *pCur){
52463   MemPage *pRoot;
52464   int rc = SQLITE_OK;
52465   Btree *p = pCur->pBtree;
52466   BtShared *pBt = p->pBt;
52467 
52468   assert( cursorHoldsMutex(pCur) );
52469   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
52470   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
52471   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
52472   if( pCur->eState>=CURSOR_REQUIRESEEK ){
52473     if( pCur->eState==CURSOR_FAULT ){
52474       assert( pCur->skipNext!=SQLITE_OK );
52475       return pCur->skipNext;
52476     }
52477     sqlite3BtreeClearCursor(pCur);
52478   }
52479 
52480   if( pCur->iPage>=0 ){
52481     int i;
52482     for(i=1; i<=pCur->iPage; i++){
52483       releasePage(pCur->apPage[i]);
52484     }
52485     pCur->iPage = 0;
52486   }else if( pCur->pgnoRoot==0 ){
52487     pCur->eState = CURSOR_INVALID;
52488     return SQLITE_OK;
52489   }else{
52490     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
52491     if( rc!=SQLITE_OK ){
52492       pCur->eState = CURSOR_INVALID;
52493       return rc;
52494     }
52495     pCur->iPage = 0;
52496 
52497     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
52498     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
52499     ** NULL, the caller expects a table b-tree. If this is not the case,
52500     ** return an SQLITE_CORRUPT error.  */
52501     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
52502     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
52503       return SQLITE_CORRUPT_BKPT;
52504     }
52505   }
52506 
52507   /* Assert that the root page is of the correct type. This must be the
52508   ** case as the call to this function that loaded the root-page (either
52509   ** this call or a previous invocation) would have detected corruption
52510   ** if the assumption were not true, and it is not possible for the flags
52511   ** byte to have been modified while this cursor is holding a reference
52512   ** to the page.  */
52513   pRoot = pCur->apPage[0];
52514   assert( pRoot->pgno==pCur->pgnoRoot );
52515   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
52516 
52517   pCur->aiIdx[0] = 0;
52518   pCur->info.nSize = 0;
52519   pCur->atLast = 0;
52520   pCur->validNKey = 0;
52521 
52522   if( pRoot->nCell==0 && !pRoot->leaf ){
52523     Pgno subpage;
52524     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
52525     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
52526     pCur->eState = CURSOR_VALID;
52527     rc = moveToChild(pCur, subpage);
52528   }else{
52529     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
52530   }
52531   return rc;
52532 }
52533 
52534 /*
52535 ** Move the cursor down to the left-most leaf entry beneath the
52536 ** entry to which it is currently pointing.
52537 **
52538 ** The left-most leaf is the one with the smallest key - the first
52539 ** in ascending order.
52540 */
52541 static int moveToLeftmost(BtCursor *pCur){
52542   Pgno pgno;
52543   int rc = SQLITE_OK;
52544   MemPage *pPage;
52545 
52546   assert( cursorHoldsMutex(pCur) );
52547   assert( pCur->eState==CURSOR_VALID );
52548   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52549     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
52550     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
52551     rc = moveToChild(pCur, pgno);
52552   }
52553   return rc;
52554 }
52555 
52556 /*
52557 ** Move the cursor down to the right-most leaf entry beneath the
52558 ** page to which it is currently pointing.  Notice the difference
52559 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
52560 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
52561 ** finds the right-most entry beneath the *page*.
52562 **
52563 ** The right-most entry is the one with the largest key - the last
52564 ** key in ascending order.
52565 */
52566 static int moveToRightmost(BtCursor *pCur){
52567   Pgno pgno;
52568   int rc = SQLITE_OK;
52569   MemPage *pPage = 0;
52570 
52571   assert( cursorHoldsMutex(pCur) );
52572   assert( pCur->eState==CURSOR_VALID );
52573   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
52574     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52575     pCur->aiIdx[pCur->iPage] = pPage->nCell;
52576     rc = moveToChild(pCur, pgno);
52577   }
52578   if( rc==SQLITE_OK ){
52579     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
52580     pCur->info.nSize = 0;
52581     pCur->validNKey = 0;
52582   }
52583   return rc;
52584 }
52585 
52586 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
52587 ** on success.  Set *pRes to 0 if the cursor actually points to something
52588 ** or set *pRes to 1 if the table is empty.
52589 */
52590 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
52591   int rc;
52592 
52593   assert( cursorHoldsMutex(pCur) );
52594   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52595   rc = moveToRoot(pCur);
52596   if( rc==SQLITE_OK ){
52597     if( pCur->eState==CURSOR_INVALID ){
52598       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52599       *pRes = 1;
52600     }else{
52601       assert( pCur->apPage[pCur->iPage]->nCell>0 );
52602       *pRes = 0;
52603       rc = moveToLeftmost(pCur);
52604     }
52605   }
52606   return rc;
52607 }
52608 
52609 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
52610 ** on success.  Set *pRes to 0 if the cursor actually points to something
52611 ** or set *pRes to 1 if the table is empty.
52612 */
52613 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
52614   int rc;
52615 
52616   assert( cursorHoldsMutex(pCur) );
52617   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52618 
52619   /* If the cursor already points to the last entry, this is a no-op. */
52620   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
52621 #ifdef SQLITE_DEBUG
52622     /* This block serves to assert() that the cursor really does point
52623     ** to the last entry in the b-tree. */
52624     int ii;
52625     for(ii=0; ii<pCur->iPage; ii++){
52626       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
52627     }
52628     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
52629     assert( pCur->apPage[pCur->iPage]->leaf );
52630 #endif
52631     return SQLITE_OK;
52632   }
52633 
52634   rc = moveToRoot(pCur);
52635   if( rc==SQLITE_OK ){
52636     if( CURSOR_INVALID==pCur->eState ){
52637       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52638       *pRes = 1;
52639     }else{
52640       assert( pCur->eState==CURSOR_VALID );
52641       *pRes = 0;
52642       rc = moveToRightmost(pCur);
52643       pCur->atLast = rc==SQLITE_OK ?1:0;
52644     }
52645   }
52646   return rc;
52647 }
52648 
52649 /* Move the cursor so that it points to an entry near the key
52650 ** specified by pIdxKey or intKey.   Return a success code.
52651 **
52652 ** For INTKEY tables, the intKey parameter is used.  pIdxKey
52653 ** must be NULL.  For index tables, pIdxKey is used and intKey
52654 ** is ignored.
52655 **
52656 ** If an exact match is not found, then the cursor is always
52657 ** left pointing at a leaf page which would hold the entry if it
52658 ** were present.  The cursor might point to an entry that comes
52659 ** before or after the key.
52660 **
52661 ** An integer is written into *pRes which is the result of
52662 ** comparing the key with the entry to which the cursor is
52663 ** pointing.  The meaning of the integer written into
52664 ** *pRes is as follows:
52665 **
52666 **     *pRes<0      The cursor is left pointing at an entry that
52667 **                  is smaller than intKey/pIdxKey or if the table is empty
52668 **                  and the cursor is therefore left point to nothing.
52669 **
52670 **     *pRes==0     The cursor is left pointing at an entry that
52671 **                  exactly matches intKey/pIdxKey.
52672 **
52673 **     *pRes>0      The cursor is left pointing at an entry that
52674 **                  is larger than intKey/pIdxKey.
52675 **
52676 */
52677 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
52678   BtCursor *pCur,          /* The cursor to be moved */
52679   UnpackedRecord *pIdxKey, /* Unpacked index key */
52680   i64 intKey,              /* The table key */
52681   int biasRight,           /* If true, bias the search to the high end */
52682   int *pRes                /* Write search results here */
52683 ){
52684   int rc;
52685 
52686   assert( cursorHoldsMutex(pCur) );
52687   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
52688   assert( pRes );
52689   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
52690 
52691   /* If the cursor is already positioned at the point we are trying
52692   ** to move to, then just return without doing any work */
52693   if( pCur->eState==CURSOR_VALID && pCur->validNKey
52694    && pCur->apPage[0]->intKey
52695   ){
52696     if( pCur->info.nKey==intKey ){
52697       *pRes = 0;
52698       return SQLITE_OK;
52699     }
52700     if( pCur->atLast && pCur->info.nKey<intKey ){
52701       *pRes = -1;
52702       return SQLITE_OK;
52703     }
52704   }
52705 
52706   rc = moveToRoot(pCur);
52707   if( rc ){
52708     return rc;
52709   }
52710   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
52711   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
52712   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
52713   if( pCur->eState==CURSOR_INVALID ){
52714     *pRes = -1;
52715     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
52716     return SQLITE_OK;
52717   }
52718   assert( pCur->apPage[0]->intKey || pIdxKey );
52719   for(;;){
52720     int lwr, upr, idx;
52721     Pgno chldPg;
52722     MemPage *pPage = pCur->apPage[pCur->iPage];
52723     int c;
52724 
52725     /* pPage->nCell must be greater than zero. If this is the root-page
52726     ** the cursor would have been INVALID above and this for(;;) loop
52727     ** not run. If this is not the root-page, then the moveToChild() routine
52728     ** would have already detected db corruption. Similarly, pPage must
52729     ** be the right kind (index or table) of b-tree page. Otherwise
52730     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
52731     assert( pPage->nCell>0 );
52732     assert( pPage->intKey==(pIdxKey==0) );
52733     lwr = 0;
52734     upr = pPage->nCell-1;
52735     if( biasRight ){
52736       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
52737     }else{
52738       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
52739     }
52740     for(;;){
52741       u8 *pCell;                          /* Pointer to current cell in pPage */
52742 
52743       assert( idx==pCur->aiIdx[pCur->iPage] );
52744       pCur->info.nSize = 0;
52745       pCell = findCell(pPage, idx) + pPage->childPtrSize;
52746       if( pPage->intKey ){
52747         i64 nCellKey;
52748         if( pPage->hasData ){
52749           u32 dummy;
52750           pCell += getVarint32(pCell, dummy);
52751         }
52752         getVarint(pCell, (u64*)&nCellKey);
52753         if( nCellKey==intKey ){
52754           c = 0;
52755         }else if( nCellKey<intKey ){
52756           c = -1;
52757         }else{
52758           assert( nCellKey>intKey );
52759           c = +1;
52760         }
52761         pCur->validNKey = 1;
52762         pCur->info.nKey = nCellKey;
52763       }else{
52764         /* The maximum supported page-size is 65536 bytes. This means that
52765         ** the maximum number of record bytes stored on an index B-Tree
52766         ** page is less than 16384 bytes and may be stored as a 2-byte
52767         ** varint. This information is used to attempt to avoid parsing
52768         ** the entire cell by checking for the cases where the record is
52769         ** stored entirely within the b-tree page by inspecting the first
52770         ** 2 bytes of the cell.
52771         */
52772         int nCell = pCell[0];
52773         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
52774           /* This branch runs if the record-size field of the cell is a
52775           ** single byte varint and the record fits entirely on the main
52776           ** b-tree page.  */
52777           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
52778         }else if( !(pCell[1] & 0x80)
52779           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
52780         ){
52781           /* The record-size field is a 2 byte varint and the record
52782           ** fits entirely on the main b-tree page.  */
52783           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
52784         }else{
52785           /* The record flows over onto one or more overflow pages. In
52786           ** this case the whole cell needs to be parsed, a buffer allocated
52787           ** and accessPayload() used to retrieve the record into the
52788           ** buffer before VdbeRecordCompare() can be called. */
52789           void *pCellKey;
52790           u8 * const pCellBody = pCell - pPage->childPtrSize;
52791           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
52792           nCell = (int)pCur->info.nKey;
52793           pCellKey = sqlite3Malloc( nCell );
52794           if( pCellKey==0 ){
52795             rc = SQLITE_NOMEM;
52796             goto moveto_finish;
52797           }
52798           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
52799           if( rc ){
52800             sqlite3_free(pCellKey);
52801             goto moveto_finish;
52802           }
52803           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
52804           sqlite3_free(pCellKey);
52805         }
52806       }
52807       if( c==0 ){
52808         if( pPage->intKey && !pPage->leaf ){
52809           lwr = idx;
52810           upr = lwr - 1;
52811           break;
52812         }else{
52813           *pRes = 0;
52814           rc = SQLITE_OK;
52815           goto moveto_finish;
52816         }
52817       }
52818       if( c<0 ){
52819         lwr = idx+1;
52820       }else{
52821         upr = idx-1;
52822       }
52823       if( lwr>upr ){
52824         break;
52825       }
52826       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
52827     }
52828     assert( lwr==upr+1 );
52829     assert( pPage->isInit );
52830     if( pPage->leaf ){
52831       chldPg = 0;
52832     }else if( lwr>=pPage->nCell ){
52833       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52834     }else{
52835       chldPg = get4byte(findCell(pPage, lwr));
52836     }
52837     if( chldPg==0 ){
52838       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
52839       *pRes = c;
52840       rc = SQLITE_OK;
52841       goto moveto_finish;
52842     }
52843     pCur->aiIdx[pCur->iPage] = (u16)lwr;
52844     pCur->info.nSize = 0;
52845     pCur->validNKey = 0;
52846     rc = moveToChild(pCur, chldPg);
52847     if( rc ) goto moveto_finish;
52848   }
52849 moveto_finish:
52850   return rc;
52851 }
52852 
52853 
52854 /*
52855 ** Return TRUE if the cursor is not pointing at an entry of the table.
52856 **
52857 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
52858 ** past the last entry in the table or sqlite3BtreePrev() moves past
52859 ** the first entry.  TRUE is also returned if the table is empty.
52860 */
52861 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
52862   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
52863   ** have been deleted? This API will need to change to return an error code
52864   ** as well as the boolean result value.
52865   */
52866   return (CURSOR_VALID!=pCur->eState);
52867 }
52868 
52869 /*
52870 ** Advance the cursor to the next entry in the database.  If
52871 ** successful then set *pRes=0.  If the cursor
52872 ** was already pointing to the last entry in the database before
52873 ** this routine was called, then set *pRes=1.
52874 */
52875 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
52876   int rc;
52877   int idx;
52878   MemPage *pPage;
52879 
52880   assert( cursorHoldsMutex(pCur) );
52881   rc = restoreCursorPosition(pCur);
52882   if( rc!=SQLITE_OK ){
52883     return rc;
52884   }
52885   assert( pRes!=0 );
52886   if( CURSOR_INVALID==pCur->eState ){
52887     *pRes = 1;
52888     return SQLITE_OK;
52889   }
52890   if( pCur->skipNext>0 ){
52891     pCur->skipNext = 0;
52892     *pRes = 0;
52893     return SQLITE_OK;
52894   }
52895   pCur->skipNext = 0;
52896 
52897   pPage = pCur->apPage[pCur->iPage];
52898   idx = ++pCur->aiIdx[pCur->iPage];
52899   assert( pPage->isInit );
52900   assert( idx<=pPage->nCell );
52901 
52902   pCur->info.nSize = 0;
52903   pCur->validNKey = 0;
52904   if( idx>=pPage->nCell ){
52905     if( !pPage->leaf ){
52906       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
52907       if( rc ) return rc;
52908       rc = moveToLeftmost(pCur);
52909       *pRes = 0;
52910       return rc;
52911     }
52912     do{
52913       if( pCur->iPage==0 ){
52914         *pRes = 1;
52915         pCur->eState = CURSOR_INVALID;
52916         return SQLITE_OK;
52917       }
52918       moveToParent(pCur);
52919       pPage = pCur->apPage[pCur->iPage];
52920     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
52921     *pRes = 0;
52922     if( pPage->intKey ){
52923       rc = sqlite3BtreeNext(pCur, pRes);
52924     }else{
52925       rc = SQLITE_OK;
52926     }
52927     return rc;
52928   }
52929   *pRes = 0;
52930   if( pPage->leaf ){
52931     return SQLITE_OK;
52932   }
52933   rc = moveToLeftmost(pCur);
52934   return rc;
52935 }
52936 
52937 
52938 /*
52939 ** Step the cursor to the back to the previous entry in the database.  If
52940 ** successful then set *pRes=0.  If the cursor
52941 ** was already pointing to the first entry in the database before
52942 ** this routine was called, then set *pRes=1.
52943 */
52944 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
52945   int rc;
52946   MemPage *pPage;
52947 
52948   assert( cursorHoldsMutex(pCur) );
52949   rc = restoreCursorPosition(pCur);
52950   if( rc!=SQLITE_OK ){
52951     return rc;
52952   }
52953   pCur->atLast = 0;
52954   if( CURSOR_INVALID==pCur->eState ){
52955     *pRes = 1;
52956     return SQLITE_OK;
52957   }
52958   if( pCur->skipNext<0 ){
52959     pCur->skipNext = 0;
52960     *pRes = 0;
52961     return SQLITE_OK;
52962   }
52963   pCur->skipNext = 0;
52964 
52965   pPage = pCur->apPage[pCur->iPage];
52966   assert( pPage->isInit );
52967   if( !pPage->leaf ){
52968     int idx = pCur->aiIdx[pCur->iPage];
52969     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
52970     if( rc ){
52971       return rc;
52972     }
52973     rc = moveToRightmost(pCur);
52974   }else{
52975     while( pCur->aiIdx[pCur->iPage]==0 ){
52976       if( pCur->iPage==0 ){
52977         pCur->eState = CURSOR_INVALID;
52978         *pRes = 1;
52979         return SQLITE_OK;
52980       }
52981       moveToParent(pCur);
52982     }
52983     pCur->info.nSize = 0;
52984     pCur->validNKey = 0;
52985 
52986     pCur->aiIdx[pCur->iPage]--;
52987     pPage = pCur->apPage[pCur->iPage];
52988     if( pPage->intKey && !pPage->leaf ){
52989       rc = sqlite3BtreePrevious(pCur, pRes);
52990     }else{
52991       rc = SQLITE_OK;
52992     }
52993   }
52994   *pRes = 0;
52995   return rc;
52996 }
52997 
52998 /*
52999 ** Allocate a new page from the database file.
53000 **
53001 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
53002 ** has already been called on the new page.)  The new page has also
53003 ** been referenced and the calling routine is responsible for calling
53004 ** sqlite3PagerUnref() on the new page when it is done.
53005 **
53006 ** SQLITE_OK is returned on success.  Any other return value indicates
53007 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
53008 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
53009 **
53010 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
53011 ** locate a page close to the page number "nearby".  This can be used in an
53012 ** attempt to keep related pages close to each other in the database file,
53013 ** which in turn can make database access faster.
53014 **
53015 ** If the "exact" parameter is not 0, and the page-number nearby exists
53016 ** anywhere on the free-list, then it is guarenteed to be returned. This
53017 ** is only used by auto-vacuum databases when allocating a new table.
53018 */
53019 static int allocateBtreePage(
53020   BtShared *pBt,
53021   MemPage **ppPage,
53022   Pgno *pPgno,
53023   Pgno nearby,
53024   u8 exact
53025 ){
53026   MemPage *pPage1;
53027   int rc;
53028   u32 n;     /* Number of pages on the freelist */
53029   u32 k;     /* Number of leaves on the trunk of the freelist */
53030   MemPage *pTrunk = 0;
53031   MemPage *pPrevTrunk = 0;
53032   Pgno mxPage;     /* Total size of the database file */
53033 
53034   assert( sqlite3_mutex_held(pBt->mutex) );
53035   pPage1 = pBt->pPage1;
53036   mxPage = btreePagecount(pBt);
53037   n = get4byte(&pPage1->aData[36]);
53038   testcase( n==mxPage-1 );
53039   if( n>=mxPage ){
53040     return SQLITE_CORRUPT_BKPT;
53041   }
53042   if( n>0 ){
53043     /* There are pages on the freelist.  Reuse one of those pages. */
53044     Pgno iTrunk;
53045     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
53046 
53047     /* If the 'exact' parameter was true and a query of the pointer-map
53048     ** shows that the page 'nearby' is somewhere on the free-list, then
53049     ** the entire-list will be searched for that page.
53050     */
53051 #ifndef SQLITE_OMIT_AUTOVACUUM
53052     if( exact && nearby<=mxPage ){
53053       u8 eType;
53054       assert( nearby>0 );
53055       assert( pBt->autoVacuum );
53056       rc = ptrmapGet(pBt, nearby, &eType, 0);
53057       if( rc ) return rc;
53058       if( eType==PTRMAP_FREEPAGE ){
53059         searchList = 1;
53060       }
53061       *pPgno = nearby;
53062     }
53063 #endif
53064 
53065     /* Decrement the free-list count by 1. Set iTrunk to the index of the
53066     ** first free-list trunk page. iPrevTrunk is initially 1.
53067     */
53068     rc = sqlite3PagerWrite(pPage1->pDbPage);
53069     if( rc ) return rc;
53070     put4byte(&pPage1->aData[36], n-1);
53071 
53072     /* The code within this loop is run only once if the 'searchList' variable
53073     ** is not true. Otherwise, it runs once for each trunk-page on the
53074     ** free-list until the page 'nearby' is located.
53075     */
53076     do {
53077       pPrevTrunk = pTrunk;
53078       if( pPrevTrunk ){
53079         iTrunk = get4byte(&pPrevTrunk->aData[0]);
53080       }else{
53081         iTrunk = get4byte(&pPage1->aData[32]);
53082       }
53083       testcase( iTrunk==mxPage );
53084       if( iTrunk>mxPage ){
53085         rc = SQLITE_CORRUPT_BKPT;
53086       }else{
53087         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53088       }
53089       if( rc ){
53090         pTrunk = 0;
53091         goto end_allocate_page;
53092       }
53093 
53094       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
53095       if( k==0 && !searchList ){
53096         /* The trunk has no leaves and the list is not being searched.
53097         ** So extract the trunk page itself and use it as the newly
53098         ** allocated page */
53099         assert( pPrevTrunk==0 );
53100         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53101         if( rc ){
53102           goto end_allocate_page;
53103         }
53104         *pPgno = iTrunk;
53105         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53106         *ppPage = pTrunk;
53107         pTrunk = 0;
53108         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53109       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
53110         /* Value of k is out of range.  Database corruption */
53111         rc = SQLITE_CORRUPT_BKPT;
53112         goto end_allocate_page;
53113 #ifndef SQLITE_OMIT_AUTOVACUUM
53114       }else if( searchList && nearby==iTrunk ){
53115         /* The list is being searched and this trunk page is the page
53116         ** to allocate, regardless of whether it has leaves.
53117         */
53118         assert( *pPgno==iTrunk );
53119         *ppPage = pTrunk;
53120         searchList = 0;
53121         rc = sqlite3PagerWrite(pTrunk->pDbPage);
53122         if( rc ){
53123           goto end_allocate_page;
53124         }
53125         if( k==0 ){
53126           if( !pPrevTrunk ){
53127             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
53128           }else{
53129             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53130             if( rc!=SQLITE_OK ){
53131               goto end_allocate_page;
53132             }
53133             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
53134           }
53135         }else{
53136           /* The trunk page is required by the caller but it contains
53137           ** pointers to free-list leaves. The first leaf becomes a trunk
53138           ** page in this case.
53139           */
53140           MemPage *pNewTrunk;
53141           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
53142           if( iNewTrunk>mxPage ){
53143             rc = SQLITE_CORRUPT_BKPT;
53144             goto end_allocate_page;
53145           }
53146           testcase( iNewTrunk==mxPage );
53147           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
53148           if( rc!=SQLITE_OK ){
53149             goto end_allocate_page;
53150           }
53151           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
53152           if( rc!=SQLITE_OK ){
53153             releasePage(pNewTrunk);
53154             goto end_allocate_page;
53155           }
53156           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
53157           put4byte(&pNewTrunk->aData[4], k-1);
53158           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
53159           releasePage(pNewTrunk);
53160           if( !pPrevTrunk ){
53161             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
53162             put4byte(&pPage1->aData[32], iNewTrunk);
53163           }else{
53164             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
53165             if( rc ){
53166               goto end_allocate_page;
53167             }
53168             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
53169           }
53170         }
53171         pTrunk = 0;
53172         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
53173 #endif
53174       }else if( k>0 ){
53175         /* Extract a leaf from the trunk */
53176         u32 closest;
53177         Pgno iPage;
53178         unsigned char *aData = pTrunk->aData;
53179         if( nearby>0 ){
53180           u32 i;
53181           int dist;
53182           closest = 0;
53183           dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
53184           for(i=1; i<k; i++){
53185             int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
53186             if( d2<dist ){
53187               closest = i;
53188               dist = d2;
53189             }
53190           }
53191         }else{
53192           closest = 0;
53193         }
53194 
53195         iPage = get4byte(&aData[8+closest*4]);
53196         testcase( iPage==mxPage );
53197         if( iPage>mxPage ){
53198           rc = SQLITE_CORRUPT_BKPT;
53199           goto end_allocate_page;
53200         }
53201         testcase( iPage==mxPage );
53202         if( !searchList || iPage==nearby ){
53203           int noContent;
53204           *pPgno = iPage;
53205           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
53206                  ": %d more free pages\n",
53207                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
53208           rc = sqlite3PagerWrite(pTrunk->pDbPage);
53209           if( rc ) goto end_allocate_page;
53210           if( closest<k-1 ){
53211             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
53212           }
53213           put4byte(&aData[4], k-1);
53214           noContent = !btreeGetHasContent(pBt, *pPgno);
53215           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
53216           if( rc==SQLITE_OK ){
53217             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53218             if( rc!=SQLITE_OK ){
53219               releasePage(*ppPage);
53220             }
53221           }
53222           searchList = 0;
53223         }
53224       }
53225       releasePage(pPrevTrunk);
53226       pPrevTrunk = 0;
53227     }while( searchList );
53228   }else{
53229     /* There are no pages on the freelist, so create a new page at the
53230     ** end of the file */
53231     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
53232     if( rc ) return rc;
53233     pBt->nPage++;
53234     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
53235 
53236 #ifndef SQLITE_OMIT_AUTOVACUUM
53237     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
53238       /* If *pPgno refers to a pointer-map page, allocate two new pages
53239       ** at the end of the file instead of one. The first allocated page
53240       ** becomes a new pointer-map page, the second is used by the caller.
53241       */
53242       MemPage *pPg = 0;
53243       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
53244       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
53245       rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
53246       if( rc==SQLITE_OK ){
53247         rc = sqlite3PagerWrite(pPg->pDbPage);
53248         releasePage(pPg);
53249       }
53250       if( rc ) return rc;
53251       pBt->nPage++;
53252       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
53253     }
53254 #endif
53255     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
53256     *pPgno = pBt->nPage;
53257 
53258     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53259     rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
53260     if( rc ) return rc;
53261     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
53262     if( rc!=SQLITE_OK ){
53263       releasePage(*ppPage);
53264     }
53265     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
53266   }
53267 
53268   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
53269 
53270 end_allocate_page:
53271   releasePage(pTrunk);
53272   releasePage(pPrevTrunk);
53273   if( rc==SQLITE_OK ){
53274     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
53275       releasePage(*ppPage);
53276       return SQLITE_CORRUPT_BKPT;
53277     }
53278     (*ppPage)->isInit = 0;
53279   }else{
53280     *ppPage = 0;
53281   }
53282   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
53283   return rc;
53284 }
53285 
53286 /*
53287 ** This function is used to add page iPage to the database file free-list.
53288 ** It is assumed that the page is not already a part of the free-list.
53289 **
53290 ** The value passed as the second argument to this function is optional.
53291 ** If the caller happens to have a pointer to the MemPage object
53292 ** corresponding to page iPage handy, it may pass it as the second value.
53293 ** Otherwise, it may pass NULL.
53294 **
53295 ** If a pointer to a MemPage object is passed as the second argument,
53296 ** its reference count is not altered by this function.
53297 */
53298 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
53299   MemPage *pTrunk = 0;                /* Free-list trunk page */
53300   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
53301   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
53302   MemPage *pPage;                     /* Page being freed. May be NULL. */
53303   int rc;                             /* Return Code */
53304   int nFree;                          /* Initial number of pages on free-list */
53305 
53306   assert( sqlite3_mutex_held(pBt->mutex) );
53307   assert( iPage>1 );
53308   assert( !pMemPage || pMemPage->pgno==iPage );
53309 
53310   if( pMemPage ){
53311     pPage = pMemPage;
53312     sqlite3PagerRef(pPage->pDbPage);
53313   }else{
53314     pPage = btreePageLookup(pBt, iPage);
53315   }
53316 
53317   /* Increment the free page count on pPage1 */
53318   rc = sqlite3PagerWrite(pPage1->pDbPage);
53319   if( rc ) goto freepage_out;
53320   nFree = get4byte(&pPage1->aData[36]);
53321   put4byte(&pPage1->aData[36], nFree+1);
53322 
53323   if( pBt->secureDelete ){
53324     /* If the secure_delete option is enabled, then
53325     ** always fully overwrite deleted information with zeros.
53326     */
53327     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
53328      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
53329     ){
53330       goto freepage_out;
53331     }
53332     memset(pPage->aData, 0, pPage->pBt->pageSize);
53333   }
53334 
53335   /* If the database supports auto-vacuum, write an entry in the pointer-map
53336   ** to indicate that the page is free.
53337   */
53338   if( ISAUTOVACUUM ){
53339     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
53340     if( rc ) goto freepage_out;
53341   }
53342 
53343   /* Now manipulate the actual database free-list structure. There are two
53344   ** possibilities. If the free-list is currently empty, or if the first
53345   ** trunk page in the free-list is full, then this page will become a
53346   ** new free-list trunk page. Otherwise, it will become a leaf of the
53347   ** first trunk page in the current free-list. This block tests if it
53348   ** is possible to add the page as a new free-list leaf.
53349   */
53350   if( nFree!=0 ){
53351     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
53352 
53353     iTrunk = get4byte(&pPage1->aData[32]);
53354     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
53355     if( rc!=SQLITE_OK ){
53356       goto freepage_out;
53357     }
53358 
53359     nLeaf = get4byte(&pTrunk->aData[4]);
53360     assert( pBt->usableSize>32 );
53361     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
53362       rc = SQLITE_CORRUPT_BKPT;
53363       goto freepage_out;
53364     }
53365     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
53366       /* In this case there is room on the trunk page to insert the page
53367       ** being freed as a new leaf.
53368       **
53369       ** Note that the trunk page is not really full until it contains
53370       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
53371       ** coded.  But due to a coding error in versions of SQLite prior to
53372       ** 3.6.0, databases with freelist trunk pages holding more than
53373       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
53374       ** to maintain backwards compatibility with older versions of SQLite,
53375       ** we will continue to restrict the number of entries to usableSize/4 - 8
53376       ** for now.  At some point in the future (once everyone has upgraded
53377       ** to 3.6.0 or later) we should consider fixing the conditional above
53378       ** to read "usableSize/4-2" instead of "usableSize/4-8".
53379       */
53380       rc = sqlite3PagerWrite(pTrunk->pDbPage);
53381       if( rc==SQLITE_OK ){
53382         put4byte(&pTrunk->aData[4], nLeaf+1);
53383         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
53384         if( pPage && !pBt->secureDelete ){
53385           sqlite3PagerDontWrite(pPage->pDbPage);
53386         }
53387         rc = btreeSetHasContent(pBt, iPage);
53388       }
53389       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
53390       goto freepage_out;
53391     }
53392   }
53393 
53394   /* If control flows to this point, then it was not possible to add the
53395   ** the page being freed as a leaf page of the first trunk in the free-list.
53396   ** Possibly because the free-list is empty, or possibly because the
53397   ** first trunk in the free-list is full. Either way, the page being freed
53398   ** will become the new first trunk page in the free-list.
53399   */
53400   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
53401     goto freepage_out;
53402   }
53403   rc = sqlite3PagerWrite(pPage->pDbPage);
53404   if( rc!=SQLITE_OK ){
53405     goto freepage_out;
53406   }
53407   put4byte(pPage->aData, iTrunk);
53408   put4byte(&pPage->aData[4], 0);
53409   put4byte(&pPage1->aData[32], iPage);
53410   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
53411 
53412 freepage_out:
53413   if( pPage ){
53414     pPage->isInit = 0;
53415   }
53416   releasePage(pPage);
53417   releasePage(pTrunk);
53418   return rc;
53419 }
53420 static void freePage(MemPage *pPage, int *pRC){
53421   if( (*pRC)==SQLITE_OK ){
53422     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
53423   }
53424 }
53425 
53426 /*
53427 ** Free any overflow pages associated with the given Cell.
53428 */
53429 static int clearCell(MemPage *pPage, unsigned char *pCell){
53430   BtShared *pBt = pPage->pBt;
53431   CellInfo info;
53432   Pgno ovflPgno;
53433   int rc;
53434   int nOvfl;
53435   u32 ovflPageSize;
53436 
53437   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53438   btreeParseCellPtr(pPage, pCell, &info);
53439   if( info.iOverflow==0 ){
53440     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
53441   }
53442   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
53443     return SQLITE_CORRUPT;  /* Cell extends past end of page */
53444   }
53445   ovflPgno = get4byte(&pCell[info.iOverflow]);
53446   assert( pBt->usableSize > 4 );
53447   ovflPageSize = pBt->usableSize - 4;
53448   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
53449   assert( ovflPgno==0 || nOvfl>0 );
53450   while( nOvfl-- ){
53451     Pgno iNext = 0;
53452     MemPage *pOvfl = 0;
53453     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
53454       /* 0 is not a legal page number and page 1 cannot be an
53455       ** overflow page. Therefore if ovflPgno<2 or past the end of the
53456       ** file the database must be corrupt. */
53457       return SQLITE_CORRUPT_BKPT;
53458     }
53459     if( nOvfl ){
53460       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
53461       if( rc ) return rc;
53462     }
53463 
53464     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
53465      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
53466     ){
53467       /* There is no reason any cursor should have an outstanding reference
53468       ** to an overflow page belonging to a cell that is being deleted/updated.
53469       ** So if there exists more than one reference to this page, then it
53470       ** must not really be an overflow page and the database must be corrupt.
53471       ** It is helpful to detect this before calling freePage2(), as
53472       ** freePage2() may zero the page contents if secure-delete mode is
53473       ** enabled. If this 'overflow' page happens to be a page that the
53474       ** caller is iterating through or using in some other way, this
53475       ** can be problematic.
53476       */
53477       rc = SQLITE_CORRUPT_BKPT;
53478     }else{
53479       rc = freePage2(pBt, pOvfl, ovflPgno);
53480     }
53481 
53482     if( pOvfl ){
53483       sqlite3PagerUnref(pOvfl->pDbPage);
53484     }
53485     if( rc ) return rc;
53486     ovflPgno = iNext;
53487   }
53488   return SQLITE_OK;
53489 }
53490 
53491 /*
53492 ** Create the byte sequence used to represent a cell on page pPage
53493 ** and write that byte sequence into pCell[].  Overflow pages are
53494 ** allocated and filled in as necessary.  The calling procedure
53495 ** is responsible for making sure sufficient space has been allocated
53496 ** for pCell[].
53497 **
53498 ** Note that pCell does not necessary need to point to the pPage->aData
53499 ** area.  pCell might point to some temporary storage.  The cell will
53500 ** be constructed in this temporary area then copied into pPage->aData
53501 ** later.
53502 */
53503 static int fillInCell(
53504   MemPage *pPage,                /* The page that contains the cell */
53505   unsigned char *pCell,          /* Complete text of the cell */
53506   const void *pKey, i64 nKey,    /* The key */
53507   const void *pData,int nData,   /* The data */
53508   int nZero,                     /* Extra zero bytes to append to pData */
53509   int *pnSize                    /* Write cell size here */
53510 ){
53511   int nPayload;
53512   const u8 *pSrc;
53513   int nSrc, n, rc;
53514   int spaceLeft;
53515   MemPage *pOvfl = 0;
53516   MemPage *pToRelease = 0;
53517   unsigned char *pPrior;
53518   unsigned char *pPayload;
53519   BtShared *pBt = pPage->pBt;
53520   Pgno pgnoOvfl = 0;
53521   int nHeader;
53522   CellInfo info;
53523 
53524   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53525 
53526   /* pPage is not necessarily writeable since pCell might be auxiliary
53527   ** buffer space that is separate from the pPage buffer area */
53528   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
53529             || sqlite3PagerIswriteable(pPage->pDbPage) );
53530 
53531   /* Fill in the header. */
53532   nHeader = 0;
53533   if( !pPage->leaf ){
53534     nHeader += 4;
53535   }
53536   if( pPage->hasData ){
53537     nHeader += putVarint(&pCell[nHeader], nData+nZero);
53538   }else{
53539     nData = nZero = 0;
53540   }
53541   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
53542   btreeParseCellPtr(pPage, pCell, &info);
53543   assert( info.nHeader==nHeader );
53544   assert( info.nKey==nKey );
53545   assert( info.nData==(u32)(nData+nZero) );
53546 
53547   /* Fill in the payload */
53548   nPayload = nData + nZero;
53549   if( pPage->intKey ){
53550     pSrc = pData;
53551     nSrc = nData;
53552     nData = 0;
53553   }else{
53554     if( NEVER(nKey>0x7fffffff || pKey==0) ){
53555       return SQLITE_CORRUPT_BKPT;
53556     }
53557     nPayload += (int)nKey;
53558     pSrc = pKey;
53559     nSrc = (int)nKey;
53560   }
53561   *pnSize = info.nSize;
53562   spaceLeft = info.nLocal;
53563   pPayload = &pCell[nHeader];
53564   pPrior = &pCell[info.iOverflow];
53565 
53566   while( nPayload>0 ){
53567     if( spaceLeft==0 ){
53568 #ifndef SQLITE_OMIT_AUTOVACUUM
53569       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
53570       if( pBt->autoVacuum ){
53571         do{
53572           pgnoOvfl++;
53573         } while(
53574           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
53575         );
53576       }
53577 #endif
53578       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
53579 #ifndef SQLITE_OMIT_AUTOVACUUM
53580       /* If the database supports auto-vacuum, and the second or subsequent
53581       ** overflow page is being allocated, add an entry to the pointer-map
53582       ** for that page now.
53583       **
53584       ** If this is the first overflow page, then write a partial entry
53585       ** to the pointer-map. If we write nothing to this pointer-map slot,
53586       ** then the optimistic overflow chain processing in clearCell()
53587       ** may misinterpret the uninitialised values and delete the
53588       ** wrong pages from the database.
53589       */
53590       if( pBt->autoVacuum && rc==SQLITE_OK ){
53591         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
53592         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
53593         if( rc ){
53594           releasePage(pOvfl);
53595         }
53596       }
53597 #endif
53598       if( rc ){
53599         releasePage(pToRelease);
53600         return rc;
53601       }
53602 
53603       /* If pToRelease is not zero than pPrior points into the data area
53604       ** of pToRelease.  Make sure pToRelease is still writeable. */
53605       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53606 
53607       /* If pPrior is part of the data area of pPage, then make sure pPage
53608       ** is still writeable */
53609       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
53610             || sqlite3PagerIswriteable(pPage->pDbPage) );
53611 
53612       put4byte(pPrior, pgnoOvfl);
53613       releasePage(pToRelease);
53614       pToRelease = pOvfl;
53615       pPrior = pOvfl->aData;
53616       put4byte(pPrior, 0);
53617       pPayload = &pOvfl->aData[4];
53618       spaceLeft = pBt->usableSize - 4;
53619     }
53620     n = nPayload;
53621     if( n>spaceLeft ) n = spaceLeft;
53622 
53623     /* If pToRelease is not zero than pPayload points into the data area
53624     ** of pToRelease.  Make sure pToRelease is still writeable. */
53625     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
53626 
53627     /* If pPayload is part of the data area of pPage, then make sure pPage
53628     ** is still writeable */
53629     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
53630             || sqlite3PagerIswriteable(pPage->pDbPage) );
53631 
53632     if( nSrc>0 ){
53633       if( n>nSrc ) n = nSrc;
53634       assert( pSrc );
53635       memcpy(pPayload, pSrc, n);
53636     }else{
53637       memset(pPayload, 0, n);
53638     }
53639     nPayload -= n;
53640     pPayload += n;
53641     pSrc += n;
53642     nSrc -= n;
53643     spaceLeft -= n;
53644     if( nSrc==0 ){
53645       nSrc = nData;
53646       pSrc = pData;
53647     }
53648   }
53649   releasePage(pToRelease);
53650   return SQLITE_OK;
53651 }
53652 
53653 /*
53654 ** Remove the i-th cell from pPage.  This routine effects pPage only.
53655 ** The cell content is not freed or deallocated.  It is assumed that
53656 ** the cell content has been copied someplace else.  This routine just
53657 ** removes the reference to the cell from pPage.
53658 **
53659 ** "sz" must be the number of bytes in the cell.
53660 */
53661 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
53662   u32 pc;         /* Offset to cell content of cell being deleted */
53663   u8 *data;       /* pPage->aData */
53664   u8 *ptr;        /* Used to move bytes around within data[] */
53665   u8 *endPtr;     /* End of loop */
53666   int rc;         /* The return code */
53667   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
53668 
53669   if( *pRC ) return;
53670 
53671   assert( idx>=0 && idx<pPage->nCell );
53672   assert( sz==cellSize(pPage, idx) );
53673   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53674   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53675   data = pPage->aData;
53676   ptr = &data[pPage->cellOffset + 2*idx];
53677   pc = get2byte(ptr);
53678   hdr = pPage->hdrOffset;
53679   testcase( pc==get2byte(&data[hdr+5]) );
53680   testcase( pc+sz==pPage->pBt->usableSize );
53681   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
53682     *pRC = SQLITE_CORRUPT_BKPT;
53683     return;
53684   }
53685   rc = freeSpace(pPage, pc, sz);
53686   if( rc ){
53687     *pRC = rc;
53688     return;
53689   }
53690   endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
53691   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53692   while( ptr<endPtr ){
53693     *(u16*)ptr = *(u16*)&ptr[2];
53694     ptr += 2;
53695   }
53696   pPage->nCell--;
53697   put2byte(&data[hdr+3], pPage->nCell);
53698   pPage->nFree += 2;
53699 }
53700 
53701 /*
53702 ** Insert a new cell on pPage at cell index "i".  pCell points to the
53703 ** content of the cell.
53704 **
53705 ** If the cell content will fit on the page, then put it there.  If it
53706 ** will not fit, then make a copy of the cell content into pTemp if
53707 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
53708 ** in pPage->aOvfl[] and make it point to the cell content (either
53709 ** in pTemp or the original pCell) and also record its index.
53710 ** Allocating a new entry in pPage->aCell[] implies that
53711 ** pPage->nOverflow is incremented.
53712 **
53713 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
53714 ** cell. The caller will overwrite them after this function returns. If
53715 ** nSkip is non-zero, then pCell may not point to an invalid memory location
53716 ** (but pCell+nSkip is always valid).
53717 */
53718 static void insertCell(
53719   MemPage *pPage,   /* Page into which we are copying */
53720   int i,            /* New cell becomes the i-th cell of the page */
53721   u8 *pCell,        /* Content of the new cell */
53722   int sz,           /* Bytes of content in pCell */
53723   u8 *pTemp,        /* Temp storage space for pCell, if needed */
53724   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
53725   int *pRC          /* Read and write return code from here */
53726 ){
53727   int idx = 0;      /* Where to write new cell content in data[] */
53728   int j;            /* Loop counter */
53729   int end;          /* First byte past the last cell pointer in data[] */
53730   int ins;          /* Index in data[] where new cell pointer is inserted */
53731   int cellOffset;   /* Address of first cell pointer in data[] */
53732   u8 *data;         /* The content of the whole page */
53733   u8 *ptr;          /* Used for moving information around in data[] */
53734   u8 *endPtr;       /* End of the loop */
53735 
53736   int nSkip = (iChild ? 4 : 0);
53737 
53738   if( *pRC ) return;
53739 
53740   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
53741   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
53742   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
53743   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53744   /* The cell should normally be sized correctly.  However, when moving a
53745   ** malformed cell from a leaf page to an interior page, if the cell size
53746   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
53747   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
53748   ** the term after the || in the following assert(). */
53749   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
53750   if( pPage->nOverflow || sz+2>pPage->nFree ){
53751     if( pTemp ){
53752       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
53753       pCell = pTemp;
53754     }
53755     if( iChild ){
53756       put4byte(pCell, iChild);
53757     }
53758     j = pPage->nOverflow++;
53759     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
53760     pPage->aOvfl[j].pCell = pCell;
53761     pPage->aOvfl[j].idx = (u16)i;
53762   }else{
53763     int rc = sqlite3PagerWrite(pPage->pDbPage);
53764     if( rc!=SQLITE_OK ){
53765       *pRC = rc;
53766       return;
53767     }
53768     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53769     data = pPage->aData;
53770     cellOffset = pPage->cellOffset;
53771     end = cellOffset + 2*pPage->nCell;
53772     ins = cellOffset + 2*i;
53773     rc = allocateSpace(pPage, sz, &idx);
53774     if( rc ){ *pRC = rc; return; }
53775     /* The allocateSpace() routine guarantees the following two properties
53776     ** if it returns success */
53777     assert( idx >= end+2 );
53778     assert( idx+sz <= (int)pPage->pBt->usableSize );
53779     pPage->nCell++;
53780     pPage->nFree -= (u16)(2 + sz);
53781     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
53782     if( iChild ){
53783       put4byte(&data[idx], iChild);
53784     }
53785     ptr = &data[end];
53786     endPtr = &data[ins];
53787     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
53788     while( ptr>endPtr ){
53789       *(u16*)ptr = *(u16*)&ptr[-2];
53790       ptr -= 2;
53791     }
53792     put2byte(&data[ins], idx);
53793     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
53794 #ifndef SQLITE_OMIT_AUTOVACUUM
53795     if( pPage->pBt->autoVacuum ){
53796       /* The cell may contain a pointer to an overflow page. If so, write
53797       ** the entry for the overflow page into the pointer map.
53798       */
53799       ptrmapPutOvflPtr(pPage, pCell, pRC);
53800     }
53801 #endif
53802   }
53803 }
53804 
53805 /*
53806 ** Add a list of cells to a page.  The page should be initially empty.
53807 ** The cells are guaranteed to fit on the page.
53808 */
53809 static void assemblePage(
53810   MemPage *pPage,   /* The page to be assemblied */
53811   int nCell,        /* The number of cells to add to this page */
53812   u8 **apCell,      /* Pointers to cell bodies */
53813   u16 *aSize        /* Sizes of the cells */
53814 ){
53815   int i;            /* Loop counter */
53816   u8 *pCellptr;     /* Address of next cell pointer */
53817   int cellbody;     /* Address of next cell body */
53818   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
53819   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
53820   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
53821 
53822   assert( pPage->nOverflow==0 );
53823   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53824   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
53825             && (int)MX_CELL(pPage->pBt)<=10921);
53826   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
53827 
53828   /* Check that the page has just been zeroed by zeroPage() */
53829   assert( pPage->nCell==0 );
53830   assert( get2byteNotZero(&data[hdr+5])==nUsable );
53831 
53832   pCellptr = &data[pPage->cellOffset + nCell*2];
53833   cellbody = nUsable;
53834   for(i=nCell-1; i>=0; i--){
53835     u16 sz = aSize[i];
53836     pCellptr -= 2;
53837     cellbody -= sz;
53838     put2byte(pCellptr, cellbody);
53839     memcpy(&data[cellbody], apCell[i], sz);
53840   }
53841   put2byte(&data[hdr+3], nCell);
53842   put2byte(&data[hdr+5], cellbody);
53843   pPage->nFree -= (nCell*2 + nUsable - cellbody);
53844   pPage->nCell = (u16)nCell;
53845 }
53846 
53847 /*
53848 ** The following parameters determine how many adjacent pages get involved
53849 ** in a balancing operation.  NN is the number of neighbors on either side
53850 ** of the page that participate in the balancing operation.  NB is the
53851 ** total number of pages that participate, including the target page and
53852 ** NN neighbors on either side.
53853 **
53854 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
53855 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
53856 ** in exchange for a larger degradation in INSERT and UPDATE performance.
53857 ** The value of NN appears to give the best results overall.
53858 */
53859 #define NN 1             /* Number of neighbors on either side of pPage */
53860 #define NB (NN*2+1)      /* Total pages involved in the balance */
53861 
53862 
53863 #ifndef SQLITE_OMIT_QUICKBALANCE
53864 /*
53865 ** This version of balance() handles the common special case where
53866 ** a new entry is being inserted on the extreme right-end of the
53867 ** tree, in other words, when the new entry will become the largest
53868 ** entry in the tree.
53869 **
53870 ** Instead of trying to balance the 3 right-most leaf pages, just add
53871 ** a new page to the right-hand side and put the one new entry in
53872 ** that page.  This leaves the right side of the tree somewhat
53873 ** unbalanced.  But odds are that we will be inserting new entries
53874 ** at the end soon afterwards so the nearly empty page will quickly
53875 ** fill up.  On average.
53876 **
53877 ** pPage is the leaf page which is the right-most page in the tree.
53878 ** pParent is its parent.  pPage must have a single overflow entry
53879 ** which is also the right-most entry on the page.
53880 **
53881 ** The pSpace buffer is used to store a temporary copy of the divider
53882 ** cell that will be inserted into pParent. Such a cell consists of a 4
53883 ** byte page number followed by a variable length integer. In other
53884 ** words, at most 13 bytes. Hence the pSpace buffer must be at
53885 ** least 13 bytes in size.
53886 */
53887 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
53888   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
53889   MemPage *pNew;                       /* Newly allocated page */
53890   int rc;                              /* Return Code */
53891   Pgno pgnoNew;                        /* Page number of pNew */
53892 
53893   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53894   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
53895   assert( pPage->nOverflow==1 );
53896 
53897   /* This error condition is now caught prior to reaching this function */
53898   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
53899 
53900   /* Allocate a new page. This page will become the right-sibling of
53901   ** pPage. Make the parent page writable, so that the new divider cell
53902   ** may be inserted. If both these operations are successful, proceed.
53903   */
53904   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
53905 
53906   if( rc==SQLITE_OK ){
53907 
53908     u8 *pOut = &pSpace[4];
53909     u8 *pCell = pPage->aOvfl[0].pCell;
53910     u16 szCell = cellSizePtr(pPage, pCell);
53911     u8 *pStop;
53912 
53913     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
53914     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
53915     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
53916     assemblePage(pNew, 1, &pCell, &szCell);
53917 
53918     /* If this is an auto-vacuum database, update the pointer map
53919     ** with entries for the new page, and any pointer from the
53920     ** cell on the page to an overflow page. If either of these
53921     ** operations fails, the return code is set, but the contents
53922     ** of the parent page are still manipulated by thh code below.
53923     ** That is Ok, at this point the parent page is guaranteed to
53924     ** be marked as dirty. Returning an error code will cause a
53925     ** rollback, undoing any changes made to the parent page.
53926     */
53927     if( ISAUTOVACUUM ){
53928       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
53929       if( szCell>pNew->minLocal ){
53930         ptrmapPutOvflPtr(pNew, pCell, &rc);
53931       }
53932     }
53933 
53934     /* Create a divider cell to insert into pParent. The divider cell
53935     ** consists of a 4-byte page number (the page number of pPage) and
53936     ** a variable length key value (which must be the same value as the
53937     ** largest key on pPage).
53938     **
53939     ** To find the largest key value on pPage, first find the right-most
53940     ** cell on pPage. The first two fields of this cell are the
53941     ** record-length (a variable length integer at most 32-bits in size)
53942     ** and the key value (a variable length integer, may have any value).
53943     ** The first of the while(...) loops below skips over the record-length
53944     ** field. The second while(...) loop copies the key value from the
53945     ** cell on pPage into the pSpace buffer.
53946     */
53947     pCell = findCell(pPage, pPage->nCell-1);
53948     pStop = &pCell[9];
53949     while( (*(pCell++)&0x80) && pCell<pStop );
53950     pStop = &pCell[9];
53951     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
53952 
53953     /* Insert the new divider cell into pParent. */
53954     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
53955                0, pPage->pgno, &rc);
53956 
53957     /* Set the right-child pointer of pParent to point to the new page. */
53958     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
53959 
53960     /* Release the reference to the new page. */
53961     releasePage(pNew);
53962   }
53963 
53964   return rc;
53965 }
53966 #endif /* SQLITE_OMIT_QUICKBALANCE */
53967 
53968 #if 0
53969 /*
53970 ** This function does not contribute anything to the operation of SQLite.
53971 ** it is sometimes activated temporarily while debugging code responsible
53972 ** for setting pointer-map entries.
53973 */
53974 static int ptrmapCheckPages(MemPage **apPage, int nPage){
53975   int i, j;
53976   for(i=0; i<nPage; i++){
53977     Pgno n;
53978     u8 e;
53979     MemPage *pPage = apPage[i];
53980     BtShared *pBt = pPage->pBt;
53981     assert( pPage->isInit );
53982 
53983     for(j=0; j<pPage->nCell; j++){
53984       CellInfo info;
53985       u8 *z;
53986 
53987       z = findCell(pPage, j);
53988       btreeParseCellPtr(pPage, z, &info);
53989       if( info.iOverflow ){
53990         Pgno ovfl = get4byte(&z[info.iOverflow]);
53991         ptrmapGet(pBt, ovfl, &e, &n);
53992         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
53993       }
53994       if( !pPage->leaf ){
53995         Pgno child = get4byte(z);
53996         ptrmapGet(pBt, child, &e, &n);
53997         assert( n==pPage->pgno && e==PTRMAP_BTREE );
53998       }
53999     }
54000     if( !pPage->leaf ){
54001       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54002       ptrmapGet(pBt, child, &e, &n);
54003       assert( n==pPage->pgno && e==PTRMAP_BTREE );
54004     }
54005   }
54006   return 1;
54007 }
54008 #endif
54009 
54010 /*
54011 ** This function is used to copy the contents of the b-tree node stored
54012 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
54013 ** the pointer-map entries for each child page are updated so that the
54014 ** parent page stored in the pointer map is page pTo. If pFrom contained
54015 ** any cells with overflow page pointers, then the corresponding pointer
54016 ** map entries are also updated so that the parent page is page pTo.
54017 **
54018 ** If pFrom is currently carrying any overflow cells (entries in the
54019 ** MemPage.aOvfl[] array), they are not copied to pTo.
54020 **
54021 ** Before returning, page pTo is reinitialized using btreeInitPage().
54022 **
54023 ** The performance of this function is not critical. It is only used by
54024 ** the balance_shallower() and balance_deeper() procedures, neither of
54025 ** which are called often under normal circumstances.
54026 */
54027 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
54028   if( (*pRC)==SQLITE_OK ){
54029     BtShared * const pBt = pFrom->pBt;
54030     u8 * const aFrom = pFrom->aData;
54031     u8 * const aTo = pTo->aData;
54032     int const iFromHdr = pFrom->hdrOffset;
54033     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
54034     int rc;
54035     int iData;
54036 
54037 
54038     assert( pFrom->isInit );
54039     assert( pFrom->nFree>=iToHdr );
54040     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
54041 
54042     /* Copy the b-tree node content from page pFrom to page pTo. */
54043     iData = get2byte(&aFrom[iFromHdr+5]);
54044     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
54045     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
54046 
54047     /* Reinitialize page pTo so that the contents of the MemPage structure
54048     ** match the new data. The initialization of pTo can actually fail under
54049     ** fairly obscure circumstances, even though it is a copy of initialized
54050     ** page pFrom.
54051     */
54052     pTo->isInit = 0;
54053     rc = btreeInitPage(pTo);
54054     if( rc!=SQLITE_OK ){
54055       *pRC = rc;
54056       return;
54057     }
54058 
54059     /* If this is an auto-vacuum database, update the pointer-map entries
54060     ** for any b-tree or overflow pages that pTo now contains the pointers to.
54061     */
54062     if( ISAUTOVACUUM ){
54063       *pRC = setChildPtrmaps(pTo);
54064     }
54065   }
54066 }
54067 
54068 /*
54069 ** This routine redistributes cells on the iParentIdx'th child of pParent
54070 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
54071 ** same amount of free space. Usually a single sibling on either side of the
54072 ** page are used in the balancing, though both siblings might come from one
54073 ** side if the page is the first or last child of its parent. If the page
54074 ** has fewer than 2 siblings (something which can only happen if the page
54075 ** is a root page or a child of a root page) then all available siblings
54076 ** participate in the balancing.
54077 **
54078 ** The number of siblings of the page might be increased or decreased by
54079 ** one or two in an effort to keep pages nearly full but not over full.
54080 **
54081 ** Note that when this routine is called, some of the cells on the page
54082 ** might not actually be stored in MemPage.aData[]. This can happen
54083 ** if the page is overfull. This routine ensures that all cells allocated
54084 ** to the page and its siblings fit into MemPage.aData[] before returning.
54085 **
54086 ** In the course of balancing the page and its siblings, cells may be
54087 ** inserted into or removed from the parent page (pParent). Doing so
54088 ** may cause the parent page to become overfull or underfull. If this
54089 ** happens, it is the responsibility of the caller to invoke the correct
54090 ** balancing routine to fix this problem (see the balance() routine).
54091 **
54092 ** If this routine fails for any reason, it might leave the database
54093 ** in a corrupted state. So if this routine fails, the database should
54094 ** be rolled back.
54095 **
54096 ** The third argument to this function, aOvflSpace, is a pointer to a
54097 ** buffer big enough to hold one page. If while inserting cells into the parent
54098 ** page (pParent) the parent page becomes overfull, this buffer is
54099 ** used to store the parent's overflow cells. Because this function inserts
54100 ** a maximum of four divider cells into the parent page, and the maximum
54101 ** size of a cell stored within an internal node is always less than 1/4
54102 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
54103 ** enough for all overflow cells.
54104 **
54105 ** If aOvflSpace is set to a null pointer, this function returns
54106 ** SQLITE_NOMEM.
54107 */
54108 static int balance_nonroot(
54109   MemPage *pParent,               /* Parent page of siblings being balanced */
54110   int iParentIdx,                 /* Index of "the page" in pParent */
54111   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
54112   int isRoot                      /* True if pParent is a root-page */
54113 ){
54114   BtShared *pBt;               /* The whole database */
54115   int nCell = 0;               /* Number of cells in apCell[] */
54116   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
54117   int nNew = 0;                /* Number of pages in apNew[] */
54118   int nOld;                    /* Number of pages in apOld[] */
54119   int i, j, k;                 /* Loop counters */
54120   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
54121   int rc = SQLITE_OK;          /* The return code */
54122   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
54123   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
54124   int usableSpace;             /* Bytes in pPage beyond the header */
54125   int pageFlags;               /* Value of pPage->aData[0] */
54126   int subtotal;                /* Subtotal of bytes in cells on one page */
54127   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
54128   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
54129   int szScratch;               /* Size of scratch memory requested */
54130   MemPage *apOld[NB];          /* pPage and up to two siblings */
54131   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
54132   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
54133   u8 *pRight;                  /* Location in parent of right-sibling pointer */
54134   u8 *apDiv[NB-1];             /* Divider cells in pParent */
54135   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
54136   int szNew[NB+2];             /* Combined size of cells place on i-th page */
54137   u8 **apCell = 0;             /* All cells begin balanced */
54138   u16 *szCell;                 /* Local size of all cells in apCell[] */
54139   u8 *aSpace1;                 /* Space for copies of dividers cells */
54140   Pgno pgno;                   /* Temp var to store a page number in */
54141 
54142   pBt = pParent->pBt;
54143   assert( sqlite3_mutex_held(pBt->mutex) );
54144   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54145 
54146 #if 0
54147   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
54148 #endif
54149 
54150   /* At this point pParent may have at most one overflow cell. And if
54151   ** this overflow cell is present, it must be the cell with
54152   ** index iParentIdx. This scenario comes about when this function
54153   ** is called (indirectly) from sqlite3BtreeDelete().
54154   */
54155   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
54156   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
54157 
54158   if( !aOvflSpace ){
54159     return SQLITE_NOMEM;
54160   }
54161 
54162   /* Find the sibling pages to balance. Also locate the cells in pParent
54163   ** that divide the siblings. An attempt is made to find NN siblings on
54164   ** either side of pPage. More siblings are taken from one side, however,
54165   ** if there are fewer than NN siblings on the other side. If pParent
54166   ** has NB or fewer children then all children of pParent are taken.
54167   **
54168   ** This loop also drops the divider cells from the parent page. This
54169   ** way, the remainder of the function does not have to deal with any
54170   ** overflow cells in the parent page, since if any existed they will
54171   ** have already been removed.
54172   */
54173   i = pParent->nOverflow + pParent->nCell;
54174   if( i<2 ){
54175     nxDiv = 0;
54176     nOld = i+1;
54177   }else{
54178     nOld = 3;
54179     if( iParentIdx==0 ){
54180       nxDiv = 0;
54181     }else if( iParentIdx==i ){
54182       nxDiv = i-2;
54183     }else{
54184       nxDiv = iParentIdx-1;
54185     }
54186     i = 2;
54187   }
54188   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
54189     pRight = &pParent->aData[pParent->hdrOffset+8];
54190   }else{
54191     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
54192   }
54193   pgno = get4byte(pRight);
54194   while( 1 ){
54195     rc = getAndInitPage(pBt, pgno, &apOld[i]);
54196     if( rc ){
54197       memset(apOld, 0, (i+1)*sizeof(MemPage*));
54198       goto balance_cleanup;
54199     }
54200     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
54201     if( (i--)==0 ) break;
54202 
54203     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
54204       apDiv[i] = pParent->aOvfl[0].pCell;
54205       pgno = get4byte(apDiv[i]);
54206       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54207       pParent->nOverflow = 0;
54208     }else{
54209       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
54210       pgno = get4byte(apDiv[i]);
54211       szNew[i] = cellSizePtr(pParent, apDiv[i]);
54212 
54213       /* Drop the cell from the parent page. apDiv[i] still points to
54214       ** the cell within the parent, even though it has been dropped.
54215       ** This is safe because dropping a cell only overwrites the first
54216       ** four bytes of it, and this function does not need the first
54217       ** four bytes of the divider cell. So the pointer is safe to use
54218       ** later on.
54219       **
54220       ** Unless SQLite is compiled in secure-delete mode. In this case,
54221       ** the dropCell() routine will overwrite the entire cell with zeroes.
54222       ** In this case, temporarily copy the cell into the aOvflSpace[]
54223       ** buffer. It will be copied out again as soon as the aSpace[] buffer
54224       ** is allocated.  */
54225       if( pBt->secureDelete ){
54226         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
54227         if( (iOff+szNew[i])>(int)pBt->usableSize ){
54228           rc = SQLITE_CORRUPT_BKPT;
54229           memset(apOld, 0, (i+1)*sizeof(MemPage*));
54230           goto balance_cleanup;
54231         }else{
54232           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
54233           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
54234         }
54235       }
54236       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
54237     }
54238   }
54239 
54240   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
54241   ** alignment */
54242   nMaxCells = (nMaxCells + 3)&~3;
54243 
54244   /*
54245   ** Allocate space for memory structures
54246   */
54247   k = pBt->pageSize + ROUND8(sizeof(MemPage));
54248   szScratch =
54249        nMaxCells*sizeof(u8*)                       /* apCell */
54250      + nMaxCells*sizeof(u16)                       /* szCell */
54251      + pBt->pageSize                               /* aSpace1 */
54252      + k*nOld;                                     /* Page copies (apCopy) */
54253   apCell = sqlite3ScratchMalloc( szScratch );
54254   if( apCell==0 ){
54255     rc = SQLITE_NOMEM;
54256     goto balance_cleanup;
54257   }
54258   szCell = (u16*)&apCell[nMaxCells];
54259   aSpace1 = (u8*)&szCell[nMaxCells];
54260   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
54261 
54262   /*
54263   ** Load pointers to all cells on sibling pages and the divider cells
54264   ** into the local apCell[] array.  Make copies of the divider cells
54265   ** into space obtained from aSpace1[] and remove the the divider Cells
54266   ** from pParent.
54267   **
54268   ** If the siblings are on leaf pages, then the child pointers of the
54269   ** divider cells are stripped from the cells before they are copied
54270   ** into aSpace1[].  In this way, all cells in apCell[] are without
54271   ** child pointers.  If siblings are not leaves, then all cell in
54272   ** apCell[] include child pointers.  Either way, all cells in apCell[]
54273   ** are alike.
54274   **
54275   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
54276   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
54277   */
54278   leafCorrection = apOld[0]->leaf*4;
54279   leafData = apOld[0]->hasData;
54280   for(i=0; i<nOld; i++){
54281     int limit;
54282 
54283     /* Before doing anything else, take a copy of the i'th original sibling
54284     ** The rest of this function will use data from the copies rather
54285     ** that the original pages since the original pages will be in the
54286     ** process of being overwritten.  */
54287     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
54288     memcpy(pOld, apOld[i], sizeof(MemPage));
54289     pOld->aData = (void*)&pOld[1];
54290     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
54291 
54292     limit = pOld->nCell+pOld->nOverflow;
54293     if( pOld->nOverflow>0 ){
54294       for(j=0; j<limit; j++){
54295         assert( nCell<nMaxCells );
54296         apCell[nCell] = findOverflowCell(pOld, j);
54297         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54298         nCell++;
54299       }
54300     }else{
54301       u8 *aData = pOld->aData;
54302       u16 maskPage = pOld->maskPage;
54303       u16 cellOffset = pOld->cellOffset;
54304       for(j=0; j<limit; j++){
54305         assert( nCell<nMaxCells );
54306         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
54307         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
54308         nCell++;
54309       }
54310     }
54311     if( i<nOld-1 && !leafData){
54312       u16 sz = (u16)szNew[i];
54313       u8 *pTemp;
54314       assert( nCell<nMaxCells );
54315       szCell[nCell] = sz;
54316       pTemp = &aSpace1[iSpace1];
54317       iSpace1 += sz;
54318       assert( sz<=pBt->maxLocal+23 );
54319       assert( iSpace1 <= (int)pBt->pageSize );
54320       memcpy(pTemp, apDiv[i], sz);
54321       apCell[nCell] = pTemp+leafCorrection;
54322       assert( leafCorrection==0 || leafCorrection==4 );
54323       szCell[nCell] = szCell[nCell] - leafCorrection;
54324       if( !pOld->leaf ){
54325         assert( leafCorrection==0 );
54326         assert( pOld->hdrOffset==0 );
54327         /* The right pointer of the child page pOld becomes the left
54328         ** pointer of the divider cell */
54329         memcpy(apCell[nCell], &pOld->aData[8], 4);
54330       }else{
54331         assert( leafCorrection==4 );
54332         if( szCell[nCell]<4 ){
54333           /* Do not allow any cells smaller than 4 bytes. */
54334           szCell[nCell] = 4;
54335         }
54336       }
54337       nCell++;
54338     }
54339   }
54340 
54341   /*
54342   ** Figure out the number of pages needed to hold all nCell cells.
54343   ** Store this number in "k".  Also compute szNew[] which is the total
54344   ** size of all cells on the i-th page and cntNew[] which is the index
54345   ** in apCell[] of the cell that divides page i from page i+1.
54346   ** cntNew[k] should equal nCell.
54347   **
54348   ** Values computed by this block:
54349   **
54350   **           k: The total number of sibling pages
54351   **    szNew[i]: Spaced used on the i-th sibling page.
54352   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
54353   **              the right of the i-th sibling page.
54354   ** usableSpace: Number of bytes of space available on each sibling.
54355   **
54356   */
54357   usableSpace = pBt->usableSize - 12 + leafCorrection;
54358   for(subtotal=k=i=0; i<nCell; i++){
54359     assert( i<nMaxCells );
54360     subtotal += szCell[i] + 2;
54361     if( subtotal > usableSpace ){
54362       szNew[k] = subtotal - szCell[i];
54363       cntNew[k] = i;
54364       if( leafData ){ i--; }
54365       subtotal = 0;
54366       k++;
54367       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
54368     }
54369   }
54370   szNew[k] = subtotal;
54371   cntNew[k] = nCell;
54372   k++;
54373 
54374   /*
54375   ** The packing computed by the previous block is biased toward the siblings
54376   ** on the left side.  The left siblings are always nearly full, while the
54377   ** right-most sibling might be nearly empty.  This block of code attempts
54378   ** to adjust the packing of siblings to get a better balance.
54379   **
54380   ** This adjustment is more than an optimization.  The packing above might
54381   ** be so out of balance as to be illegal.  For example, the right-most
54382   ** sibling might be completely empty.  This adjustment is not optional.
54383   */
54384   for(i=k-1; i>0; i--){
54385     int szRight = szNew[i];  /* Size of sibling on the right */
54386     int szLeft = szNew[i-1]; /* Size of sibling on the left */
54387     int r;              /* Index of right-most cell in left sibling */
54388     int d;              /* Index of first cell to the left of right sibling */
54389 
54390     r = cntNew[i-1] - 1;
54391     d = r + 1 - leafData;
54392     assert( d<nMaxCells );
54393     assert( r<nMaxCells );
54394     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
54395       szRight += szCell[d] + 2;
54396       szLeft -= szCell[r] + 2;
54397       cntNew[i-1]--;
54398       r = cntNew[i-1] - 1;
54399       d = r + 1 - leafData;
54400     }
54401     szNew[i] = szRight;
54402     szNew[i-1] = szLeft;
54403   }
54404 
54405   /* Either we found one or more cells (cntnew[0])>0) or pPage is
54406   ** a virtual root page.  A virtual root page is when the real root
54407   ** page is page 1 and we are the only child of that page.
54408   */
54409   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
54410 
54411   TRACE(("BALANCE: old: %d %d %d  ",
54412     apOld[0]->pgno,
54413     nOld>=2 ? apOld[1]->pgno : 0,
54414     nOld>=3 ? apOld[2]->pgno : 0
54415   ));
54416 
54417   /*
54418   ** Allocate k new pages.  Reuse old pages where possible.
54419   */
54420   if( apOld[0]->pgno<=1 ){
54421     rc = SQLITE_CORRUPT_BKPT;
54422     goto balance_cleanup;
54423   }
54424   pageFlags = apOld[0]->aData[0];
54425   for(i=0; i<k; i++){
54426     MemPage *pNew;
54427     if( i<nOld ){
54428       pNew = apNew[i] = apOld[i];
54429       apOld[i] = 0;
54430       rc = sqlite3PagerWrite(pNew->pDbPage);
54431       nNew++;
54432       if( rc ) goto balance_cleanup;
54433     }else{
54434       assert( i>0 );
54435       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
54436       if( rc ) goto balance_cleanup;
54437       apNew[i] = pNew;
54438       nNew++;
54439 
54440       /* Set the pointer-map entry for the new sibling page. */
54441       if( ISAUTOVACUUM ){
54442         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
54443         if( rc!=SQLITE_OK ){
54444           goto balance_cleanup;
54445         }
54446       }
54447     }
54448   }
54449 
54450   /* Free any old pages that were not reused as new pages.
54451   */
54452   while( i<nOld ){
54453     freePage(apOld[i], &rc);
54454     if( rc ) goto balance_cleanup;
54455     releasePage(apOld[i]);
54456     apOld[i] = 0;
54457     i++;
54458   }
54459 
54460   /*
54461   ** Put the new pages in accending order.  This helps to
54462   ** keep entries in the disk file in order so that a scan
54463   ** of the table is a linear scan through the file.  That
54464   ** in turn helps the operating system to deliver pages
54465   ** from the disk more rapidly.
54466   **
54467   ** An O(n^2) insertion sort algorithm is used, but since
54468   ** n is never more than NB (a small constant), that should
54469   ** not be a problem.
54470   **
54471   ** When NB==3, this one optimization makes the database
54472   ** about 25% faster for large insertions and deletions.
54473   */
54474   for(i=0; i<k-1; i++){
54475     int minV = apNew[i]->pgno;
54476     int minI = i;
54477     for(j=i+1; j<k; j++){
54478       if( apNew[j]->pgno<(unsigned)minV ){
54479         minI = j;
54480         minV = apNew[j]->pgno;
54481       }
54482     }
54483     if( minI>i ){
54484       MemPage *pT;
54485       pT = apNew[i];
54486       apNew[i] = apNew[minI];
54487       apNew[minI] = pT;
54488     }
54489   }
54490   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
54491     apNew[0]->pgno, szNew[0],
54492     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
54493     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
54494     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
54495     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
54496 
54497   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54498   put4byte(pRight, apNew[nNew-1]->pgno);
54499 
54500   /*
54501   ** Evenly distribute the data in apCell[] across the new pages.
54502   ** Insert divider cells into pParent as necessary.
54503   */
54504   j = 0;
54505   for(i=0; i<nNew; i++){
54506     /* Assemble the new sibling page. */
54507     MemPage *pNew = apNew[i];
54508     assert( j<nMaxCells );
54509     zeroPage(pNew, pageFlags);
54510     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
54511     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
54512     assert( pNew->nOverflow==0 );
54513 
54514     j = cntNew[i];
54515 
54516     /* If the sibling page assembled above was not the right-most sibling,
54517     ** insert a divider cell into the parent page.
54518     */
54519     assert( i<nNew-1 || j==nCell );
54520     if( j<nCell ){
54521       u8 *pCell;
54522       u8 *pTemp;
54523       int sz;
54524 
54525       assert( j<nMaxCells );
54526       pCell = apCell[j];
54527       sz = szCell[j] + leafCorrection;
54528       pTemp = &aOvflSpace[iOvflSpace];
54529       if( !pNew->leaf ){
54530         memcpy(&pNew->aData[8], pCell, 4);
54531       }else if( leafData ){
54532         /* If the tree is a leaf-data tree, and the siblings are leaves,
54533         ** then there is no divider cell in apCell[]. Instead, the divider
54534         ** cell consists of the integer key for the right-most cell of
54535         ** the sibling-page assembled above only.
54536         */
54537         CellInfo info;
54538         j--;
54539         btreeParseCellPtr(pNew, apCell[j], &info);
54540         pCell = pTemp;
54541         sz = 4 + putVarint(&pCell[4], info.nKey);
54542         pTemp = 0;
54543       }else{
54544         pCell -= 4;
54545         /* Obscure case for non-leaf-data trees: If the cell at pCell was
54546         ** previously stored on a leaf node, and its reported size was 4
54547         ** bytes, then it may actually be smaller than this
54548         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
54549         ** any cell). But it is important to pass the correct size to
54550         ** insertCell(), so reparse the cell now.
54551         **
54552         ** Note that this can never happen in an SQLite data file, as all
54553         ** cells are at least 4 bytes. It only happens in b-trees used
54554         ** to evaluate "IN (SELECT ...)" and similar clauses.
54555         */
54556         if( szCell[j]==4 ){
54557           assert(leafCorrection==4);
54558           sz = cellSizePtr(pParent, pCell);
54559         }
54560       }
54561       iOvflSpace += sz;
54562       assert( sz<=pBt->maxLocal+23 );
54563       assert( iOvflSpace <= (int)pBt->pageSize );
54564       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
54565       if( rc!=SQLITE_OK ) goto balance_cleanup;
54566       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
54567 
54568       j++;
54569       nxDiv++;
54570     }
54571   }
54572   assert( j==nCell );
54573   assert( nOld>0 );
54574   assert( nNew>0 );
54575   if( (pageFlags & PTF_LEAF)==0 ){
54576     u8 *zChild = &apCopy[nOld-1]->aData[8];
54577     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
54578   }
54579 
54580   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
54581     /* The root page of the b-tree now contains no cells. The only sibling
54582     ** page is the right-child of the parent. Copy the contents of the
54583     ** child page into the parent, decreasing the overall height of the
54584     ** b-tree structure by one. This is described as the "balance-shallower"
54585     ** sub-algorithm in some documentation.
54586     **
54587     ** If this is an auto-vacuum database, the call to copyNodeContent()
54588     ** sets all pointer-map entries corresponding to database image pages
54589     ** for which the pointer is stored within the content being copied.
54590     **
54591     ** The second assert below verifies that the child page is defragmented
54592     ** (it must be, as it was just reconstructed using assemblePage()). This
54593     ** is important if the parent page happens to be page 1 of the database
54594     ** image.  */
54595     assert( nNew==1 );
54596     assert( apNew[0]->nFree ==
54597         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
54598     );
54599     copyNodeContent(apNew[0], pParent, &rc);
54600     freePage(apNew[0], &rc);
54601   }else if( ISAUTOVACUUM ){
54602     /* Fix the pointer-map entries for all the cells that were shifted around.
54603     ** There are several different types of pointer-map entries that need to
54604     ** be dealt with by this routine. Some of these have been set already, but
54605     ** many have not. The following is a summary:
54606     **
54607     **   1) The entries associated with new sibling pages that were not
54608     **      siblings when this function was called. These have already
54609     **      been set. We don't need to worry about old siblings that were
54610     **      moved to the free-list - the freePage() code has taken care
54611     **      of those.
54612     **
54613     **   2) The pointer-map entries associated with the first overflow
54614     **      page in any overflow chains used by new divider cells. These
54615     **      have also already been taken care of by the insertCell() code.
54616     **
54617     **   3) If the sibling pages are not leaves, then the child pages of
54618     **      cells stored on the sibling pages may need to be updated.
54619     **
54620     **   4) If the sibling pages are not internal intkey nodes, then any
54621     **      overflow pages used by these cells may need to be updated
54622     **      (internal intkey nodes never contain pointers to overflow pages).
54623     **
54624     **   5) If the sibling pages are not leaves, then the pointer-map
54625     **      entries for the right-child pages of each sibling may need
54626     **      to be updated.
54627     **
54628     ** Cases 1 and 2 are dealt with above by other code. The next
54629     ** block deals with cases 3 and 4 and the one after that, case 5. Since
54630     ** setting a pointer map entry is a relatively expensive operation, this
54631     ** code only sets pointer map entries for child or overflow pages that have
54632     ** actually moved between pages.  */
54633     MemPage *pNew = apNew[0];
54634     MemPage *pOld = apCopy[0];
54635     int nOverflow = pOld->nOverflow;
54636     int iNextOld = pOld->nCell + nOverflow;
54637     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
54638     j = 0;                             /* Current 'old' sibling page */
54639     k = 0;                             /* Current 'new' sibling page */
54640     for(i=0; i<nCell; i++){
54641       int isDivider = 0;
54642       while( i==iNextOld ){
54643         /* Cell i is the cell immediately following the last cell on old
54644         ** sibling page j. If the siblings are not leaf pages of an
54645         ** intkey b-tree, then cell i was a divider cell. */
54646         pOld = apCopy[++j];
54647         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
54648         if( pOld->nOverflow ){
54649           nOverflow = pOld->nOverflow;
54650           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
54651         }
54652         isDivider = !leafData;
54653       }
54654 
54655       assert(nOverflow>0 || iOverflow<i );
54656       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
54657       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
54658       if( i==iOverflow ){
54659         isDivider = 1;
54660         if( (--nOverflow)>0 ){
54661           iOverflow++;
54662         }
54663       }
54664 
54665       if( i==cntNew[k] ){
54666         /* Cell i is the cell immediately following the last cell on new
54667         ** sibling page k. If the siblings are not leaf pages of an
54668         ** intkey b-tree, then cell i is a divider cell.  */
54669         pNew = apNew[++k];
54670         if( !leafData ) continue;
54671       }
54672       assert( j<nOld );
54673       assert( k<nNew );
54674 
54675       /* If the cell was originally divider cell (and is not now) or
54676       ** an overflow cell, or if the cell was located on a different sibling
54677       ** page before the balancing, then the pointer map entries associated
54678       ** with any child or overflow pages need to be updated.  */
54679       if( isDivider || pOld->pgno!=pNew->pgno ){
54680         if( !leafCorrection ){
54681           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
54682         }
54683         if( szCell[i]>pNew->minLocal ){
54684           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
54685         }
54686       }
54687     }
54688 
54689     if( !leafCorrection ){
54690       for(i=0; i<nNew; i++){
54691         u32 key = get4byte(&apNew[i]->aData[8]);
54692         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
54693       }
54694     }
54695 
54696 #if 0
54697     /* The ptrmapCheckPages() contains assert() statements that verify that
54698     ** all pointer map pages are set correctly. This is helpful while
54699     ** debugging. This is usually disabled because a corrupt database may
54700     ** cause an assert() statement to fail.  */
54701     ptrmapCheckPages(apNew, nNew);
54702     ptrmapCheckPages(&pParent, 1);
54703 #endif
54704   }
54705 
54706   assert( pParent->isInit );
54707   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
54708           nOld, nNew, nCell));
54709 
54710   /*
54711   ** Cleanup before returning.
54712   */
54713 balance_cleanup:
54714   sqlite3ScratchFree(apCell);
54715   for(i=0; i<nOld; i++){
54716     releasePage(apOld[i]);
54717   }
54718   for(i=0; i<nNew; i++){
54719     releasePage(apNew[i]);
54720   }
54721 
54722   return rc;
54723 }
54724 
54725 
54726 /*
54727 ** This function is called when the root page of a b-tree structure is
54728 ** overfull (has one or more overflow pages).
54729 **
54730 ** A new child page is allocated and the contents of the current root
54731 ** page, including overflow cells, are copied into the child. The root
54732 ** page is then overwritten to make it an empty page with the right-child
54733 ** pointer pointing to the new page.
54734 **
54735 ** Before returning, all pointer-map entries corresponding to pages
54736 ** that the new child-page now contains pointers to are updated. The
54737 ** entry corresponding to the new right-child pointer of the root
54738 ** page is also updated.
54739 **
54740 ** If successful, *ppChild is set to contain a reference to the child
54741 ** page and SQLITE_OK is returned. In this case the caller is required
54742 ** to call releasePage() on *ppChild exactly once. If an error occurs,
54743 ** an error code is returned and *ppChild is set to 0.
54744 */
54745 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
54746   int rc;                        /* Return value from subprocedures */
54747   MemPage *pChild = 0;           /* Pointer to a new child page */
54748   Pgno pgnoChild = 0;            /* Page number of the new child page */
54749   BtShared *pBt = pRoot->pBt;    /* The BTree */
54750 
54751   assert( pRoot->nOverflow>0 );
54752   assert( sqlite3_mutex_held(pBt->mutex) );
54753 
54754   /* Make pRoot, the root page of the b-tree, writable. Allocate a new
54755   ** page that will become the new right-child of pPage. Copy the contents
54756   ** of the node stored on pRoot into the new child page.
54757   */
54758   rc = sqlite3PagerWrite(pRoot->pDbPage);
54759   if( rc==SQLITE_OK ){
54760     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
54761     copyNodeContent(pRoot, pChild, &rc);
54762     if( ISAUTOVACUUM ){
54763       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
54764     }
54765   }
54766   if( rc ){
54767     *ppChild = 0;
54768     releasePage(pChild);
54769     return rc;
54770   }
54771   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
54772   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
54773   assert( pChild->nCell==pRoot->nCell );
54774 
54775   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
54776 
54777   /* Copy the overflow cells from pRoot to pChild */
54778   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
54779   pChild->nOverflow = pRoot->nOverflow;
54780 
54781   /* Zero the contents of pRoot. Then install pChild as the right-child. */
54782   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
54783   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
54784 
54785   *ppChild = pChild;
54786   return SQLITE_OK;
54787 }
54788 
54789 /*
54790 ** The page that pCur currently points to has just been modified in
54791 ** some way. This function figures out if this modification means the
54792 ** tree needs to be balanced, and if so calls the appropriate balancing
54793 ** routine. Balancing routines are:
54794 **
54795 **   balance_quick()
54796 **   balance_deeper()
54797 **   balance_nonroot()
54798 */
54799 static int balance(BtCursor *pCur){
54800   int rc = SQLITE_OK;
54801   const int nMin = pCur->pBt->usableSize * 2 / 3;
54802   u8 aBalanceQuickSpace[13];
54803   u8 *pFree = 0;
54804 
54805   TESTONLY( int balance_quick_called = 0 );
54806   TESTONLY( int balance_deeper_called = 0 );
54807 
54808   do {
54809     int iPage = pCur->iPage;
54810     MemPage *pPage = pCur->apPage[iPage];
54811 
54812     if( iPage==0 ){
54813       if( pPage->nOverflow ){
54814         /* The root page of the b-tree is overfull. In this case call the
54815         ** balance_deeper() function to create a new child for the root-page
54816         ** and copy the current contents of the root-page to it. The
54817         ** next iteration of the do-loop will balance the child page.
54818         */
54819         assert( (balance_deeper_called++)==0 );
54820         rc = balance_deeper(pPage, &pCur->apPage[1]);
54821         if( rc==SQLITE_OK ){
54822           pCur->iPage = 1;
54823           pCur->aiIdx[0] = 0;
54824           pCur->aiIdx[1] = 0;
54825           assert( pCur->apPage[1]->nOverflow );
54826         }
54827       }else{
54828         break;
54829       }
54830     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
54831       break;
54832     }else{
54833       MemPage * const pParent = pCur->apPage[iPage-1];
54834       int const iIdx = pCur->aiIdx[iPage-1];
54835 
54836       rc = sqlite3PagerWrite(pParent->pDbPage);
54837       if( rc==SQLITE_OK ){
54838 #ifndef SQLITE_OMIT_QUICKBALANCE
54839         if( pPage->hasData
54840          && pPage->nOverflow==1
54841          && pPage->aOvfl[0].idx==pPage->nCell
54842          && pParent->pgno!=1
54843          && pParent->nCell==iIdx
54844         ){
54845           /* Call balance_quick() to create a new sibling of pPage on which
54846           ** to store the overflow cell. balance_quick() inserts a new cell
54847           ** into pParent, which may cause pParent overflow. If this
54848           ** happens, the next interation of the do-loop will balance pParent
54849           ** use either balance_nonroot() or balance_deeper(). Until this
54850           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
54851           ** buffer.
54852           **
54853           ** The purpose of the following assert() is to check that only a
54854           ** single call to balance_quick() is made for each call to this
54855           ** function. If this were not verified, a subtle bug involving reuse
54856           ** of the aBalanceQuickSpace[] might sneak in.
54857           */
54858           assert( (balance_quick_called++)==0 );
54859           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
54860         }else
54861 #endif
54862         {
54863           /* In this case, call balance_nonroot() to redistribute cells
54864           ** between pPage and up to 2 of its sibling pages. This involves
54865           ** modifying the contents of pParent, which may cause pParent to
54866           ** become overfull or underfull. The next iteration of the do-loop
54867           ** will balance the parent page to correct this.
54868           **
54869           ** If the parent page becomes overfull, the overflow cell or cells
54870           ** are stored in the pSpace buffer allocated immediately below.
54871           ** A subsequent iteration of the do-loop will deal with this by
54872           ** calling balance_nonroot() (balance_deeper() may be called first,
54873           ** but it doesn't deal with overflow cells - just moves them to a
54874           ** different page). Once this subsequent call to balance_nonroot()
54875           ** has completed, it is safe to release the pSpace buffer used by
54876           ** the previous call, as the overflow cell data will have been
54877           ** copied either into the body of a database page or into the new
54878           ** pSpace buffer passed to the latter call to balance_nonroot().
54879           */
54880           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
54881           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
54882           if( pFree ){
54883             /* If pFree is not NULL, it points to the pSpace buffer used
54884             ** by a previous call to balance_nonroot(). Its contents are
54885             ** now stored either on real database pages or within the
54886             ** new pSpace buffer, so it may be safely freed here. */
54887             sqlite3PageFree(pFree);
54888           }
54889 
54890           /* The pSpace buffer will be freed after the next call to
54891           ** balance_nonroot(), or just before this function returns, whichever
54892           ** comes first. */
54893           pFree = pSpace;
54894         }
54895       }
54896 
54897       pPage->nOverflow = 0;
54898 
54899       /* The next iteration of the do-loop balances the parent page. */
54900       releasePage(pPage);
54901       pCur->iPage--;
54902     }
54903   }while( rc==SQLITE_OK );
54904 
54905   if( pFree ){
54906     sqlite3PageFree(pFree);
54907   }
54908   return rc;
54909 }
54910 
54911 
54912 /*
54913 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
54914 ** and the data is given by (pData,nData).  The cursor is used only to
54915 ** define what table the record should be inserted into.  The cursor
54916 ** is left pointing at a random location.
54917 **
54918 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
54919 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
54920 **
54921 ** If the seekResult parameter is non-zero, then a successful call to
54922 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
54923 ** been performed. seekResult is the search result returned (a negative
54924 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
54925 ** a positive value if pCur points at an etry that is larger than
54926 ** (pKey, nKey)).
54927 **
54928 ** If the seekResult parameter is non-zero, then the caller guarantees that
54929 ** cursor pCur is pointing at the existing copy of a row that is to be
54930 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
54931 ** point to any entry or to no entry at all and so this function has to seek
54932 ** the cursor before the new key can be inserted.
54933 */
54934 SQLITE_PRIVATE int sqlite3BtreeInsert(
54935   BtCursor *pCur,                /* Insert data into the table of this cursor */
54936   const void *pKey, i64 nKey,    /* The key of the new record */
54937   const void *pData, int nData,  /* The data of the new record */
54938   int nZero,                     /* Number of extra 0 bytes to append to data */
54939   int appendBias,                /* True if this is likely an append */
54940   int seekResult                 /* Result of prior MovetoUnpacked() call */
54941 ){
54942   int rc;
54943   int loc = seekResult;          /* -1: before desired location  +1: after */
54944   int szNew = 0;
54945   int idx;
54946   MemPage *pPage;
54947   Btree *p = pCur->pBtree;
54948   BtShared *pBt = p->pBt;
54949   unsigned char *oldCell;
54950   unsigned char *newCell = 0;
54951 
54952   if( pCur->eState==CURSOR_FAULT ){
54953     assert( pCur->skipNext!=SQLITE_OK );
54954     return pCur->skipNext;
54955   }
54956 
54957   assert( cursorHoldsMutex(pCur) );
54958   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
54959   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
54960 
54961   /* Assert that the caller has been consistent. If this cursor was opened
54962   ** expecting an index b-tree, then the caller should be inserting blob
54963   ** keys with no associated data. If the cursor was opened expecting an
54964   ** intkey table, the caller should be inserting integer keys with a
54965   ** blob of associated data.  */
54966   assert( (pKey==0)==(pCur->pKeyInfo==0) );
54967 
54968   /* If this is an insert into a table b-tree, invalidate any incrblob
54969   ** cursors open on the row being replaced (assuming this is a replace
54970   ** operation - if it is not, the following is a no-op).  */
54971   if( pCur->pKeyInfo==0 ){
54972     invalidateIncrblobCursors(p, nKey, 0);
54973   }
54974 
54975   /* Save the positions of any other cursors open on this table.
54976   **
54977   ** In some cases, the call to btreeMoveto() below is a no-op. For
54978   ** example, when inserting data into a table with auto-generated integer
54979   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
54980   ** integer key to use. It then calls this function to actually insert the
54981   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
54982   ** that the cursor is already where it needs to be and returns without
54983   ** doing any work. To avoid thwarting these optimizations, it is important
54984   ** not to clear the cursor here.
54985   */
54986   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
54987   if( rc ) return rc;
54988   if( !loc ){
54989     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
54990     if( rc ) return rc;
54991   }
54992   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
54993 
54994   pPage = pCur->apPage[pCur->iPage];
54995   assert( pPage->intKey || nKey>=0 );
54996   assert( pPage->leaf || !pPage->intKey );
54997 
54998   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
54999           pCur->pgnoRoot, nKey, nData, pPage->pgno,
55000           loc==0 ? "overwrite" : "new entry"));
55001   assert( pPage->isInit );
55002   allocateTempSpace(pBt);
55003   newCell = pBt->pTmpSpace;
55004   if( newCell==0 ) return SQLITE_NOMEM;
55005   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
55006   if( rc ) goto end_insert;
55007   assert( szNew==cellSizePtr(pPage, newCell) );
55008   assert( szNew <= MX_CELL_SIZE(pBt) );
55009   idx = pCur->aiIdx[pCur->iPage];
55010   if( loc==0 ){
55011     u16 szOld;
55012     assert( idx<pPage->nCell );
55013     rc = sqlite3PagerWrite(pPage->pDbPage);
55014     if( rc ){
55015       goto end_insert;
55016     }
55017     oldCell = findCell(pPage, idx);
55018     if( !pPage->leaf ){
55019       memcpy(newCell, oldCell, 4);
55020     }
55021     szOld = cellSizePtr(pPage, oldCell);
55022     rc = clearCell(pPage, oldCell);
55023     dropCell(pPage, idx, szOld, &rc);
55024     if( rc ) goto end_insert;
55025   }else if( loc<0 && pPage->nCell>0 ){
55026     assert( pPage->leaf );
55027     idx = ++pCur->aiIdx[pCur->iPage];
55028   }else{
55029     assert( pPage->leaf );
55030   }
55031   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
55032   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
55033 
55034   /* If no error has occured and pPage has an overflow cell, call balance()
55035   ** to redistribute the cells within the tree. Since balance() may move
55036   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
55037   ** variables.
55038   **
55039   ** Previous versions of SQLite called moveToRoot() to move the cursor
55040   ** back to the root page as balance() used to invalidate the contents
55041   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
55042   ** set the cursor state to "invalid". This makes common insert operations
55043   ** slightly faster.
55044   **
55045   ** There is a subtle but important optimization here too. When inserting
55046   ** multiple records into an intkey b-tree using a single cursor (as can
55047   ** happen while processing an "INSERT INTO ... SELECT" statement), it
55048   ** is advantageous to leave the cursor pointing to the last entry in
55049   ** the b-tree if possible. If the cursor is left pointing to the last
55050   ** entry in the table, and the next row inserted has an integer key
55051   ** larger than the largest existing key, it is possible to insert the
55052   ** row without seeking the cursor. This can be a big performance boost.
55053   */
55054   pCur->info.nSize = 0;
55055   pCur->validNKey = 0;
55056   if( rc==SQLITE_OK && pPage->nOverflow ){
55057     rc = balance(pCur);
55058 
55059     /* Must make sure nOverflow is reset to zero even if the balance()
55060     ** fails. Internal data structure corruption will result otherwise.
55061     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
55062     ** from trying to save the current position of the cursor.  */
55063     pCur->apPage[pCur->iPage]->nOverflow = 0;
55064     pCur->eState = CURSOR_INVALID;
55065   }
55066   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
55067 
55068 end_insert:
55069   return rc;
55070 }
55071 
55072 /*
55073 ** Delete the entry that the cursor is pointing to.  The cursor
55074 ** is left pointing at a arbitrary location.
55075 */
55076 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
55077   Btree *p = pCur->pBtree;
55078   BtShared *pBt = p->pBt;
55079   int rc;                              /* Return code */
55080   MemPage *pPage;                      /* Page to delete cell from */
55081   unsigned char *pCell;                /* Pointer to cell to delete */
55082   int iCellIdx;                        /* Index of cell to delete */
55083   int iCellDepth;                      /* Depth of node containing pCell */
55084 
55085   assert( cursorHoldsMutex(pCur) );
55086   assert( pBt->inTransaction==TRANS_WRITE );
55087   assert( !pBt->readOnly );
55088   assert( pCur->wrFlag );
55089   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
55090   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
55091 
55092   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
55093    || NEVER(pCur->eState!=CURSOR_VALID)
55094   ){
55095     return SQLITE_ERROR;  /* Something has gone awry. */
55096   }
55097 
55098   /* If this is a delete operation to remove a row from a table b-tree,
55099   ** invalidate any incrblob cursors open on the row being deleted.  */
55100   if( pCur->pKeyInfo==0 ){
55101     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
55102   }
55103 
55104   iCellDepth = pCur->iPage;
55105   iCellIdx = pCur->aiIdx[iCellDepth];
55106   pPage = pCur->apPage[iCellDepth];
55107   pCell = findCell(pPage, iCellIdx);
55108 
55109   /* If the page containing the entry to delete is not a leaf page, move
55110   ** the cursor to the largest entry in the tree that is smaller than
55111   ** the entry being deleted. This cell will replace the cell being deleted
55112   ** from the internal node. The 'previous' entry is used for this instead
55113   ** of the 'next' entry, as the previous entry is always a part of the
55114   ** sub-tree headed by the child page of the cell being deleted. This makes
55115   ** balancing the tree following the delete operation easier.  */
55116   if( !pPage->leaf ){
55117     int notUsed;
55118     rc = sqlite3BtreePrevious(pCur, &notUsed);
55119     if( rc ) return rc;
55120   }
55121 
55122   /* Save the positions of any other cursors open on this table before
55123   ** making any modifications. Make the page containing the entry to be
55124   ** deleted writable. Then free any overflow pages associated with the
55125   ** entry and finally remove the cell itself from within the page.
55126   */
55127   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
55128   if( rc ) return rc;
55129   rc = sqlite3PagerWrite(pPage->pDbPage);
55130   if( rc ) return rc;
55131   rc = clearCell(pPage, pCell);
55132   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
55133   if( rc ) return rc;
55134 
55135   /* If the cell deleted was not located on a leaf page, then the cursor
55136   ** is currently pointing to the largest entry in the sub-tree headed
55137   ** by the child-page of the cell that was just deleted from an internal
55138   ** node. The cell from the leaf node needs to be moved to the internal
55139   ** node to replace the deleted cell.  */
55140   if( !pPage->leaf ){
55141     MemPage *pLeaf = pCur->apPage[pCur->iPage];
55142     int nCell;
55143     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
55144     unsigned char *pTmp;
55145 
55146     pCell = findCell(pLeaf, pLeaf->nCell-1);
55147     nCell = cellSizePtr(pLeaf, pCell);
55148     assert( MX_CELL_SIZE(pBt) >= nCell );
55149 
55150     allocateTempSpace(pBt);
55151     pTmp = pBt->pTmpSpace;
55152 
55153     rc = sqlite3PagerWrite(pLeaf->pDbPage);
55154     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
55155     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
55156     if( rc ) return rc;
55157   }
55158 
55159   /* Balance the tree. If the entry deleted was located on a leaf page,
55160   ** then the cursor still points to that page. In this case the first
55161   ** call to balance() repairs the tree, and the if(...) condition is
55162   ** never true.
55163   **
55164   ** Otherwise, if the entry deleted was on an internal node page, then
55165   ** pCur is pointing to the leaf page from which a cell was removed to
55166   ** replace the cell deleted from the internal node. This is slightly
55167   ** tricky as the leaf node may be underfull, and the internal node may
55168   ** be either under or overfull. In this case run the balancing algorithm
55169   ** on the leaf node first. If the balance proceeds far enough up the
55170   ** tree that we can be sure that any problem in the internal node has
55171   ** been corrected, so be it. Otherwise, after balancing the leaf node,
55172   ** walk the cursor up the tree to the internal node and balance it as
55173   ** well.  */
55174   rc = balance(pCur);
55175   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
55176     while( pCur->iPage>iCellDepth ){
55177       releasePage(pCur->apPage[pCur->iPage--]);
55178     }
55179     rc = balance(pCur);
55180   }
55181 
55182   if( rc==SQLITE_OK ){
55183     moveToRoot(pCur);
55184   }
55185   return rc;
55186 }
55187 
55188 /*
55189 ** Create a new BTree table.  Write into *piTable the page
55190 ** number for the root page of the new table.
55191 **
55192 ** The type of type is determined by the flags parameter.  Only the
55193 ** following values of flags are currently in use.  Other values for
55194 ** flags might not work:
55195 **
55196 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
55197 **     BTREE_ZERODATA                  Used for SQL indices
55198 */
55199 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
55200   BtShared *pBt = p->pBt;
55201   MemPage *pRoot;
55202   Pgno pgnoRoot;
55203   int rc;
55204   int ptfFlags;          /* Page-type flage for the root page of new table */
55205 
55206   assert( sqlite3BtreeHoldsMutex(p) );
55207   assert( pBt->inTransaction==TRANS_WRITE );
55208   assert( !pBt->readOnly );
55209 
55210 #ifdef SQLITE_OMIT_AUTOVACUUM
55211   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55212   if( rc ){
55213     return rc;
55214   }
55215 #else
55216   if( pBt->autoVacuum ){
55217     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
55218     MemPage *pPageMove; /* The page to move to. */
55219 
55220     /* Creating a new table may probably require moving an existing database
55221     ** to make room for the new tables root page. In case this page turns
55222     ** out to be an overflow page, delete all overflow page-map caches
55223     ** held by open cursors.
55224     */
55225     invalidateAllOverflowCache(pBt);
55226 
55227     /* Read the value of meta[3] from the database to determine where the
55228     ** root page of the new table should go. meta[3] is the largest root-page
55229     ** created so far, so the new root-page is (meta[3]+1).
55230     */
55231     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
55232     pgnoRoot++;
55233 
55234     /* The new root-page may not be allocated on a pointer-map page, or the
55235     ** PENDING_BYTE page.
55236     */
55237     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
55238         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
55239       pgnoRoot++;
55240     }
55241     assert( pgnoRoot>=3 );
55242 
55243     /* Allocate a page. The page that currently resides at pgnoRoot will
55244     ** be moved to the allocated page (unless the allocated page happens
55245     ** to reside at pgnoRoot).
55246     */
55247     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
55248     if( rc!=SQLITE_OK ){
55249       return rc;
55250     }
55251 
55252     if( pgnoMove!=pgnoRoot ){
55253       /* pgnoRoot is the page that will be used for the root-page of
55254       ** the new table (assuming an error did not occur). But we were
55255       ** allocated pgnoMove. If required (i.e. if it was not allocated
55256       ** by extending the file), the current page at position pgnoMove
55257       ** is already journaled.
55258       */
55259       u8 eType = 0;
55260       Pgno iPtrPage = 0;
55261 
55262       releasePage(pPageMove);
55263 
55264       /* Move the page currently at pgnoRoot to pgnoMove. */
55265       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55266       if( rc!=SQLITE_OK ){
55267         return rc;
55268       }
55269       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
55270       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
55271         rc = SQLITE_CORRUPT_BKPT;
55272       }
55273       if( rc!=SQLITE_OK ){
55274         releasePage(pRoot);
55275         return rc;
55276       }
55277       assert( eType!=PTRMAP_ROOTPAGE );
55278       assert( eType!=PTRMAP_FREEPAGE );
55279       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
55280       releasePage(pRoot);
55281 
55282       /* Obtain the page at pgnoRoot */
55283       if( rc!=SQLITE_OK ){
55284         return rc;
55285       }
55286       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
55287       if( rc!=SQLITE_OK ){
55288         return rc;
55289       }
55290       rc = sqlite3PagerWrite(pRoot->pDbPage);
55291       if( rc!=SQLITE_OK ){
55292         releasePage(pRoot);
55293         return rc;
55294       }
55295     }else{
55296       pRoot = pPageMove;
55297     }
55298 
55299     /* Update the pointer-map and meta-data with the new root-page number. */
55300     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
55301     if( rc ){
55302       releasePage(pRoot);
55303       return rc;
55304     }
55305 
55306     /* When the new root page was allocated, page 1 was made writable in
55307     ** order either to increase the database filesize, or to decrement the
55308     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
55309     */
55310     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
55311     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
55312     if( NEVER(rc) ){
55313       releasePage(pRoot);
55314       return rc;
55315     }
55316 
55317   }else{
55318     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
55319     if( rc ) return rc;
55320   }
55321 #endif
55322   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55323   if( createTabFlags & BTREE_INTKEY ){
55324     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
55325   }else{
55326     ptfFlags = PTF_ZERODATA | PTF_LEAF;
55327   }
55328   zeroPage(pRoot, ptfFlags);
55329   sqlite3PagerUnref(pRoot->pDbPage);
55330   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
55331   *piTable = (int)pgnoRoot;
55332   return SQLITE_OK;
55333 }
55334 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
55335   int rc;
55336   sqlite3BtreeEnter(p);
55337   rc = btreeCreateTable(p, piTable, flags);
55338   sqlite3BtreeLeave(p);
55339   return rc;
55340 }
55341 
55342 /*
55343 ** Erase the given database page and all its children.  Return
55344 ** the page to the freelist.
55345 */
55346 static int clearDatabasePage(
55347   BtShared *pBt,           /* The BTree that contains the table */
55348   Pgno pgno,               /* Page number to clear */
55349   int freePageFlag,        /* Deallocate page if true */
55350   int *pnChange            /* Add number of Cells freed to this counter */
55351 ){
55352   MemPage *pPage;
55353   int rc;
55354   unsigned char *pCell;
55355   int i;
55356 
55357   assert( sqlite3_mutex_held(pBt->mutex) );
55358   if( pgno>btreePagecount(pBt) ){
55359     return SQLITE_CORRUPT_BKPT;
55360   }
55361 
55362   rc = getAndInitPage(pBt, pgno, &pPage);
55363   if( rc ) return rc;
55364   for(i=0; i<pPage->nCell; i++){
55365     pCell = findCell(pPage, i);
55366     if( !pPage->leaf ){
55367       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
55368       if( rc ) goto cleardatabasepage_out;
55369     }
55370     rc = clearCell(pPage, pCell);
55371     if( rc ) goto cleardatabasepage_out;
55372   }
55373   if( !pPage->leaf ){
55374     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
55375     if( rc ) goto cleardatabasepage_out;
55376   }else if( pnChange ){
55377     assert( pPage->intKey );
55378     *pnChange += pPage->nCell;
55379   }
55380   if( freePageFlag ){
55381     freePage(pPage, &rc);
55382   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
55383     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
55384   }
55385 
55386 cleardatabasepage_out:
55387   releasePage(pPage);
55388   return rc;
55389 }
55390 
55391 /*
55392 ** Delete all information from a single table in the database.  iTable is
55393 ** the page number of the root of the table.  After this routine returns,
55394 ** the root page is empty, but still exists.
55395 **
55396 ** This routine will fail with SQLITE_LOCKED if there are any open
55397 ** read cursors on the table.  Open write cursors are moved to the
55398 ** root of the table.
55399 **
55400 ** If pnChange is not NULL, then table iTable must be an intkey table. The
55401 ** integer value pointed to by pnChange is incremented by the number of
55402 ** entries in the table.
55403 */
55404 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
55405   int rc;
55406   BtShared *pBt = p->pBt;
55407   sqlite3BtreeEnter(p);
55408   assert( p->inTrans==TRANS_WRITE );
55409 
55410   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
55411   ** is the root of a table b-tree - if it is not, the following call is
55412   ** a no-op).  */
55413   invalidateIncrblobCursors(p, 0, 1);
55414 
55415   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
55416   if( SQLITE_OK==rc ){
55417     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
55418   }
55419   sqlite3BtreeLeave(p);
55420   return rc;
55421 }
55422 
55423 /*
55424 ** Erase all information in a table and add the root of the table to
55425 ** the freelist.  Except, the root of the principle table (the one on
55426 ** page 1) is never added to the freelist.
55427 **
55428 ** This routine will fail with SQLITE_LOCKED if there are any open
55429 ** cursors on the table.
55430 **
55431 ** If AUTOVACUUM is enabled and the page at iTable is not the last
55432 ** root page in the database file, then the last root page
55433 ** in the database file is moved into the slot formerly occupied by
55434 ** iTable and that last slot formerly occupied by the last root page
55435 ** is added to the freelist instead of iTable.  In this say, all
55436 ** root pages are kept at the beginning of the database file, which
55437 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
55438 ** page number that used to be the last root page in the file before
55439 ** the move.  If no page gets moved, *piMoved is set to 0.
55440 ** The last root page is recorded in meta[3] and the value of
55441 ** meta[3] is updated by this procedure.
55442 */
55443 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
55444   int rc;
55445   MemPage *pPage = 0;
55446   BtShared *pBt = p->pBt;
55447 
55448   assert( sqlite3BtreeHoldsMutex(p) );
55449   assert( p->inTrans==TRANS_WRITE );
55450 
55451   /* It is illegal to drop a table if any cursors are open on the
55452   ** database. This is because in auto-vacuum mode the backend may
55453   ** need to move another root-page to fill a gap left by the deleted
55454   ** root page. If an open cursor was using this page a problem would
55455   ** occur.
55456   **
55457   ** This error is caught long before control reaches this point.
55458   */
55459   if( NEVER(pBt->pCursor) ){
55460     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
55461     return SQLITE_LOCKED_SHAREDCACHE;
55462   }
55463 
55464   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
55465   if( rc ) return rc;
55466   rc = sqlite3BtreeClearTable(p, iTable, 0);
55467   if( rc ){
55468     releasePage(pPage);
55469     return rc;
55470   }
55471 
55472   *piMoved = 0;
55473 
55474   if( iTable>1 ){
55475 #ifdef SQLITE_OMIT_AUTOVACUUM
55476     freePage(pPage, &rc);
55477     releasePage(pPage);
55478 #else
55479     if( pBt->autoVacuum ){
55480       Pgno maxRootPgno;
55481       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
55482 
55483       if( iTable==maxRootPgno ){
55484         /* If the table being dropped is the table with the largest root-page
55485         ** number in the database, put the root page on the free list.
55486         */
55487         freePage(pPage, &rc);
55488         releasePage(pPage);
55489         if( rc!=SQLITE_OK ){
55490           return rc;
55491         }
55492       }else{
55493         /* The table being dropped does not have the largest root-page
55494         ** number in the database. So move the page that does into the
55495         ** gap left by the deleted root-page.
55496         */
55497         MemPage *pMove;
55498         releasePage(pPage);
55499         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55500         if( rc!=SQLITE_OK ){
55501           return rc;
55502         }
55503         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
55504         releasePage(pMove);
55505         if( rc!=SQLITE_OK ){
55506           return rc;
55507         }
55508         pMove = 0;
55509         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
55510         freePage(pMove, &rc);
55511         releasePage(pMove);
55512         if( rc!=SQLITE_OK ){
55513           return rc;
55514         }
55515         *piMoved = maxRootPgno;
55516       }
55517 
55518       /* Set the new 'max-root-page' value in the database header. This
55519       ** is the old value less one, less one more if that happens to
55520       ** be a root-page number, less one again if that is the
55521       ** PENDING_BYTE_PAGE.
55522       */
55523       maxRootPgno--;
55524       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
55525              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
55526         maxRootPgno--;
55527       }
55528       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
55529 
55530       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
55531     }else{
55532       freePage(pPage, &rc);
55533       releasePage(pPage);
55534     }
55535 #endif
55536   }else{
55537     /* If sqlite3BtreeDropTable was called on page 1.
55538     ** This really never should happen except in a corrupt
55539     ** database.
55540     */
55541     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
55542     releasePage(pPage);
55543   }
55544   return rc;
55545 }
55546 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
55547   int rc;
55548   sqlite3BtreeEnter(p);
55549   rc = btreeDropTable(p, iTable, piMoved);
55550   sqlite3BtreeLeave(p);
55551   return rc;
55552 }
55553 
55554 
55555 /*
55556 ** This function may only be called if the b-tree connection already
55557 ** has a read or write transaction open on the database.
55558 **
55559 ** Read the meta-information out of a database file.  Meta[0]
55560 ** is the number of free pages currently in the database.  Meta[1]
55561 ** through meta[15] are available for use by higher layers.  Meta[0]
55562 ** is read-only, the others are read/write.
55563 **
55564 ** The schema layer numbers meta values differently.  At the schema
55565 ** layer (and the SetCookie and ReadCookie opcodes) the number of
55566 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
55567 */
55568 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
55569   BtShared *pBt = p->pBt;
55570 
55571   sqlite3BtreeEnter(p);
55572   assert( p->inTrans>TRANS_NONE );
55573   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
55574   assert( pBt->pPage1 );
55575   assert( idx>=0 && idx<=15 );
55576 
55577   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
55578 
55579   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
55580   ** database, mark the database as read-only.  */
55581 #ifdef SQLITE_OMIT_AUTOVACUUM
55582   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
55583 #endif
55584 
55585   sqlite3BtreeLeave(p);
55586 }
55587 
55588 /*
55589 ** Write meta-information back into the database.  Meta[0] is
55590 ** read-only and may not be written.
55591 */
55592 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
55593   BtShared *pBt = p->pBt;
55594   unsigned char *pP1;
55595   int rc;
55596   assert( idx>=1 && idx<=15 );
55597   sqlite3BtreeEnter(p);
55598   assert( p->inTrans==TRANS_WRITE );
55599   assert( pBt->pPage1!=0 );
55600   pP1 = pBt->pPage1->aData;
55601   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
55602   if( rc==SQLITE_OK ){
55603     put4byte(&pP1[36 + idx*4], iMeta);
55604 #ifndef SQLITE_OMIT_AUTOVACUUM
55605     if( idx==BTREE_INCR_VACUUM ){
55606       assert( pBt->autoVacuum || iMeta==0 );
55607       assert( iMeta==0 || iMeta==1 );
55608       pBt->incrVacuum = (u8)iMeta;
55609     }
55610 #endif
55611   }
55612   sqlite3BtreeLeave(p);
55613   return rc;
55614 }
55615 
55616 #ifndef SQLITE_OMIT_BTREECOUNT
55617 /*
55618 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
55619 ** number of entries in the b-tree and write the result to *pnEntry.
55620 **
55621 ** SQLITE_OK is returned if the operation is successfully executed.
55622 ** Otherwise, if an error is encountered (i.e. an IO error or database
55623 ** corruption) an SQLite error code is returned.
55624 */
55625 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
55626   i64 nEntry = 0;                      /* Value to return in *pnEntry */
55627   int rc;                              /* Return code */
55628 
55629   if( pCur->pgnoRoot==0 ){
55630     *pnEntry = 0;
55631     return SQLITE_OK;
55632   }
55633   rc = moveToRoot(pCur);
55634 
55635   /* Unless an error occurs, the following loop runs one iteration for each
55636   ** page in the B-Tree structure (not including overflow pages).
55637   */
55638   while( rc==SQLITE_OK ){
55639     int iIdx;                          /* Index of child node in parent */
55640     MemPage *pPage;                    /* Current page of the b-tree */
55641 
55642     /* If this is a leaf page or the tree is not an int-key tree, then
55643     ** this page contains countable entries. Increment the entry counter
55644     ** accordingly.
55645     */
55646     pPage = pCur->apPage[pCur->iPage];
55647     if( pPage->leaf || !pPage->intKey ){
55648       nEntry += pPage->nCell;
55649     }
55650 
55651     /* pPage is a leaf node. This loop navigates the cursor so that it
55652     ** points to the first interior cell that it points to the parent of
55653     ** the next page in the tree that has not yet been visited. The
55654     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
55655     ** of the page, or to the number of cells in the page if the next page
55656     ** to visit is the right-child of its parent.
55657     **
55658     ** If all pages in the tree have been visited, return SQLITE_OK to the
55659     ** caller.
55660     */
55661     if( pPage->leaf ){
55662       do {
55663         if( pCur->iPage==0 ){
55664           /* All pages of the b-tree have been visited. Return successfully. */
55665           *pnEntry = nEntry;
55666           return SQLITE_OK;
55667         }
55668         moveToParent(pCur);
55669       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
55670 
55671       pCur->aiIdx[pCur->iPage]++;
55672       pPage = pCur->apPage[pCur->iPage];
55673     }
55674 
55675     /* Descend to the child node of the cell that the cursor currently
55676     ** points at. This is the right-child if (iIdx==pPage->nCell).
55677     */
55678     iIdx = pCur->aiIdx[pCur->iPage];
55679     if( iIdx==pPage->nCell ){
55680       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
55681     }else{
55682       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
55683     }
55684   }
55685 
55686   /* An error has occurred. Return an error code. */
55687   return rc;
55688 }
55689 #endif
55690 
55691 /*
55692 ** Return the pager associated with a BTree.  This routine is used for
55693 ** testing and debugging only.
55694 */
55695 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
55696   return p->pBt->pPager;
55697 }
55698 
55699 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55700 /*
55701 ** Append a message to the error message string.
55702 */
55703 static void checkAppendMsg(
55704   IntegrityCk *pCheck,
55705   char *zMsg1,
55706   const char *zFormat,
55707   ...
55708 ){
55709   va_list ap;
55710   if( !pCheck->mxErr ) return;
55711   pCheck->mxErr--;
55712   pCheck->nErr++;
55713   va_start(ap, zFormat);
55714   if( pCheck->errMsg.nChar ){
55715     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
55716   }
55717   if( zMsg1 ){
55718     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
55719   }
55720   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
55721   va_end(ap);
55722   if( pCheck->errMsg.mallocFailed ){
55723     pCheck->mallocFailed = 1;
55724   }
55725 }
55726 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55727 
55728 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55729 /*
55730 ** Add 1 to the reference count for page iPage.  If this is the second
55731 ** reference to the page, add an error message to pCheck->zErrMsg.
55732 ** Return 1 if there are 2 ore more references to the page and 0 if
55733 ** if this is the first reference to the page.
55734 **
55735 ** Also check that the page number is in bounds.
55736 */
55737 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
55738   if( iPage==0 ) return 1;
55739   if( iPage>pCheck->nPage ){
55740     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
55741     return 1;
55742   }
55743   if( pCheck->anRef[iPage]==1 ){
55744     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
55745     return 1;
55746   }
55747   return  (pCheck->anRef[iPage]++)>1;
55748 }
55749 
55750 #ifndef SQLITE_OMIT_AUTOVACUUM
55751 /*
55752 ** Check that the entry in the pointer-map for page iChild maps to
55753 ** page iParent, pointer type ptrType. If not, append an error message
55754 ** to pCheck.
55755 */
55756 static void checkPtrmap(
55757   IntegrityCk *pCheck,   /* Integrity check context */
55758   Pgno iChild,           /* Child page number */
55759   u8 eType,              /* Expected pointer map type */
55760   Pgno iParent,          /* Expected pointer map parent page number */
55761   char *zContext         /* Context description (used for error msg) */
55762 ){
55763   int rc;
55764   u8 ePtrmapType;
55765   Pgno iPtrmapParent;
55766 
55767   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
55768   if( rc!=SQLITE_OK ){
55769     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
55770     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
55771     return;
55772   }
55773 
55774   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
55775     checkAppendMsg(pCheck, zContext,
55776       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
55777       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
55778   }
55779 }
55780 #endif
55781 
55782 /*
55783 ** Check the integrity of the freelist or of an overflow page list.
55784 ** Verify that the number of pages on the list is N.
55785 */
55786 static void checkList(
55787   IntegrityCk *pCheck,  /* Integrity checking context */
55788   int isFreeList,       /* True for a freelist.  False for overflow page list */
55789   int iPage,            /* Page number for first page in the list */
55790   int N,                /* Expected number of pages in the list */
55791   char *zContext        /* Context for error messages */
55792 ){
55793   int i;
55794   int expected = N;
55795   int iFirst = iPage;
55796   while( N-- > 0 && pCheck->mxErr ){
55797     DbPage *pOvflPage;
55798     unsigned char *pOvflData;
55799     if( iPage<1 ){
55800       checkAppendMsg(pCheck, zContext,
55801          "%d of %d pages missing from overflow list starting at %d",
55802           N+1, expected, iFirst);
55803       break;
55804     }
55805     if( checkRef(pCheck, iPage, zContext) ) break;
55806     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
55807       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
55808       break;
55809     }
55810     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
55811     if( isFreeList ){
55812       int n = get4byte(&pOvflData[4]);
55813 #ifndef SQLITE_OMIT_AUTOVACUUM
55814       if( pCheck->pBt->autoVacuum ){
55815         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
55816       }
55817 #endif
55818       if( n>(int)pCheck->pBt->usableSize/4-2 ){
55819         checkAppendMsg(pCheck, zContext,
55820            "freelist leaf count too big on page %d", iPage);
55821         N--;
55822       }else{
55823         for(i=0; i<n; i++){
55824           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
55825 #ifndef SQLITE_OMIT_AUTOVACUUM
55826           if( pCheck->pBt->autoVacuum ){
55827             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
55828           }
55829 #endif
55830           checkRef(pCheck, iFreePage, zContext);
55831         }
55832         N -= n;
55833       }
55834     }
55835 #ifndef SQLITE_OMIT_AUTOVACUUM
55836     else{
55837       /* If this database supports auto-vacuum and iPage is not the last
55838       ** page in this overflow list, check that the pointer-map entry for
55839       ** the following page matches iPage.
55840       */
55841       if( pCheck->pBt->autoVacuum && N>0 ){
55842         i = get4byte(pOvflData);
55843         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
55844       }
55845     }
55846 #endif
55847     iPage = get4byte(pOvflData);
55848     sqlite3PagerUnref(pOvflPage);
55849   }
55850 }
55851 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
55852 
55853 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
55854 /*
55855 ** Do various sanity checks on a single page of a tree.  Return
55856 ** the tree depth.  Root pages return 0.  Parents of root pages
55857 ** return 1, and so forth.
55858 **
55859 ** These checks are done:
55860 **
55861 **      1.  Make sure that cells and freeblocks do not overlap
55862 **          but combine to completely cover the page.
55863 **  NO  2.  Make sure cell keys are in order.
55864 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
55865 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
55866 **      5.  Check the integrity of overflow pages.
55867 **      6.  Recursively call checkTreePage on all children.
55868 **      7.  Verify that the depth of all children is the same.
55869 **      8.  Make sure this page is at least 33% full or else it is
55870 **          the root of the tree.
55871 */
55872 static int checkTreePage(
55873   IntegrityCk *pCheck,  /* Context for the sanity check */
55874   int iPage,            /* Page number of the page to check */
55875   char *zParentContext, /* Parent context */
55876   i64 *pnParentMinKey,
55877   i64 *pnParentMaxKey
55878 ){
55879   MemPage *pPage;
55880   int i, rc, depth, d2, pgno, cnt;
55881   int hdr, cellStart;
55882   int nCell;
55883   u8 *data;
55884   BtShared *pBt;
55885   int usableSize;
55886   char zContext[100];
55887   char *hit = 0;
55888   i64 nMinKey = 0;
55889   i64 nMaxKey = 0;
55890 
55891   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
55892 
55893   /* Check that the page exists
55894   */
55895   pBt = pCheck->pBt;
55896   usableSize = pBt->usableSize;
55897   if( iPage==0 ) return 0;
55898   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
55899   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
55900     checkAppendMsg(pCheck, zContext,
55901        "unable to get the page. error code=%d", rc);
55902     return 0;
55903   }
55904 
55905   /* Clear MemPage.isInit to make sure the corruption detection code in
55906   ** btreeInitPage() is executed.  */
55907   pPage->isInit = 0;
55908   if( (rc = btreeInitPage(pPage))!=0 ){
55909     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
55910     checkAppendMsg(pCheck, zContext,
55911                    "btreeInitPage() returns error code %d", rc);
55912     releasePage(pPage);
55913     return 0;
55914   }
55915 
55916   /* Check out all the cells.
55917   */
55918   depth = 0;
55919   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
55920     u8 *pCell;
55921     u32 sz;
55922     CellInfo info;
55923 
55924     /* Check payload overflow pages
55925     */
55926     sqlite3_snprintf(sizeof(zContext), zContext,
55927              "On tree page %d cell %d: ", iPage, i);
55928     pCell = findCell(pPage,i);
55929     btreeParseCellPtr(pPage, pCell, &info);
55930     sz = info.nData;
55931     if( !pPage->intKey ) sz += (int)info.nKey;
55932     /* For intKey pages, check that the keys are in order.
55933     */
55934     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
55935     else{
55936       if( info.nKey <= nMaxKey ){
55937         checkAppendMsg(pCheck, zContext,
55938             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
55939       }
55940       nMaxKey = info.nKey;
55941     }
55942     assert( sz==info.nPayload );
55943     if( (sz>info.nLocal)
55944      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
55945     ){
55946       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
55947       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
55948 #ifndef SQLITE_OMIT_AUTOVACUUM
55949       if( pBt->autoVacuum ){
55950         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
55951       }
55952 #endif
55953       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
55954     }
55955 
55956     /* Check sanity of left child page.
55957     */
55958     if( !pPage->leaf ){
55959       pgno = get4byte(pCell);
55960 #ifndef SQLITE_OMIT_AUTOVACUUM
55961       if( pBt->autoVacuum ){
55962         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55963       }
55964 #endif
55965       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
55966       if( i>0 && d2!=depth ){
55967         checkAppendMsg(pCheck, zContext, "Child page depth differs");
55968       }
55969       depth = d2;
55970     }
55971   }
55972 
55973   if( !pPage->leaf ){
55974     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55975     sqlite3_snprintf(sizeof(zContext), zContext,
55976                      "On page %d at right child: ", iPage);
55977 #ifndef SQLITE_OMIT_AUTOVACUUM
55978     if( pBt->autoVacuum ){
55979       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
55980     }
55981 #endif
55982     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
55983   }
55984 
55985   /* For intKey leaf pages, check that the min/max keys are in order
55986   ** with any left/parent/right pages.
55987   */
55988   if( pPage->leaf && pPage->intKey ){
55989     /* if we are a left child page */
55990     if( pnParentMinKey ){
55991       /* if we are the left most child page */
55992       if( !pnParentMaxKey ){
55993         if( nMaxKey > *pnParentMinKey ){
55994           checkAppendMsg(pCheck, zContext,
55995               "Rowid %lld out of order (max larger than parent min of %lld)",
55996               nMaxKey, *pnParentMinKey);
55997         }
55998       }else{
55999         if( nMinKey <= *pnParentMinKey ){
56000           checkAppendMsg(pCheck, zContext,
56001               "Rowid %lld out of order (min less than parent min of %lld)",
56002               nMinKey, *pnParentMinKey);
56003         }
56004         if( nMaxKey > *pnParentMaxKey ){
56005           checkAppendMsg(pCheck, zContext,
56006               "Rowid %lld out of order (max larger than parent max of %lld)",
56007               nMaxKey, *pnParentMaxKey);
56008         }
56009         *pnParentMinKey = nMaxKey;
56010       }
56011     /* else if we're a right child page */
56012     } else if( pnParentMaxKey ){
56013       if( nMinKey <= *pnParentMaxKey ){
56014         checkAppendMsg(pCheck, zContext,
56015             "Rowid %lld out of order (min less than parent max of %lld)",
56016             nMinKey, *pnParentMaxKey);
56017       }
56018     }
56019   }
56020 
56021   /* Check for complete coverage of the page
56022   */
56023   data = pPage->aData;
56024   hdr = pPage->hdrOffset;
56025   hit = sqlite3PageMalloc( pBt->pageSize );
56026   if( hit==0 ){
56027     pCheck->mallocFailed = 1;
56028   }else{
56029     int contentOffset = get2byteNotZero(&data[hdr+5]);
56030     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
56031     memset(hit+contentOffset, 0, usableSize-contentOffset);
56032     memset(hit, 1, contentOffset);
56033     nCell = get2byte(&data[hdr+3]);
56034     cellStart = hdr + 12 - 4*pPage->leaf;
56035     for(i=0; i<nCell; i++){
56036       int pc = get2byte(&data[cellStart+i*2]);
56037       u32 size = 65536;
56038       int j;
56039       if( pc<=usableSize-4 ){
56040         size = cellSizePtr(pPage, &data[pc]);
56041       }
56042       if( (int)(pc+size-1)>=usableSize ){
56043         checkAppendMsg(pCheck, 0,
56044             "Corruption detected in cell %d on page %d",i,iPage);
56045       }else{
56046         for(j=pc+size-1; j>=pc; j--) hit[j]++;
56047       }
56048     }
56049     i = get2byte(&data[hdr+1]);
56050     while( i>0 ){
56051       int size, j;
56052       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
56053       size = get2byte(&data[i+2]);
56054       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
56055       for(j=i+size-1; j>=i; j--) hit[j]++;
56056       j = get2byte(&data[i]);
56057       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
56058       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
56059       i = j;
56060     }
56061     for(i=cnt=0; i<usableSize; i++){
56062       if( hit[i]==0 ){
56063         cnt++;
56064       }else if( hit[i]>1 ){
56065         checkAppendMsg(pCheck, 0,
56066           "Multiple uses for byte %d of page %d", i, iPage);
56067         break;
56068       }
56069     }
56070     if( cnt!=data[hdr+7] ){
56071       checkAppendMsg(pCheck, 0,
56072           "Fragmentation of %d bytes reported as %d on page %d",
56073           cnt, data[hdr+7], iPage);
56074     }
56075   }
56076   sqlite3PageFree(hit);
56077   releasePage(pPage);
56078   return depth+1;
56079 }
56080 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56081 
56082 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
56083 /*
56084 ** This routine does a complete check of the given BTree file.  aRoot[] is
56085 ** an array of pages numbers were each page number is the root page of
56086 ** a table.  nRoot is the number of entries in aRoot.
56087 **
56088 ** A read-only or read-write transaction must be opened before calling
56089 ** this function.
56090 **
56091 ** Write the number of error seen in *pnErr.  Except for some memory
56092 ** allocation errors,  an error message held in memory obtained from
56093 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
56094 ** returned.  If a memory allocation error occurs, NULL is returned.
56095 */
56096 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
56097   Btree *p,     /* The btree to be checked */
56098   int *aRoot,   /* An array of root pages numbers for individual trees */
56099   int nRoot,    /* Number of entries in aRoot[] */
56100   int mxErr,    /* Stop reporting errors after this many */
56101   int *pnErr    /* Write number of errors seen to this variable */
56102 ){
56103   Pgno i;
56104   int nRef;
56105   IntegrityCk sCheck;
56106   BtShared *pBt = p->pBt;
56107   char zErr[100];
56108 
56109   sqlite3BtreeEnter(p);
56110   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
56111   nRef = sqlite3PagerRefcount(pBt->pPager);
56112   sCheck.pBt = pBt;
56113   sCheck.pPager = pBt->pPager;
56114   sCheck.nPage = btreePagecount(sCheck.pBt);
56115   sCheck.mxErr = mxErr;
56116   sCheck.nErr = 0;
56117   sCheck.mallocFailed = 0;
56118   *pnErr = 0;
56119   if( sCheck.nPage==0 ){
56120     sqlite3BtreeLeave(p);
56121     return 0;
56122   }
56123   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
56124   if( !sCheck.anRef ){
56125     *pnErr = 1;
56126     sqlite3BtreeLeave(p);
56127     return 0;
56128   }
56129   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
56130   i = PENDING_BYTE_PAGE(pBt);
56131   if( i<=sCheck.nPage ){
56132     sCheck.anRef[i] = 1;
56133   }
56134   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
56135   sCheck.errMsg.useMalloc = 2;
56136 
56137   /* Check the integrity of the freelist
56138   */
56139   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
56140             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
56141 
56142   /* Check all the tables.
56143   */
56144   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
56145     if( aRoot[i]==0 ) continue;
56146 #ifndef SQLITE_OMIT_AUTOVACUUM
56147     if( pBt->autoVacuum && aRoot[i]>1 ){
56148       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
56149     }
56150 #endif
56151     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
56152   }
56153 
56154   /* Make sure every page in the file is referenced
56155   */
56156   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
56157 #ifdef SQLITE_OMIT_AUTOVACUUM
56158     if( sCheck.anRef[i]==0 ){
56159       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56160     }
56161 #else
56162     /* If the database supports auto-vacuum, make sure no tables contain
56163     ** references to pointer-map pages.
56164     */
56165     if( sCheck.anRef[i]==0 &&
56166        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
56167       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
56168     }
56169     if( sCheck.anRef[i]!=0 &&
56170        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
56171       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
56172     }
56173 #endif
56174   }
56175 
56176   /* Make sure this analysis did not leave any unref() pages.
56177   ** This is an internal consistency check; an integrity check
56178   ** of the integrity check.
56179   */
56180   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
56181     checkAppendMsg(&sCheck, 0,
56182       "Outstanding page count goes from %d to %d during this analysis",
56183       nRef, sqlite3PagerRefcount(pBt->pPager)
56184     );
56185   }
56186 
56187   /* Clean  up and report errors.
56188   */
56189   sqlite3BtreeLeave(p);
56190   sqlite3_free(sCheck.anRef);
56191   if( sCheck.mallocFailed ){
56192     sqlite3StrAccumReset(&sCheck.errMsg);
56193     *pnErr = sCheck.nErr+1;
56194     return 0;
56195   }
56196   *pnErr = sCheck.nErr;
56197   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
56198   return sqlite3StrAccumFinish(&sCheck.errMsg);
56199 }
56200 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56201 
56202 /*
56203 ** Return the full pathname of the underlying database file.
56204 **
56205 ** The pager filename is invariant as long as the pager is
56206 ** open so it is safe to access without the BtShared mutex.
56207 */
56208 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
56209   assert( p->pBt->pPager!=0 );
56210   return sqlite3PagerFilename(p->pBt->pPager);
56211 }
56212 
56213 /*
56214 ** Return the pathname of the journal file for this database. The return
56215 ** value of this routine is the same regardless of whether the journal file
56216 ** has been created or not.
56217 **
56218 ** The pager journal filename is invariant as long as the pager is
56219 ** open so it is safe to access without the BtShared mutex.
56220 */
56221 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
56222   assert( p->pBt->pPager!=0 );
56223   return sqlite3PagerJournalname(p->pBt->pPager);
56224 }
56225 
56226 /*
56227 ** Return non-zero if a transaction is active.
56228 */
56229 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
56230   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
56231   return (p && (p->inTrans==TRANS_WRITE));
56232 }
56233 
56234 #ifndef SQLITE_OMIT_WAL
56235 /*
56236 ** Run a checkpoint on the Btree passed as the first argument.
56237 **
56238 ** Return SQLITE_LOCKED if this or any other connection has an open
56239 ** transaction on the shared-cache the argument Btree is connected to.
56240 **
56241 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
56242 */
56243 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
56244   int rc = SQLITE_OK;
56245   if( p ){
56246     BtShared *pBt = p->pBt;
56247     sqlite3BtreeEnter(p);
56248     if( pBt->inTransaction!=TRANS_NONE ){
56249       rc = SQLITE_LOCKED;
56250     }else{
56251       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
56252     }
56253     sqlite3BtreeLeave(p);
56254   }
56255   return rc;
56256 }
56257 #endif
56258 
56259 /*
56260 ** Return non-zero if a read (or write) transaction is active.
56261 */
56262 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
56263   assert( p );
56264   assert( sqlite3_mutex_held(p->db->mutex) );
56265   return p->inTrans!=TRANS_NONE;
56266 }
56267 
56268 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
56269   assert( p );
56270   assert( sqlite3_mutex_held(p->db->mutex) );
56271   return p->nBackup!=0;
56272 }
56273 
56274 /*
56275 ** This function returns a pointer to a blob of memory associated with
56276 ** a single shared-btree. The memory is used by client code for its own
56277 ** purposes (for example, to store a high-level schema associated with
56278 ** the shared-btree). The btree layer manages reference counting issues.
56279 **
56280 ** The first time this is called on a shared-btree, nBytes bytes of memory
56281 ** are allocated, zeroed, and returned to the caller. For each subsequent
56282 ** call the nBytes parameter is ignored and a pointer to the same blob
56283 ** of memory returned.
56284 **
56285 ** If the nBytes parameter is 0 and the blob of memory has not yet been
56286 ** allocated, a null pointer is returned. If the blob has already been
56287 ** allocated, it is returned as normal.
56288 **
56289 ** Just before the shared-btree is closed, the function passed as the
56290 ** xFree argument when the memory allocation was made is invoked on the
56291 ** blob of allocated memory. The xFree function should not call sqlite3_free()
56292 ** on the memory, the btree layer does that.
56293 */
56294 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
56295   BtShared *pBt = p->pBt;
56296   sqlite3BtreeEnter(p);
56297   if( !pBt->pSchema && nBytes ){
56298     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
56299     pBt->xFreeSchema = xFree;
56300   }
56301   sqlite3BtreeLeave(p);
56302   return pBt->pSchema;
56303 }
56304 
56305 /*
56306 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
56307 ** btree as the argument handle holds an exclusive lock on the
56308 ** sqlite_master table. Otherwise SQLITE_OK.
56309 */
56310 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
56311   int rc;
56312   assert( sqlite3_mutex_held(p->db->mutex) );
56313   sqlite3BtreeEnter(p);
56314   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
56315   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
56316   sqlite3BtreeLeave(p);
56317   return rc;
56318 }
56319 
56320 
56321 #ifndef SQLITE_OMIT_SHARED_CACHE
56322 /*
56323 ** Obtain a lock on the table whose root page is iTab.  The
56324 ** lock is a write lock if isWritelock is true or a read lock
56325 ** if it is false.
56326 */
56327 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
56328   int rc = SQLITE_OK;
56329   assert( p->inTrans!=TRANS_NONE );
56330   if( p->sharable ){
56331     u8 lockType = READ_LOCK + isWriteLock;
56332     assert( READ_LOCK+1==WRITE_LOCK );
56333     assert( isWriteLock==0 || isWriteLock==1 );
56334 
56335     sqlite3BtreeEnter(p);
56336     rc = querySharedCacheTableLock(p, iTab, lockType);
56337     if( rc==SQLITE_OK ){
56338       rc = setSharedCacheTableLock(p, iTab, lockType);
56339     }
56340     sqlite3BtreeLeave(p);
56341   }
56342   return rc;
56343 }
56344 #endif
56345 
56346 #ifndef SQLITE_OMIT_INCRBLOB
56347 /*
56348 ** Argument pCsr must be a cursor opened for writing on an
56349 ** INTKEY table currently pointing at a valid table entry.
56350 ** This function modifies the data stored as part of that entry.
56351 **
56352 ** Only the data content may only be modified, it is not possible to
56353 ** change the length of the data stored. If this function is called with
56354 ** parameters that attempt to write past the end of the existing data,
56355 ** no modifications are made and SQLITE_CORRUPT is returned.
56356 */
56357 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
56358   int rc;
56359   assert( cursorHoldsMutex(pCsr) );
56360   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
56361   assert( pCsr->isIncrblobHandle );
56362 
56363   rc = restoreCursorPosition(pCsr);
56364   if( rc!=SQLITE_OK ){
56365     return rc;
56366   }
56367   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
56368   if( pCsr->eState!=CURSOR_VALID ){
56369     return SQLITE_ABORT;
56370   }
56371 
56372   /* Check some assumptions:
56373   **   (a) the cursor is open for writing,
56374   **   (b) there is a read/write transaction open,
56375   **   (c) the connection holds a write-lock on the table (if required),
56376   **   (d) there are no conflicting read-locks, and
56377   **   (e) the cursor points at a valid row of an intKey table.
56378   */
56379   if( !pCsr->wrFlag ){
56380     return SQLITE_READONLY;
56381   }
56382   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
56383   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
56384   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
56385   assert( pCsr->apPage[pCsr->iPage]->intKey );
56386 
56387   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
56388 }
56389 
56390 /*
56391 ** Set a flag on this cursor to cache the locations of pages from the
56392 ** overflow list for the current row. This is used by cursors opened
56393 ** for incremental blob IO only.
56394 **
56395 ** This function sets a flag only. The actual page location cache
56396 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
56397 ** accessPayload() (the worker function for sqlite3BtreeData() and
56398 ** sqlite3BtreePutData()).
56399 */
56400 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
56401   assert( cursorHoldsMutex(pCur) );
56402   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
56403   invalidateOverflowCache(pCur);
56404   pCur->isIncrblobHandle = 1;
56405 }
56406 #endif
56407 
56408 /*
56409 ** Set both the "read version" (single byte at byte offset 18) and
56410 ** "write version" (single byte at byte offset 19) fields in the database
56411 ** header to iVersion.
56412 */
56413 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
56414   BtShared *pBt = pBtree->pBt;
56415   int rc;                         /* Return code */
56416 
56417   assert( iVersion==1 || iVersion==2 );
56418 
56419   /* If setting the version fields to 1, do not automatically open the
56420   ** WAL connection, even if the version fields are currently set to 2.
56421   */
56422   pBt->doNotUseWAL = (u8)(iVersion==1);
56423 
56424   rc = sqlite3BtreeBeginTrans(pBtree, 0);
56425   if( rc==SQLITE_OK ){
56426     u8 *aData = pBt->pPage1->aData;
56427     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
56428       rc = sqlite3BtreeBeginTrans(pBtree, 2);
56429       if( rc==SQLITE_OK ){
56430         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56431         if( rc==SQLITE_OK ){
56432           aData[18] = (u8)iVersion;
56433           aData[19] = (u8)iVersion;
56434         }
56435       }
56436     }
56437   }
56438 
56439   pBt->doNotUseWAL = 0;
56440   return rc;
56441 }
56442 
56443 /************** End of btree.c ***********************************************/
56444 /************** Begin file backup.c ******************************************/
56445 /*
56446 ** 2009 January 28
56447 **
56448 ** The author disclaims copyright to this source code.  In place of
56449 ** a legal notice, here is a blessing:
56450 **
56451 **    May you do good and not evil.
56452 **    May you find forgiveness for yourself and forgive others.
56453 **    May you share freely, never taking more than you give.
56454 **
56455 *************************************************************************
56456 ** This file contains the implementation of the sqlite3_backup_XXX()
56457 ** API functions and the related features.
56458 */
56459 
56460 /* Macro to find the minimum of two numeric values.
56461 */
56462 #ifndef MIN
56463 # define MIN(x,y) ((x)<(y)?(x):(y))
56464 #endif
56465 
56466 /*
56467 ** Structure allocated for each backup operation.
56468 */
56469 struct sqlite3_backup {
56470   sqlite3* pDestDb;        /* Destination database handle */
56471   Btree *pDest;            /* Destination b-tree file */
56472   u32 iDestSchema;         /* Original schema cookie in destination */
56473   int bDestLocked;         /* True once a write-transaction is open on pDest */
56474 
56475   Pgno iNext;              /* Page number of the next source page to copy */
56476   sqlite3* pSrcDb;         /* Source database handle */
56477   Btree *pSrc;             /* Source b-tree file */
56478 
56479   int rc;                  /* Backup process error code */
56480 
56481   /* These two variables are set by every call to backup_step(). They are
56482   ** read by calls to backup_remaining() and backup_pagecount().
56483   */
56484   Pgno nRemaining;         /* Number of pages left to copy */
56485   Pgno nPagecount;         /* Total number of pages to copy */
56486 
56487   int isAttached;          /* True once backup has been registered with pager */
56488   sqlite3_backup *pNext;   /* Next backup associated with source pager */
56489 };
56490 
56491 /*
56492 ** THREAD SAFETY NOTES:
56493 **
56494 **   Once it has been created using backup_init(), a single sqlite3_backup
56495 **   structure may be accessed via two groups of thread-safe entry points:
56496 **
56497 **     * Via the sqlite3_backup_XXX() API function backup_step() and
56498 **       backup_finish(). Both these functions obtain the source database
56499 **       handle mutex and the mutex associated with the source BtShared
56500 **       structure, in that order.
56501 **
56502 **     * Via the BackupUpdate() and BackupRestart() functions, which are
56503 **       invoked by the pager layer to report various state changes in
56504 **       the page cache associated with the source database. The mutex
56505 **       associated with the source database BtShared structure will always
56506 **       be held when either of these functions are invoked.
56507 **
56508 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
56509 **   backup_pagecount() are not thread-safe functions. If they are called
56510 **   while some other thread is calling backup_step() or backup_finish(),
56511 **   the values returned may be invalid. There is no way for a call to
56512 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
56513 **   or backup_pagecount().
56514 **
56515 **   Depending on the SQLite configuration, the database handles and/or
56516 **   the Btree objects may have their own mutexes that require locking.
56517 **   Non-sharable Btrees (in-memory databases for example), do not have
56518 **   associated mutexes.
56519 */
56520 
56521 /*
56522 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
56523 ** in connection handle pDb. If such a database cannot be found, return
56524 ** a NULL pointer and write an error message to pErrorDb.
56525 **
56526 ** If the "temp" database is requested, it may need to be opened by this
56527 ** function. If an error occurs while doing so, return 0 and write an
56528 ** error message to pErrorDb.
56529 */
56530 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
56531   int i = sqlite3FindDbName(pDb, zDb);
56532 
56533   if( i==1 ){
56534     Parse *pParse;
56535     int rc = 0;
56536     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
56537     if( pParse==0 ){
56538       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
56539       rc = SQLITE_NOMEM;
56540     }else{
56541       pParse->db = pDb;
56542       if( sqlite3OpenTempDatabase(pParse) ){
56543         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
56544         rc = SQLITE_ERROR;
56545       }
56546       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
56547       sqlite3StackFree(pErrorDb, pParse);
56548     }
56549     if( rc ){
56550       return 0;
56551     }
56552   }
56553 
56554   if( i<0 ){
56555     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
56556     return 0;
56557   }
56558 
56559   return pDb->aDb[i].pBt;
56560 }
56561 
56562 /*
56563 ** Attempt to set the page size of the destination to match the page size
56564 ** of the source.
56565 */
56566 static int setDestPgsz(sqlite3_backup *p){
56567   int rc;
56568   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
56569   return rc;
56570 }
56571 
56572 /*
56573 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
56574 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
56575 ** a pointer to the new sqlite3_backup object.
56576 **
56577 ** If an error occurs, NULL is returned and an error code and error message
56578 ** stored in database handle pDestDb.
56579 */
56580 SQLITE_API sqlite3_backup *sqlite3_backup_init(
56581   sqlite3* pDestDb,                     /* Database to write to */
56582   const char *zDestDb,                  /* Name of database within pDestDb */
56583   sqlite3* pSrcDb,                      /* Database connection to read from */
56584   const char *zSrcDb                    /* Name of database within pSrcDb */
56585 ){
56586   sqlite3_backup *p;                    /* Value to return */
56587 
56588   /* Lock the source database handle. The destination database
56589   ** handle is not locked in this routine, but it is locked in
56590   ** sqlite3_backup_step(). The user is required to ensure that no
56591   ** other thread accesses the destination handle for the duration
56592   ** of the backup operation.  Any attempt to use the destination
56593   ** database connection while a backup is in progress may cause
56594   ** a malfunction or a deadlock.
56595   */
56596   sqlite3_mutex_enter(pSrcDb->mutex);
56597   sqlite3_mutex_enter(pDestDb->mutex);
56598 
56599   if( pSrcDb==pDestDb ){
56600     sqlite3Error(
56601         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
56602     );
56603     p = 0;
56604   }else {
56605     /* Allocate space for a new sqlite3_backup object...
56606     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
56607     ** call to sqlite3_backup_init() and is destroyed by a call to
56608     ** sqlite3_backup_finish(). */
56609     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
56610     if( !p ){
56611       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
56612     }
56613   }
56614 
56615   /* If the allocation succeeded, populate the new object. */
56616   if( p ){
56617     memset(p, 0, sizeof(sqlite3_backup));
56618     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
56619     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
56620     p->pDestDb = pDestDb;
56621     p->pSrcDb = pSrcDb;
56622     p->iNext = 1;
56623     p->isAttached = 0;
56624 
56625     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
56626       /* One (or both) of the named databases did not exist or an OOM
56627       ** error was hit.  The error has already been written into the
56628       ** pDestDb handle.  All that is left to do here is free the
56629       ** sqlite3_backup structure.
56630       */
56631       sqlite3_free(p);
56632       p = 0;
56633     }
56634   }
56635   if( p ){
56636     p->pSrc->nBackup++;
56637   }
56638 
56639   sqlite3_mutex_leave(pDestDb->mutex);
56640   sqlite3_mutex_leave(pSrcDb->mutex);
56641   return p;
56642 }
56643 
56644 /*
56645 ** Argument rc is an SQLite error code. Return true if this error is
56646 ** considered fatal if encountered during a backup operation. All errors
56647 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
56648 */
56649 static int isFatalError(int rc){
56650   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
56651 }
56652 
56653 /*
56654 ** Parameter zSrcData points to a buffer containing the data for
56655 ** page iSrcPg from the source database. Copy this data into the
56656 ** destination database.
56657 */
56658 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
56659   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
56660   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
56661   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
56662   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
56663   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
56664 #ifdef SQLITE_HAS_CODEC
56665   int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
56666   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
56667 #endif
56668 
56669   int rc = SQLITE_OK;
56670   i64 iOff;
56671 
56672   assert( p->bDestLocked );
56673   assert( !isFatalError(p->rc) );
56674   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
56675   assert( zSrcData );
56676 
56677   /* Catch the case where the destination is an in-memory database and the
56678   ** page sizes of the source and destination differ.
56679   */
56680   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
56681     rc = SQLITE_READONLY;
56682   }
56683 
56684 #ifdef SQLITE_HAS_CODEC
56685   /* Backup is not possible if the page size of the destination is changing
56686   ** and a codec is in use.
56687   */
56688   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
56689     rc = SQLITE_READONLY;
56690   }
56691 
56692   /* Backup is not possible if the number of bytes of reserve space differ
56693   ** between source and destination.  If there is a difference, try to
56694   ** fix the destination to agree with the source.  If that is not possible,
56695   ** then the backup cannot proceed.
56696   */
56697   if( nSrcReserve!=nDestReserve ){
56698     u32 newPgsz = nSrcPgsz;
56699     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
56700     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
56701   }
56702 #endif
56703 
56704   /* This loop runs once for each destination page spanned by the source
56705   ** page. For each iteration, variable iOff is set to the byte offset
56706   ** of the destination page.
56707   */
56708   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
56709     DbPage *pDestPg = 0;
56710     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
56711     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
56712     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
56713      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
56714     ){
56715       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
56716       u8 *zDestData = sqlite3PagerGetData(pDestPg);
56717       u8 *zOut = &zDestData[iOff%nDestPgsz];
56718 
56719       /* Copy the data from the source page into the destination page.
56720       ** Then clear the Btree layer MemPage.isInit flag. Both this module
56721       ** and the pager code use this trick (clearing the first byte
56722       ** of the page 'extra' space to invalidate the Btree layers
56723       ** cached parse of the page). MemPage.isInit is marked
56724       ** "MUST BE FIRST" for this purpose.
56725       */
56726       memcpy(zOut, zIn, nCopy);
56727       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
56728     }
56729     sqlite3PagerUnref(pDestPg);
56730   }
56731 
56732   return rc;
56733 }
56734 
56735 /*
56736 ** If pFile is currently larger than iSize bytes, then truncate it to
56737 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
56738 ** this function is a no-op.
56739 **
56740 ** Return SQLITE_OK if everything is successful, or an SQLite error
56741 ** code if an error occurs.
56742 */
56743 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
56744   i64 iCurrent;
56745   int rc = sqlite3OsFileSize(pFile, &iCurrent);
56746   if( rc==SQLITE_OK && iCurrent>iSize ){
56747     rc = sqlite3OsTruncate(pFile, iSize);
56748   }
56749   return rc;
56750 }
56751 
56752 /*
56753 ** Register this backup object with the associated source pager for
56754 ** callbacks when pages are changed or the cache invalidated.
56755 */
56756 static void attachBackupObject(sqlite3_backup *p){
56757   sqlite3_backup **pp;
56758   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
56759   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
56760   p->pNext = *pp;
56761   *pp = p;
56762   p->isAttached = 1;
56763 }
56764 
56765 /*
56766 ** Copy nPage pages from the source b-tree to the destination.
56767 */
56768 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
56769   int rc;
56770   int destMode;       /* Destination journal mode */
56771   int pgszSrc = 0;    /* Source page size */
56772   int pgszDest = 0;   /* Destination page size */
56773 
56774   sqlite3_mutex_enter(p->pSrcDb->mutex);
56775   sqlite3BtreeEnter(p->pSrc);
56776   if( p->pDestDb ){
56777     sqlite3_mutex_enter(p->pDestDb->mutex);
56778   }
56779 
56780   rc = p->rc;
56781   if( !isFatalError(rc) ){
56782     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
56783     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
56784     int ii;                            /* Iterator variable */
56785     int nSrcPage = -1;                 /* Size of source db in pages */
56786     int bCloseTrans = 0;               /* True if src db requires unlocking */
56787 
56788     /* If the source pager is currently in a write-transaction, return
56789     ** SQLITE_BUSY immediately.
56790     */
56791     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
56792       rc = SQLITE_BUSY;
56793     }else{
56794       rc = SQLITE_OK;
56795     }
56796 
56797     /* Lock the destination database, if it is not locked already. */
56798     if( SQLITE_OK==rc && p->bDestLocked==0
56799      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
56800     ){
56801       p->bDestLocked = 1;
56802       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
56803     }
56804 
56805     /* If there is no open read-transaction on the source database, open
56806     ** one now. If a transaction is opened here, then it will be closed
56807     ** before this function exits.
56808     */
56809     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
56810       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
56811       bCloseTrans = 1;
56812     }
56813 
56814     /* Do not allow backup if the destination database is in WAL mode
56815     ** and the page sizes are different between source and destination */
56816     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
56817     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
56818     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
56819     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
56820       rc = SQLITE_READONLY;
56821     }
56822 
56823     /* Now that there is a read-lock on the source database, query the
56824     ** source pager for the number of pages in the database.
56825     */
56826     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
56827     assert( nSrcPage>=0 );
56828     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
56829       const Pgno iSrcPg = p->iNext;                 /* Source page number */
56830       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
56831         DbPage *pSrcPg;                             /* Source page object */
56832         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56833         if( rc==SQLITE_OK ){
56834           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
56835           sqlite3PagerUnref(pSrcPg);
56836         }
56837       }
56838       p->iNext++;
56839     }
56840     if( rc==SQLITE_OK ){
56841       p->nPagecount = nSrcPage;
56842       p->nRemaining = nSrcPage+1-p->iNext;
56843       if( p->iNext>(Pgno)nSrcPage ){
56844         rc = SQLITE_DONE;
56845       }else if( !p->isAttached ){
56846         attachBackupObject(p);
56847       }
56848     }
56849 
56850     /* Update the schema version field in the destination database. This
56851     ** is to make sure that the schema-version really does change in
56852     ** the case where the source and destination databases have the
56853     ** same schema version.
56854     */
56855     if( rc==SQLITE_DONE ){
56856       rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
56857       if( rc==SQLITE_OK ){
56858         if( p->pDestDb ){
56859           sqlite3ResetInternalSchema(p->pDestDb, -1);
56860         }
56861         if( destMode==PAGER_JOURNALMODE_WAL ){
56862           rc = sqlite3BtreeSetVersion(p->pDest, 2);
56863         }
56864       }
56865       if( rc==SQLITE_OK ){
56866         int nDestTruncate;
56867         /* Set nDestTruncate to the final number of pages in the destination
56868         ** database. The complication here is that the destination page
56869         ** size may be different to the source page size.
56870         **
56871         ** If the source page size is smaller than the destination page size,
56872         ** round up. In this case the call to sqlite3OsTruncate() below will
56873         ** fix the size of the file. However it is important to call
56874         ** sqlite3PagerTruncateImage() here so that any pages in the
56875         ** destination file that lie beyond the nDestTruncate page mark are
56876         ** journalled by PagerCommitPhaseOne() before they are destroyed
56877         ** by the file truncation.
56878         */
56879         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
56880         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
56881         if( pgszSrc<pgszDest ){
56882           int ratio = pgszDest/pgszSrc;
56883           nDestTruncate = (nSrcPage+ratio-1)/ratio;
56884           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
56885             nDestTruncate--;
56886           }
56887         }else{
56888           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
56889         }
56890         sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
56891 
56892         if( pgszSrc<pgszDest ){
56893           /* If the source page-size is smaller than the destination page-size,
56894           ** two extra things may need to happen:
56895           **
56896           **   * The destination may need to be truncated, and
56897           **
56898           **   * Data stored on the pages immediately following the
56899           **     pending-byte page in the source database may need to be
56900           **     copied into the destination database.
56901           */
56902           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
56903           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
56904           i64 iOff;
56905           i64 iEnd;
56906 
56907           assert( pFile );
56908           assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
56909                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
56910              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
56911           ));
56912 
56913           /* This call ensures that all data required to recreate the original
56914           ** database has been stored in the journal for pDestPager and the
56915           ** journal synced to disk. So at this point we may safely modify
56916           ** the database file in any way, knowing that if a power failure
56917           ** occurs, the original database will be reconstructed from the
56918           ** journal file.  */
56919           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
56920 
56921           /* Write the extra pages and truncate the database file as required */
56922           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
56923           for(
56924             iOff=PENDING_BYTE+pgszSrc;
56925             rc==SQLITE_OK && iOff<iEnd;
56926             iOff+=pgszSrc
56927           ){
56928             PgHdr *pSrcPg = 0;
56929             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
56930             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
56931             if( rc==SQLITE_OK ){
56932               u8 *zData = sqlite3PagerGetData(pSrcPg);
56933               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
56934             }
56935             sqlite3PagerUnref(pSrcPg);
56936           }
56937           if( rc==SQLITE_OK ){
56938             rc = backupTruncateFile(pFile, iSize);
56939           }
56940 
56941           /* Sync the database file to disk. */
56942           if( rc==SQLITE_OK ){
56943             rc = sqlite3PagerSync(pDestPager);
56944           }
56945         }else{
56946           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
56947         }
56948 
56949         /* Finish committing the transaction to the destination database. */
56950         if( SQLITE_OK==rc
56951          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
56952         ){
56953           rc = SQLITE_DONE;
56954         }
56955       }
56956     }
56957 
56958     /* If bCloseTrans is true, then this function opened a read transaction
56959     ** on the source database. Close the read transaction here. There is
56960     ** no need to check the return values of the btree methods here, as
56961     ** "committing" a read-only transaction cannot fail.
56962     */
56963     if( bCloseTrans ){
56964       TESTONLY( int rc2 );
56965       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
56966       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
56967       assert( rc2==SQLITE_OK );
56968     }
56969 
56970     if( rc==SQLITE_IOERR_NOMEM ){
56971       rc = SQLITE_NOMEM;
56972     }
56973     p->rc = rc;
56974   }
56975   if( p->pDestDb ){
56976     sqlite3_mutex_leave(p->pDestDb->mutex);
56977   }
56978   sqlite3BtreeLeave(p->pSrc);
56979   sqlite3_mutex_leave(p->pSrcDb->mutex);
56980   return rc;
56981 }
56982 
56983 /*
56984 ** Release all resources associated with an sqlite3_backup* handle.
56985 */
56986 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
56987   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
56988   sqlite3_mutex *mutex;                /* Mutex to protect source database */
56989   int rc;                              /* Value to return */
56990 
56991   /* Enter the mutexes */
56992   if( p==0 ) return SQLITE_OK;
56993   sqlite3_mutex_enter(p->pSrcDb->mutex);
56994   sqlite3BtreeEnter(p->pSrc);
56995   mutex = p->pSrcDb->mutex;
56996   if( p->pDestDb ){
56997     sqlite3_mutex_enter(p->pDestDb->mutex);
56998   }
56999 
57000   /* Detach this backup from the source pager. */
57001   if( p->pDestDb ){
57002     p->pSrc->nBackup--;
57003   }
57004   if( p->isAttached ){
57005     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57006     while( *pp!=p ){
57007       pp = &(*pp)->pNext;
57008     }
57009     *pp = p->pNext;
57010   }
57011 
57012   /* If a transaction is still open on the Btree, roll it back. */
57013   sqlite3BtreeRollback(p->pDest);
57014 
57015   /* Set the error code of the destination database handle. */
57016   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
57017   sqlite3Error(p->pDestDb, rc, 0);
57018 
57019   /* Exit the mutexes and free the backup context structure. */
57020   if( p->pDestDb ){
57021     sqlite3_mutex_leave(p->pDestDb->mutex);
57022   }
57023   sqlite3BtreeLeave(p->pSrc);
57024   if( p->pDestDb ){
57025     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57026     ** call to sqlite3_backup_init() and is destroyed by a call to
57027     ** sqlite3_backup_finish(). */
57028     sqlite3_free(p);
57029   }
57030   sqlite3_mutex_leave(mutex);
57031   return rc;
57032 }
57033 
57034 /*
57035 ** Return the number of pages still to be backed up as of the most recent
57036 ** call to sqlite3_backup_step().
57037 */
57038 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
57039   return p->nRemaining;
57040 }
57041 
57042 /*
57043 ** Return the total number of pages in the source database as of the most
57044 ** recent call to sqlite3_backup_step().
57045 */
57046 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
57047   return p->nPagecount;
57048 }
57049 
57050 /*
57051 ** This function is called after the contents of page iPage of the
57052 ** source database have been modified. If page iPage has already been
57053 ** copied into the destination database, then the data written to the
57054 ** destination is now invalidated. The destination copy of iPage needs
57055 ** to be updated with the new data before the backup operation is
57056 ** complete.
57057 **
57058 ** It is assumed that the mutex associated with the BtShared object
57059 ** corresponding to the source database is held when this function is
57060 ** called.
57061 */
57062 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
57063   sqlite3_backup *p;                   /* Iterator variable */
57064   for(p=pBackup; p; p=p->pNext){
57065     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57066     if( !isFatalError(p->rc) && iPage<p->iNext ){
57067       /* The backup process p has already copied page iPage. But now it
57068       ** has been modified by a transaction on the source pager. Copy
57069       ** the new data into the backup.
57070       */
57071       int rc;
57072       assert( p->pDestDb );
57073       sqlite3_mutex_enter(p->pDestDb->mutex);
57074       rc = backupOnePage(p, iPage, aData);
57075       sqlite3_mutex_leave(p->pDestDb->mutex);
57076       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
57077       if( rc!=SQLITE_OK ){
57078         p->rc = rc;
57079       }
57080     }
57081   }
57082 }
57083 
57084 /*
57085 ** Restart the backup process. This is called when the pager layer
57086 ** detects that the database has been modified by an external database
57087 ** connection. In this case there is no way of knowing which of the
57088 ** pages that have been copied into the destination database are still
57089 ** valid and which are not, so the entire process needs to be restarted.
57090 **
57091 ** It is assumed that the mutex associated with the BtShared object
57092 ** corresponding to the source database is held when this function is
57093 ** called.
57094 */
57095 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
57096   sqlite3_backup *p;                   /* Iterator variable */
57097   for(p=pBackup; p; p=p->pNext){
57098     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
57099     p->iNext = 1;
57100   }
57101 }
57102 
57103 #ifndef SQLITE_OMIT_VACUUM
57104 /*
57105 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
57106 ** must be active for both files.
57107 **
57108 ** The size of file pTo may be reduced by this operation. If anything
57109 ** goes wrong, the transaction on pTo is rolled back. If successful, the
57110 ** transaction is committed before returning.
57111 */
57112 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
57113   int rc;
57114   sqlite3_backup b;
57115   sqlite3BtreeEnter(pTo);
57116   sqlite3BtreeEnter(pFrom);
57117 
57118   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
57119   ** to 0. This is used by the implementations of sqlite3_backup_step()
57120   ** and sqlite3_backup_finish() to detect that they are being called
57121   ** from this function, not directly by the user.
57122   */
57123   memset(&b, 0, sizeof(b));
57124   b.pSrcDb = pFrom->db;
57125   b.pSrc = pFrom;
57126   b.pDest = pTo;
57127   b.iNext = 1;
57128 
57129   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
57130   ** file. By passing this as the number of pages to copy to
57131   ** sqlite3_backup_step(), we can guarantee that the copy finishes
57132   ** within a single call (unless an error occurs). The assert() statement
57133   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
57134   ** or an error code.
57135   */
57136   sqlite3_backup_step(&b, 0x7FFFFFFF);
57137   assert( b.rc!=SQLITE_OK );
57138   rc = sqlite3_backup_finish(&b);
57139   if( rc==SQLITE_OK ){
57140     pTo->pBt->pageSizeFixed = 0;
57141   }
57142 
57143   sqlite3BtreeLeave(pFrom);
57144   sqlite3BtreeLeave(pTo);
57145   return rc;
57146 }
57147 #endif /* SQLITE_OMIT_VACUUM */
57148 
57149 /************** End of backup.c **********************************************/
57150 /************** Begin file vdbemem.c *****************************************/
57151 /*
57152 ** 2004 May 26
57153 **
57154 ** The author disclaims copyright to this source code.  In place of
57155 ** a legal notice, here is a blessing:
57156 **
57157 **    May you do good and not evil.
57158 **    May you find forgiveness for yourself and forgive others.
57159 **    May you share freely, never taking more than you give.
57160 **
57161 *************************************************************************
57162 **
57163 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
57164 ** stores a single value in the VDBE.  Mem is an opaque structure visible
57165 ** only within the VDBE.  Interface routines refer to a Mem using the
57166 ** name sqlite_value
57167 */
57168 
57169 /*
57170 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
57171 ** P if required.
57172 */
57173 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
57174 
57175 /*
57176 ** If pMem is an object with a valid string representation, this routine
57177 ** ensures the internal encoding for the string representation is
57178 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
57179 **
57180 ** If pMem is not a string object, or the encoding of the string
57181 ** representation is already stored using the requested encoding, then this
57182 ** routine is a no-op.
57183 **
57184 ** SQLITE_OK is returned if the conversion is successful (or not required).
57185 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
57186 ** between formats.
57187 */
57188 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
57189   int rc;
57190   assert( (pMem->flags&MEM_RowSet)==0 );
57191   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
57192            || desiredEnc==SQLITE_UTF16BE );
57193   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
57194     return SQLITE_OK;
57195   }
57196   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57197 #ifdef SQLITE_OMIT_UTF16
57198   return SQLITE_ERROR;
57199 #else
57200 
57201   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
57202   ** then the encoding of the value may not have changed.
57203   */
57204   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
57205   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
57206   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
57207   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
57208   return rc;
57209 #endif
57210 }
57211 
57212 /*
57213 ** Make sure pMem->z points to a writable allocation of at least
57214 ** n bytes.
57215 **
57216 ** If the memory cell currently contains string or blob data
57217 ** and the third argument passed to this function is true, the
57218 ** current content of the cell is preserved. Otherwise, it may
57219 ** be discarded.
57220 **
57221 ** This function sets the MEM_Dyn flag and clears any xDel callback.
57222 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
57223 ** not set, Mem.n is zeroed.
57224 */
57225 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
57226   assert( 1 >=
57227     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
57228     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
57229     ((pMem->flags&MEM_Ephem) ? 1 : 0) +
57230     ((pMem->flags&MEM_Static) ? 1 : 0)
57231   );
57232   assert( (pMem->flags&MEM_RowSet)==0 );
57233 
57234   if( n<32 ) n = 32;
57235   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
57236     if( preserve && pMem->z==pMem->zMalloc ){
57237       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
57238       preserve = 0;
57239     }else{
57240       sqlite3DbFree(pMem->db, pMem->zMalloc);
57241       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
57242     }
57243   }
57244 
57245   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
57246     memcpy(pMem->zMalloc, pMem->z, pMem->n);
57247   }
57248   if( pMem->flags&MEM_Dyn && pMem->xDel ){
57249     pMem->xDel((void *)(pMem->z));
57250   }
57251 
57252   pMem->z = pMem->zMalloc;
57253   if( pMem->z==0 ){
57254     pMem->flags = MEM_Null;
57255   }else{
57256     pMem->flags &= ~(MEM_Ephem|MEM_Static);
57257   }
57258   pMem->xDel = 0;
57259   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
57260 }
57261 
57262 /*
57263 ** Make the given Mem object MEM_Dyn.  In other words, make it so
57264 ** that any TEXT or BLOB content is stored in memory obtained from
57265 ** malloc().  In this way, we know that the memory is safe to be
57266 ** overwritten or altered.
57267 **
57268 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
57269 */
57270 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
57271   int f;
57272   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57273   assert( (pMem->flags&MEM_RowSet)==0 );
57274   expandBlob(pMem);
57275   f = pMem->flags;
57276   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
57277     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
57278       return SQLITE_NOMEM;
57279     }
57280     pMem->z[pMem->n] = 0;
57281     pMem->z[pMem->n+1] = 0;
57282     pMem->flags |= MEM_Term;
57283 #ifdef SQLITE_DEBUG
57284     pMem->pScopyFrom = 0;
57285 #endif
57286   }
57287 
57288   return SQLITE_OK;
57289 }
57290 
57291 /*
57292 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
57293 ** blob stored in dynamically allocated space.
57294 */
57295 #ifndef SQLITE_OMIT_INCRBLOB
57296 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
57297   if( pMem->flags & MEM_Zero ){
57298     int nByte;
57299     assert( pMem->flags&MEM_Blob );
57300     assert( (pMem->flags&MEM_RowSet)==0 );
57301     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57302 
57303     /* Set nByte to the number of bytes required to store the expanded blob. */
57304     nByte = pMem->n + pMem->u.nZero;
57305     if( nByte<=0 ){
57306       nByte = 1;
57307     }
57308     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
57309       return SQLITE_NOMEM;
57310     }
57311 
57312     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
57313     pMem->n += pMem->u.nZero;
57314     pMem->flags &= ~(MEM_Zero|MEM_Term);
57315   }
57316   return SQLITE_OK;
57317 }
57318 #endif
57319 
57320 
57321 /*
57322 ** Make sure the given Mem is \u0000 terminated.
57323 */
57324 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
57325   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57326   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
57327     return SQLITE_OK;   /* Nothing to do */
57328   }
57329   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
57330     return SQLITE_NOMEM;
57331   }
57332   pMem->z[pMem->n] = 0;
57333   pMem->z[pMem->n+1] = 0;
57334   pMem->flags |= MEM_Term;
57335   return SQLITE_OK;
57336 }
57337 
57338 /*
57339 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
57340 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
57341 ** is a no-op.
57342 **
57343 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
57344 **
57345 ** A MEM_Null value will never be passed to this function. This function is
57346 ** used for converting values to text for returning to the user (i.e. via
57347 ** sqlite3_value_text()), or for ensuring that values to be used as btree
57348 ** keys are strings. In the former case a NULL pointer is returned the
57349 ** user and the later is an internal programming error.
57350 */
57351 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
57352   int rc = SQLITE_OK;
57353   int fg = pMem->flags;
57354   const int nByte = 32;
57355 
57356   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57357   assert( !(fg&MEM_Zero) );
57358   assert( !(fg&(MEM_Str|MEM_Blob)) );
57359   assert( fg&(MEM_Int|MEM_Real) );
57360   assert( (pMem->flags&MEM_RowSet)==0 );
57361   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57362 
57363 
57364   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
57365     return SQLITE_NOMEM;
57366   }
57367 
57368   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
57369   ** string representation of the value. Then, if the required encoding
57370   ** is UTF-16le or UTF-16be do a translation.
57371   **
57372   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
57373   */
57374   if( fg & MEM_Int ){
57375     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
57376   }else{
57377     assert( fg & MEM_Real );
57378     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
57379   }
57380   pMem->n = sqlite3Strlen30(pMem->z);
57381   pMem->enc = SQLITE_UTF8;
57382   pMem->flags |= MEM_Str|MEM_Term;
57383   sqlite3VdbeChangeEncoding(pMem, enc);
57384   return rc;
57385 }
57386 
57387 /*
57388 ** Memory cell pMem contains the context of an aggregate function.
57389 ** This routine calls the finalize method for that function.  The
57390 ** result of the aggregate is stored back into pMem.
57391 **
57392 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
57393 ** otherwise.
57394 */
57395 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
57396   int rc = SQLITE_OK;
57397   if( ALWAYS(pFunc && pFunc->xFinalize) ){
57398     sqlite3_context ctx;
57399     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
57400     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57401     memset(&ctx, 0, sizeof(ctx));
57402     ctx.s.flags = MEM_Null;
57403     ctx.s.db = pMem->db;
57404     ctx.pMem = pMem;
57405     ctx.pFunc = pFunc;
57406     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
57407     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
57408     sqlite3DbFree(pMem->db, pMem->zMalloc);
57409     memcpy(pMem, &ctx.s, sizeof(ctx.s));
57410     rc = ctx.isError;
57411   }
57412   return rc;
57413 }
57414 
57415 /*
57416 ** If the memory cell contains a string value that must be freed by
57417 ** invoking an external callback, free it now. Calling this function
57418 ** does not free any Mem.zMalloc buffer.
57419 */
57420 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
57421   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
57422   if( p->flags&MEM_Agg ){
57423     sqlite3VdbeMemFinalize(p, p->u.pDef);
57424     assert( (p->flags & MEM_Agg)==0 );
57425     sqlite3VdbeMemRelease(p);
57426   }else if( p->flags&MEM_Dyn && p->xDel ){
57427     assert( (p->flags&MEM_RowSet)==0 );
57428     p->xDel((void *)p->z);
57429     p->xDel = 0;
57430   }else if( p->flags&MEM_RowSet ){
57431     sqlite3RowSetClear(p->u.pRowSet);
57432   }else if( p->flags&MEM_Frame ){
57433     sqlite3VdbeMemSetNull(p);
57434   }
57435 }
57436 
57437 /*
57438 ** Release any memory held by the Mem. This may leave the Mem in an
57439 ** inconsistent state, for example with (Mem.z==0) and
57440 ** (Mem.type==SQLITE_TEXT).
57441 */
57442 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
57443   MemReleaseExt(p);
57444   sqlite3DbFree(p->db, p->zMalloc);
57445   p->z = 0;
57446   p->zMalloc = 0;
57447   p->xDel = 0;
57448 }
57449 
57450 /*
57451 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
57452 ** If the double is too large, return 0x8000000000000000.
57453 **
57454 ** Most systems appear to do this simply by assigning
57455 ** variables and without the extra range tests.  But
57456 ** there are reports that windows throws an expection
57457 ** if the floating point value is out of range. (See ticket #2880.)
57458 ** Because we do not completely understand the problem, we will
57459 ** take the conservative approach and always do range tests
57460 ** before attempting the conversion.
57461 */
57462 static i64 doubleToInt64(double r){
57463 #ifdef SQLITE_OMIT_FLOATING_POINT
57464   /* When floating-point is omitted, double and int64 are the same thing */
57465   return r;
57466 #else
57467   /*
57468   ** Many compilers we encounter do not define constants for the
57469   ** minimum and maximum 64-bit integers, or they define them
57470   ** inconsistently.  And many do not understand the "LL" notation.
57471   ** So we define our own static constants here using nothing
57472   ** larger than a 32-bit integer constant.
57473   */
57474   static const i64 maxInt = LARGEST_INT64;
57475   static const i64 minInt = SMALLEST_INT64;
57476 
57477   if( r<(double)minInt ){
57478     return minInt;
57479   }else if( r>(double)maxInt ){
57480     /* minInt is correct here - not maxInt.  It turns out that assigning
57481     ** a very large positive number to an integer results in a very large
57482     ** negative integer.  This makes no sense, but it is what x86 hardware
57483     ** does so for compatibility we will do the same in software. */
57484     return minInt;
57485   }else{
57486     return (i64)r;
57487   }
57488 #endif
57489 }
57490 
57491 /*
57492 ** Return some kind of integer value which is the best we can do
57493 ** at representing the value that *pMem describes as an integer.
57494 ** If pMem is an integer, then the value is exact.  If pMem is
57495 ** a floating-point then the value returned is the integer part.
57496 ** If pMem is a string or blob, then we make an attempt to convert
57497 ** it into a integer and return that.  If pMem represents an
57498 ** an SQL-NULL value, return 0.
57499 **
57500 ** If pMem represents a string value, its encoding might be changed.
57501 */
57502 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
57503   int flags;
57504   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57505   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57506   flags = pMem->flags;
57507   if( flags & MEM_Int ){
57508     return pMem->u.i;
57509   }else if( flags & MEM_Real ){
57510     return doubleToInt64(pMem->r);
57511   }else if( flags & (MEM_Str|MEM_Blob) ){
57512     i64 value = 0;
57513     assert( pMem->z || pMem->n==0 );
57514     testcase( pMem->z==0 );
57515     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
57516     return value;
57517   }else{
57518     return 0;
57519   }
57520 }
57521 
57522 /*
57523 ** Return the best representation of pMem that we can get into a
57524 ** double.  If pMem is already a double or an integer, return its
57525 ** value.  If it is a string or blob, try to convert it to a double.
57526 ** If it is a NULL, return 0.0.
57527 */
57528 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
57529   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57530   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57531   if( pMem->flags & MEM_Real ){
57532     return pMem->r;
57533   }else if( pMem->flags & MEM_Int ){
57534     return (double)pMem->u.i;
57535   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
57536     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57537     double val = (double)0;
57538     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
57539     return val;
57540   }else{
57541     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
57542     return (double)0;
57543   }
57544 }
57545 
57546 /*
57547 ** The MEM structure is already a MEM_Real.  Try to also make it a
57548 ** MEM_Int if we can.
57549 */
57550 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
57551   assert( pMem->flags & MEM_Real );
57552   assert( (pMem->flags & MEM_RowSet)==0 );
57553   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57554   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57555 
57556   pMem->u.i = doubleToInt64(pMem->r);
57557 
57558   /* Only mark the value as an integer if
57559   **
57560   **    (1) the round-trip conversion real->int->real is a no-op, and
57561   **    (2) The integer is neither the largest nor the smallest
57562   **        possible integer (ticket #3922)
57563   **
57564   ** The second and third terms in the following conditional enforces
57565   ** the second condition under the assumption that addition overflow causes
57566   ** values to wrap around.  On x86 hardware, the third term is always
57567   ** true and could be omitted.  But we leave it in because other
57568   ** architectures might behave differently.
57569   */
57570   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
57571       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
57572     pMem->flags |= MEM_Int;
57573   }
57574 }
57575 
57576 /*
57577 ** Convert pMem to type integer.  Invalidate any prior representations.
57578 */
57579 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
57580   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57581   assert( (pMem->flags & MEM_RowSet)==0 );
57582   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57583 
57584   pMem->u.i = sqlite3VdbeIntValue(pMem);
57585   MemSetTypeFlag(pMem, MEM_Int);
57586   return SQLITE_OK;
57587 }
57588 
57589 /*
57590 ** Convert pMem so that it is of type MEM_Real.
57591 ** Invalidate any prior representations.
57592 */
57593 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
57594   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57595   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
57596 
57597   pMem->r = sqlite3VdbeRealValue(pMem);
57598   MemSetTypeFlag(pMem, MEM_Real);
57599   return SQLITE_OK;
57600 }
57601 
57602 /*
57603 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
57604 ** Invalidate any prior representations.
57605 **
57606 ** Every effort is made to force the conversion, even if the input
57607 ** is a string that does not look completely like a number.  Convert
57608 ** as much of the string as we can and ignore the rest.
57609 */
57610 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
57611   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
57612     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
57613     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57614     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
57615       MemSetTypeFlag(pMem, MEM_Int);
57616     }else{
57617       pMem->r = sqlite3VdbeRealValue(pMem);
57618       MemSetTypeFlag(pMem, MEM_Real);
57619       sqlite3VdbeIntegerAffinity(pMem);
57620     }
57621   }
57622   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
57623   pMem->flags &= ~(MEM_Str|MEM_Blob);
57624   return SQLITE_OK;
57625 }
57626 
57627 /*
57628 ** Delete any previous value and set the value stored in *pMem to NULL.
57629 */
57630 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
57631   if( pMem->flags & MEM_Frame ){
57632     VdbeFrame *pFrame = pMem->u.pFrame;
57633     pFrame->pParent = pFrame->v->pDelFrame;
57634     pFrame->v->pDelFrame = pFrame;
57635   }
57636   if( pMem->flags & MEM_RowSet ){
57637     sqlite3RowSetClear(pMem->u.pRowSet);
57638   }
57639   MemSetTypeFlag(pMem, MEM_Null);
57640   pMem->type = SQLITE_NULL;
57641 }
57642 
57643 /*
57644 ** Delete any previous value and set the value to be a BLOB of length
57645 ** n containing all zeros.
57646 */
57647 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
57648   sqlite3VdbeMemRelease(pMem);
57649   pMem->flags = MEM_Blob|MEM_Zero;
57650   pMem->type = SQLITE_BLOB;
57651   pMem->n = 0;
57652   if( n<0 ) n = 0;
57653   pMem->u.nZero = n;
57654   pMem->enc = SQLITE_UTF8;
57655 
57656 #ifdef SQLITE_OMIT_INCRBLOB
57657   sqlite3VdbeMemGrow(pMem, n, 0);
57658   if( pMem->z ){
57659     pMem->n = n;
57660     memset(pMem->z, 0, n);
57661   }
57662 #endif
57663 }
57664 
57665 /*
57666 ** Delete any previous value and set the value stored in *pMem to val,
57667 ** manifest type INTEGER.
57668 */
57669 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
57670   sqlite3VdbeMemRelease(pMem);
57671   pMem->u.i = val;
57672   pMem->flags = MEM_Int;
57673   pMem->type = SQLITE_INTEGER;
57674 }
57675 
57676 #ifndef SQLITE_OMIT_FLOATING_POINT
57677 /*
57678 ** Delete any previous value and set the value stored in *pMem to val,
57679 ** manifest type REAL.
57680 */
57681 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
57682   if( sqlite3IsNaN(val) ){
57683     sqlite3VdbeMemSetNull(pMem);
57684   }else{
57685     sqlite3VdbeMemRelease(pMem);
57686     pMem->r = val;
57687     pMem->flags = MEM_Real;
57688     pMem->type = SQLITE_FLOAT;
57689   }
57690 }
57691 #endif
57692 
57693 /*
57694 ** Delete any previous value and set the value of pMem to be an
57695 ** empty boolean index.
57696 */
57697 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
57698   sqlite3 *db = pMem->db;
57699   assert( db!=0 );
57700   assert( (pMem->flags & MEM_RowSet)==0 );
57701   sqlite3VdbeMemRelease(pMem);
57702   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
57703   if( db->mallocFailed ){
57704     pMem->flags = MEM_Null;
57705   }else{
57706     assert( pMem->zMalloc );
57707     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
57708                                        sqlite3DbMallocSize(db, pMem->zMalloc));
57709     assert( pMem->u.pRowSet!=0 );
57710     pMem->flags = MEM_RowSet;
57711   }
57712 }
57713 
57714 /*
57715 ** Return true if the Mem object contains a TEXT or BLOB that is
57716 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
57717 */
57718 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
57719   assert( p->db!=0 );
57720   if( p->flags & (MEM_Str|MEM_Blob) ){
57721     int n = p->n;
57722     if( p->flags & MEM_Zero ){
57723       n += p->u.nZero;
57724     }
57725     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
57726   }
57727   return 0;
57728 }
57729 
57730 #ifdef SQLITE_DEBUG
57731 /*
57732 ** This routine prepares a memory cell for modication by breaking
57733 ** its link to a shallow copy and by marking any current shallow
57734 ** copies of this cell as invalid.
57735 **
57736 ** This is used for testing and debugging only - to make sure shallow
57737 ** copies are not misused.
57738 */
57739 SQLITE_PRIVATE void sqlite3VdbeMemPrepareToChange(Vdbe *pVdbe, Mem *pMem){
57740   int i;
57741   Mem *pX;
57742   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
57743     if( pX->pScopyFrom==pMem ){
57744       pX->flags |= MEM_Invalid;
57745       pX->pScopyFrom = 0;
57746     }
57747   }
57748   pMem->pScopyFrom = 0;
57749 }
57750 #endif /* SQLITE_DEBUG */
57751 
57752 /*
57753 ** Size of struct Mem not including the Mem.zMalloc member.
57754 */
57755 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
57756 
57757 /*
57758 ** Make an shallow copy of pFrom into pTo.  Prior contents of
57759 ** pTo are freed.  The pFrom->z field is not duplicated.  If
57760 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
57761 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
57762 */
57763 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
57764   assert( (pFrom->flags & MEM_RowSet)==0 );
57765   MemReleaseExt(pTo);
57766   memcpy(pTo, pFrom, MEMCELLSIZE);
57767   pTo->xDel = 0;
57768   if( (pFrom->flags&MEM_Static)==0 ){
57769     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
57770     assert( srcType==MEM_Ephem || srcType==MEM_Static );
57771     pTo->flags |= srcType;
57772   }
57773 }
57774 
57775 /*
57776 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
57777 ** freed before the copy is made.
57778 */
57779 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
57780   int rc = SQLITE_OK;
57781 
57782   assert( (pFrom->flags & MEM_RowSet)==0 );
57783   MemReleaseExt(pTo);
57784   memcpy(pTo, pFrom, MEMCELLSIZE);
57785   pTo->flags &= ~MEM_Dyn;
57786 
57787   if( pTo->flags&(MEM_Str|MEM_Blob) ){
57788     if( 0==(pFrom->flags&MEM_Static) ){
57789       pTo->flags |= MEM_Ephem;
57790       rc = sqlite3VdbeMemMakeWriteable(pTo);
57791     }
57792   }
57793 
57794   return rc;
57795 }
57796 
57797 /*
57798 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
57799 ** freed. If pFrom contains ephemeral data, a copy is made.
57800 **
57801 ** pFrom contains an SQL NULL when this routine returns.
57802 */
57803 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
57804   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
57805   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
57806   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
57807 
57808   sqlite3VdbeMemRelease(pTo);
57809   memcpy(pTo, pFrom, sizeof(Mem));
57810   pFrom->flags = MEM_Null;
57811   pFrom->xDel = 0;
57812   pFrom->zMalloc = 0;
57813 }
57814 
57815 /*
57816 ** Change the value of a Mem to be a string or a BLOB.
57817 **
57818 ** The memory management strategy depends on the value of the xDel
57819 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
57820 ** string is copied into a (possibly existing) buffer managed by the
57821 ** Mem structure. Otherwise, any existing buffer is freed and the
57822 ** pointer copied.
57823 **
57824 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
57825 ** size limit) then no memory allocation occurs.  If the string can be
57826 ** stored without allocating memory, then it is.  If a memory allocation
57827 ** is required to store the string, then value of pMem is unchanged.  In
57828 ** either case, SQLITE_TOOBIG is returned.
57829 */
57830 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
57831   Mem *pMem,          /* Memory cell to set to string value */
57832   const char *z,      /* String pointer */
57833   int n,              /* Bytes in string, or negative */
57834   u8 enc,             /* Encoding of z.  0 for BLOBs */
57835   void (*xDel)(void*) /* Destructor function */
57836 ){
57837   int nByte = n;      /* New value for pMem->n */
57838   int iLimit;         /* Maximum allowed string or blob size */
57839   u16 flags = 0;      /* New value for pMem->flags */
57840 
57841   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
57842   assert( (pMem->flags & MEM_RowSet)==0 );
57843 
57844   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
57845   if( !z ){
57846     sqlite3VdbeMemSetNull(pMem);
57847     return SQLITE_OK;
57848   }
57849 
57850   if( pMem->db ){
57851     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
57852   }else{
57853     iLimit = SQLITE_MAX_LENGTH;
57854   }
57855   flags = (enc==0?MEM_Blob:MEM_Str);
57856   if( nByte<0 ){
57857     assert( enc!=0 );
57858     if( enc==SQLITE_UTF8 ){
57859       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
57860     }else{
57861       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
57862     }
57863     flags |= MEM_Term;
57864   }
57865 
57866   /* The following block sets the new values of Mem.z and Mem.xDel. It
57867   ** also sets a flag in local variable "flags" to indicate the memory
57868   ** management (one of MEM_Dyn or MEM_Static).
57869   */
57870   if( xDel==SQLITE_TRANSIENT ){
57871     int nAlloc = nByte;
57872     if( flags&MEM_Term ){
57873       nAlloc += (enc==SQLITE_UTF8?1:2);
57874     }
57875     if( nByte>iLimit ){
57876       return SQLITE_TOOBIG;
57877     }
57878     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
57879       return SQLITE_NOMEM;
57880     }
57881     memcpy(pMem->z, z, nAlloc);
57882   }else if( xDel==SQLITE_DYNAMIC ){
57883     sqlite3VdbeMemRelease(pMem);
57884     pMem->zMalloc = pMem->z = (char *)z;
57885     pMem->xDel = 0;
57886   }else{
57887     sqlite3VdbeMemRelease(pMem);
57888     pMem->z = (char *)z;
57889     pMem->xDel = xDel;
57890     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
57891   }
57892 
57893   pMem->n = nByte;
57894   pMem->flags = flags;
57895   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
57896   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
57897 
57898 #ifndef SQLITE_OMIT_UTF16
57899   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
57900     return SQLITE_NOMEM;
57901   }
57902 #endif
57903 
57904   if( nByte>iLimit ){
57905     return SQLITE_TOOBIG;
57906   }
57907 
57908   return SQLITE_OK;
57909 }
57910 
57911 /*
57912 ** Compare the values contained by the two memory cells, returning
57913 ** negative, zero or positive if pMem1 is less than, equal to, or greater
57914 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
57915 ** and reals) sorted numerically, followed by text ordered by the collating
57916 ** sequence pColl and finally blob's ordered by memcmp().
57917 **
57918 ** Two NULL values are considered equal by this function.
57919 */
57920 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
57921   int rc;
57922   int f1, f2;
57923   int combined_flags;
57924 
57925   f1 = pMem1->flags;
57926   f2 = pMem2->flags;
57927   combined_flags = f1|f2;
57928   assert( (combined_flags & MEM_RowSet)==0 );
57929 
57930   /* If one value is NULL, it is less than the other. If both values
57931   ** are NULL, return 0.
57932   */
57933   if( combined_flags&MEM_Null ){
57934     return (f2&MEM_Null) - (f1&MEM_Null);
57935   }
57936 
57937   /* If one value is a number and the other is not, the number is less.
57938   ** If both are numbers, compare as reals if one is a real, or as integers
57939   ** if both values are integers.
57940   */
57941   if( combined_flags&(MEM_Int|MEM_Real) ){
57942     if( !(f1&(MEM_Int|MEM_Real)) ){
57943       return 1;
57944     }
57945     if( !(f2&(MEM_Int|MEM_Real)) ){
57946       return -1;
57947     }
57948     if( (f1 & f2 & MEM_Int)==0 ){
57949       double r1, r2;
57950       if( (f1&MEM_Real)==0 ){
57951         r1 = (double)pMem1->u.i;
57952       }else{
57953         r1 = pMem1->r;
57954       }
57955       if( (f2&MEM_Real)==0 ){
57956         r2 = (double)pMem2->u.i;
57957       }else{
57958         r2 = pMem2->r;
57959       }
57960       if( r1<r2 ) return -1;
57961       if( r1>r2 ) return 1;
57962       return 0;
57963     }else{
57964       assert( f1&MEM_Int );
57965       assert( f2&MEM_Int );
57966       if( pMem1->u.i < pMem2->u.i ) return -1;
57967       if( pMem1->u.i > pMem2->u.i ) return 1;
57968       return 0;
57969     }
57970   }
57971 
57972   /* If one value is a string and the other is a blob, the string is less.
57973   ** If both are strings, compare using the collating functions.
57974   */
57975   if( combined_flags&MEM_Str ){
57976     if( (f1 & MEM_Str)==0 ){
57977       return 1;
57978     }
57979     if( (f2 & MEM_Str)==0 ){
57980       return -1;
57981     }
57982 
57983     assert( pMem1->enc==pMem2->enc );
57984     assert( pMem1->enc==SQLITE_UTF8 ||
57985             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
57986 
57987     /* The collation sequence must be defined at this point, even if
57988     ** the user deletes the collation sequence after the vdbe program is
57989     ** compiled (this was not always the case).
57990     */
57991     assert( !pColl || pColl->xCmp );
57992 
57993     if( pColl ){
57994       if( pMem1->enc==pColl->enc ){
57995         /* The strings are already in the correct encoding.  Call the
57996         ** comparison function directly */
57997         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
57998       }else{
57999         const void *v1, *v2;
58000         int n1, n2;
58001         Mem c1;
58002         Mem c2;
58003         memset(&c1, 0, sizeof(c1));
58004         memset(&c2, 0, sizeof(c2));
58005         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
58006         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
58007         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
58008         n1 = v1==0 ? 0 : c1.n;
58009         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
58010         n2 = v2==0 ? 0 : c2.n;
58011         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
58012         sqlite3VdbeMemRelease(&c1);
58013         sqlite3VdbeMemRelease(&c2);
58014         return rc;
58015       }
58016     }
58017     /* If a NULL pointer was passed as the collate function, fall through
58018     ** to the blob case and use memcmp().  */
58019   }
58020 
58021   /* Both values must be blobs.  Compare using memcmp().  */
58022   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
58023   if( rc==0 ){
58024     rc = pMem1->n - pMem2->n;
58025   }
58026   return rc;
58027 }
58028 
58029 /*
58030 ** Move data out of a btree key or data field and into a Mem structure.
58031 ** The data or key is taken from the entry that pCur is currently pointing
58032 ** to.  offset and amt determine what portion of the data or key to retrieve.
58033 ** key is true to get the key or false to get data.  The result is written
58034 ** into the pMem element.
58035 **
58036 ** The pMem structure is assumed to be uninitialized.  Any prior content
58037 ** is overwritten without being freed.
58038 **
58039 ** If this routine fails for any reason (malloc returns NULL or unable
58040 ** to read from the disk) then the pMem is left in an inconsistent state.
58041 */
58042 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
58043   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
58044   int offset,       /* Offset from the start of data to return bytes from. */
58045   int amt,          /* Number of bytes to return. */
58046   int key,          /* If true, retrieve from the btree key, not data. */
58047   Mem *pMem         /* OUT: Return data in this Mem structure. */
58048 ){
58049   char *zData;        /* Data from the btree layer */
58050   int available = 0;  /* Number of bytes available on the local btree page */
58051   int rc = SQLITE_OK; /* Return code */
58052 
58053   assert( sqlite3BtreeCursorIsValid(pCur) );
58054 
58055   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
58056   ** that both the BtShared and database handle mutexes are held. */
58057   assert( (pMem->flags & MEM_RowSet)==0 );
58058   if( key ){
58059     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
58060   }else{
58061     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
58062   }
58063   assert( zData!=0 );
58064 
58065   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
58066     sqlite3VdbeMemRelease(pMem);
58067     pMem->z = &zData[offset];
58068     pMem->flags = MEM_Blob|MEM_Ephem;
58069   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
58070     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
58071     pMem->enc = 0;
58072     pMem->type = SQLITE_BLOB;
58073     if( key ){
58074       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
58075     }else{
58076       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
58077     }
58078     pMem->z[amt] = 0;
58079     pMem->z[amt+1] = 0;
58080     if( rc!=SQLITE_OK ){
58081       sqlite3VdbeMemRelease(pMem);
58082     }
58083   }
58084   pMem->n = amt;
58085 
58086   return rc;
58087 }
58088 
58089 /* This function is only available internally, it is not part of the
58090 ** external API. It works in a similar way to sqlite3_value_text(),
58091 ** except the data returned is in the encoding specified by the second
58092 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
58093 ** SQLITE_UTF8.
58094 **
58095 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
58096 ** If that is the case, then the result must be aligned on an even byte
58097 ** boundary.
58098 */
58099 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
58100   if( !pVal ) return 0;
58101 
58102   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
58103   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
58104   assert( (pVal->flags & MEM_RowSet)==0 );
58105 
58106   if( pVal->flags&MEM_Null ){
58107     return 0;
58108   }
58109   assert( (MEM_Blob>>3) == MEM_Str );
58110   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
58111   expandBlob(pVal);
58112   if( pVal->flags&MEM_Str ){
58113     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
58114     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
58115       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
58116       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
58117         return 0;
58118       }
58119     }
58120     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-59893-45467 */
58121   }else{
58122     assert( (pVal->flags&MEM_Blob)==0 );
58123     sqlite3VdbeMemStringify(pVal, enc);
58124     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
58125   }
58126   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
58127               || pVal->db->mallocFailed );
58128   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
58129     return pVal->z;
58130   }else{
58131     return 0;
58132   }
58133 }
58134 
58135 /*
58136 ** Create a new sqlite3_value object.
58137 */
58138 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
58139   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
58140   if( p ){
58141     p->flags = MEM_Null;
58142     p->type = SQLITE_NULL;
58143     p->db = db;
58144   }
58145   return p;
58146 }
58147 
58148 /*
58149 ** Create a new sqlite3_value object, containing the value of pExpr.
58150 **
58151 ** This only works for very simple expressions that consist of one constant
58152 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
58153 ** be converted directly into a value, then the value is allocated and
58154 ** a pointer written to *ppVal. The caller is responsible for deallocating
58155 ** the value by passing it to sqlite3ValueFree() later on. If the expression
58156 ** cannot be converted to a value, then *ppVal is set to NULL.
58157 */
58158 SQLITE_PRIVATE int sqlite3ValueFromExpr(
58159   sqlite3 *db,              /* The database connection */
58160   Expr *pExpr,              /* The expression to evaluate */
58161   u8 enc,                   /* Encoding to use */
58162   u8 affinity,              /* Affinity to use */
58163   sqlite3_value **ppVal     /* Write the new value here */
58164 ){
58165   int op;
58166   char *zVal = 0;
58167   sqlite3_value *pVal = 0;
58168   int negInt = 1;
58169   const char *zNeg = "";
58170 
58171   if( !pExpr ){
58172     *ppVal = 0;
58173     return SQLITE_OK;
58174   }
58175   op = pExpr->op;
58176 
58177   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT2.
58178   ** The ifdef here is to enable us to achieve 100% branch test coverage even
58179   ** when SQLITE_ENABLE_STAT2 is omitted.
58180   */
58181 #ifdef SQLITE_ENABLE_STAT2
58182   if( op==TK_REGISTER ) op = pExpr->op2;
58183 #else
58184   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
58185 #endif
58186 
58187   /* Handle negative integers in a single step.  This is needed in the
58188   ** case when the value is -9223372036854775808.
58189   */
58190   if( op==TK_UMINUS
58191    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
58192     pExpr = pExpr->pLeft;
58193     op = pExpr->op;
58194     negInt = -1;
58195     zNeg = "-";
58196   }
58197 
58198   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
58199     pVal = sqlite3ValueNew(db);
58200     if( pVal==0 ) goto no_mem;
58201     if( ExprHasProperty(pExpr, EP_IntValue) ){
58202       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
58203     }else{
58204       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
58205       if( zVal==0 ) goto no_mem;
58206       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
58207       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
58208     }
58209     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
58210       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
58211     }else{
58212       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
58213     }
58214     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
58215     if( enc!=SQLITE_UTF8 ){
58216       sqlite3VdbeChangeEncoding(pVal, enc);
58217     }
58218   }else if( op==TK_UMINUS ) {
58219     /* This branch happens for multiple negative signs.  Ex: -(-5) */
58220     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
58221       sqlite3VdbeMemNumerify(pVal);
58222       if( pVal->u.i==SMALLEST_INT64 ){
58223         pVal->flags &= MEM_Int;
58224         pVal->flags |= MEM_Real;
58225         pVal->r = (double)LARGEST_INT64;
58226       }else{
58227         pVal->u.i = -pVal->u.i;
58228       }
58229       pVal->r = -pVal->r;
58230       sqlite3ValueApplyAffinity(pVal, affinity, enc);
58231     }
58232   }else if( op==TK_NULL ){
58233     pVal = sqlite3ValueNew(db);
58234     if( pVal==0 ) goto no_mem;
58235   }
58236 #ifndef SQLITE_OMIT_BLOB_LITERAL
58237   else if( op==TK_BLOB ){
58238     int nVal;
58239     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
58240     assert( pExpr->u.zToken[1]=='\'' );
58241     pVal = sqlite3ValueNew(db);
58242     if( !pVal ) goto no_mem;
58243     zVal = &pExpr->u.zToken[2];
58244     nVal = sqlite3Strlen30(zVal)-1;
58245     assert( zVal[nVal]=='\'' );
58246     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
58247                          0, SQLITE_DYNAMIC);
58248   }
58249 #endif
58250 
58251   if( pVal ){
58252     sqlite3VdbeMemStoreType(pVal);
58253   }
58254   *ppVal = pVal;
58255   return SQLITE_OK;
58256 
58257 no_mem:
58258   db->mallocFailed = 1;
58259   sqlite3DbFree(db, zVal);
58260   sqlite3ValueFree(pVal);
58261   *ppVal = 0;
58262   return SQLITE_NOMEM;
58263 }
58264 
58265 /*
58266 ** Change the string value of an sqlite3_value object
58267 */
58268 SQLITE_PRIVATE void sqlite3ValueSetStr(
58269   sqlite3_value *v,     /* Value to be set */
58270   int n,                /* Length of string z */
58271   const void *z,        /* Text of the new string */
58272   u8 enc,               /* Encoding to use */
58273   void (*xDel)(void*)   /* Destructor for the string */
58274 ){
58275   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
58276 }
58277 
58278 /*
58279 ** Free an sqlite3_value object
58280 */
58281 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
58282   if( !v ) return;
58283   sqlite3VdbeMemRelease((Mem *)v);
58284   sqlite3DbFree(((Mem*)v)->db, v);
58285 }
58286 
58287 /*
58288 ** Return the number of bytes in the sqlite3_value object assuming
58289 ** that it uses the encoding "enc"
58290 */
58291 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
58292   Mem *p = (Mem*)pVal;
58293   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
58294     if( p->flags & MEM_Zero ){
58295       return p->n + p->u.nZero;
58296     }else{
58297       return p->n;
58298     }
58299   }
58300   return 0;
58301 }
58302 
58303 /************** End of vdbemem.c *********************************************/
58304 /************** Begin file vdbeaux.c *****************************************/
58305 /*
58306 ** 2003 September 6
58307 **
58308 ** The author disclaims copyright to this source code.  In place of
58309 ** a legal notice, here is a blessing:
58310 **
58311 **    May you do good and not evil.
58312 **    May you find forgiveness for yourself and forgive others.
58313 **    May you share freely, never taking more than you give.
58314 **
58315 *************************************************************************
58316 ** This file contains code used for creating, destroying, and populating
58317 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
58318 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
58319 ** But that file was getting too big so this subroutines were split out.
58320 */
58321 
58322 
58323 
58324 /*
58325 ** When debugging the code generator in a symbolic debugger, one can
58326 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
58327 ** as they are added to the instruction stream.
58328 */
58329 #ifdef SQLITE_DEBUG
58330 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
58331 #endif
58332 
58333 
58334 /*
58335 ** Create a new virtual database engine.
58336 */
58337 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
58338   Vdbe *p;
58339   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
58340   if( p==0 ) return 0;
58341   p->db = db;
58342   if( db->pVdbe ){
58343     db->pVdbe->pPrev = p;
58344   }
58345   p->pNext = db->pVdbe;
58346   p->pPrev = 0;
58347   db->pVdbe = p;
58348   p->magic = VDBE_MAGIC_INIT;
58349   return p;
58350 }
58351 
58352 /*
58353 ** Remember the SQL string for a prepared statement.
58354 */
58355 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
58356   assert( isPrepareV2==1 || isPrepareV2==0 );
58357   if( p==0 ) return;
58358 #ifdef SQLITE_OMIT_TRACE
58359   if( !isPrepareV2 ) return;
58360 #endif
58361   assert( p->zSql==0 );
58362   p->zSql = sqlite3DbStrNDup(p->db, z, n);
58363   p->isPrepareV2 = (u8)isPrepareV2;
58364 }
58365 
58366 /*
58367 ** Return the SQL associated with a prepared statement
58368 */
58369 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
58370   Vdbe *p = (Vdbe *)pStmt;
58371   return (p && p->isPrepareV2) ? p->zSql : 0;
58372 }
58373 
58374 /*
58375 ** Swap all content between two VDBE structures.
58376 */
58377 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
58378   Vdbe tmp, *pTmp;
58379   char *zTmp;
58380   tmp = *pA;
58381   *pA = *pB;
58382   *pB = tmp;
58383   pTmp = pA->pNext;
58384   pA->pNext = pB->pNext;
58385   pB->pNext = pTmp;
58386   pTmp = pA->pPrev;
58387   pA->pPrev = pB->pPrev;
58388   pB->pPrev = pTmp;
58389   zTmp = pA->zSql;
58390   pA->zSql = pB->zSql;
58391   pB->zSql = zTmp;
58392   pB->isPrepareV2 = pA->isPrepareV2;
58393 }
58394 
58395 #ifdef SQLITE_DEBUG
58396 /*
58397 ** Turn tracing on or off
58398 */
58399 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
58400   p->trace = trace;
58401 }
58402 #endif
58403 
58404 /*
58405 ** Resize the Vdbe.aOp array so that it is at least one op larger than
58406 ** it was.
58407 **
58408 ** If an out-of-memory error occurs while resizing the array, return
58409 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
58410 ** unchanged (this is so that any opcodes already allocated can be
58411 ** correctly deallocated along with the rest of the Vdbe).
58412 */
58413 static int growOpArray(Vdbe *p){
58414   VdbeOp *pNew;
58415   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
58416   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
58417   if( pNew ){
58418     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
58419     p->aOp = pNew;
58420   }
58421   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
58422 }
58423 
58424 /*
58425 ** Add a new instruction to the list of instructions current in the
58426 ** VDBE.  Return the address of the new instruction.
58427 **
58428 ** Parameters:
58429 **
58430 **    p               Pointer to the VDBE
58431 **
58432 **    op              The opcode for this instruction
58433 **
58434 **    p1, p2, p3      Operands
58435 **
58436 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
58437 ** the sqlite3VdbeChangeP4() function to change the value of the P4
58438 ** operand.
58439 */
58440 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
58441   int i;
58442   VdbeOp *pOp;
58443 
58444   i = p->nOp;
58445   assert( p->magic==VDBE_MAGIC_INIT );
58446   assert( op>0 && op<0xff );
58447   if( p->nOpAlloc<=i ){
58448     if( growOpArray(p) ){
58449       return 1;
58450     }
58451   }
58452   p->nOp++;
58453   pOp = &p->aOp[i];
58454   pOp->opcode = (u8)op;
58455   pOp->p5 = 0;
58456   pOp->p1 = p1;
58457   pOp->p2 = p2;
58458   pOp->p3 = p3;
58459   pOp->p4.p = 0;
58460   pOp->p4type = P4_NOTUSED;
58461 #ifdef SQLITE_DEBUG
58462   pOp->zComment = 0;
58463   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
58464 #endif
58465 #ifdef VDBE_PROFILE
58466   pOp->cycles = 0;
58467   pOp->cnt = 0;
58468 #endif
58469   return i;
58470 }
58471 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
58472   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
58473 }
58474 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
58475   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
58476 }
58477 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
58478   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
58479 }
58480 
58481 
58482 /*
58483 ** Add an opcode that includes the p4 value as a pointer.
58484 */
58485 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
58486   Vdbe *p,            /* Add the opcode to this VM */
58487   int op,             /* The new opcode */
58488   int p1,             /* The P1 operand */
58489   int p2,             /* The P2 operand */
58490   int p3,             /* The P3 operand */
58491   const char *zP4,    /* The P4 operand */
58492   int p4type          /* P4 operand type */
58493 ){
58494   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58495   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
58496   return addr;
58497 }
58498 
58499 /*
58500 ** Add an OP_ParseSchema opcode.  This routine is broken out from
58501 ** sqlite3VdbeAddOp4() since it needs to also local all btrees.
58502 **
58503 ** The zWhere string must have been obtained from sqlite3_malloc().
58504 ** This routine will take ownership of the allocated memory.
58505 */
58506 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
58507   int j;
58508   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
58509   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
58510   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
58511 }
58512 
58513 /*
58514 ** Add an opcode that includes the p4 value as an integer.
58515 */
58516 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
58517   Vdbe *p,            /* Add the opcode to this VM */
58518   int op,             /* The new opcode */
58519   int p1,             /* The P1 operand */
58520   int p2,             /* The P2 operand */
58521   int p3,             /* The P3 operand */
58522   int p4              /* The P4 operand as an integer */
58523 ){
58524   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
58525   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
58526   return addr;
58527 }
58528 
58529 /*
58530 ** Create a new symbolic label for an instruction that has yet to be
58531 ** coded.  The symbolic label is really just a negative number.  The
58532 ** label can be used as the P2 value of an operation.  Later, when
58533 ** the label is resolved to a specific address, the VDBE will scan
58534 ** through its operation list and change all values of P2 which match
58535 ** the label into the resolved address.
58536 **
58537 ** The VDBE knows that a P2 value is a label because labels are
58538 ** always negative and P2 values are suppose to be non-negative.
58539 ** Hence, a negative P2 value is a label that has yet to be resolved.
58540 **
58541 ** Zero is returned if a malloc() fails.
58542 */
58543 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
58544   int i;
58545   i = p->nLabel++;
58546   assert( p->magic==VDBE_MAGIC_INIT );
58547   if( i>=p->nLabelAlloc ){
58548     int n = p->nLabelAlloc*2 + 5;
58549     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
58550                                        n*sizeof(p->aLabel[0]));
58551     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
58552   }
58553   if( p->aLabel ){
58554     p->aLabel[i] = -1;
58555   }
58556   return -1-i;
58557 }
58558 
58559 /*
58560 ** Resolve label "x" to be the address of the next instruction to
58561 ** be inserted.  The parameter "x" must have been obtained from
58562 ** a prior call to sqlite3VdbeMakeLabel().
58563 */
58564 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
58565   int j = -1-x;
58566   assert( p->magic==VDBE_MAGIC_INIT );
58567   assert( j>=0 && j<p->nLabel );
58568   if( p->aLabel ){
58569     p->aLabel[j] = p->nOp;
58570   }
58571 }
58572 
58573 /*
58574 ** Mark the VDBE as one that can only be run one time.
58575 */
58576 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
58577   p->runOnlyOnce = 1;
58578 }
58579 
58580 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
58581 
58582 /*
58583 ** The following type and function are used to iterate through all opcodes
58584 ** in a Vdbe main program and each of the sub-programs (triggers) it may
58585 ** invoke directly or indirectly. It should be used as follows:
58586 **
58587 **   Op *pOp;
58588 **   VdbeOpIter sIter;
58589 **
58590 **   memset(&sIter, 0, sizeof(sIter));
58591 **   sIter.v = v;                            // v is of type Vdbe*
58592 **   while( (pOp = opIterNext(&sIter)) ){
58593 **     // Do something with pOp
58594 **   }
58595 **   sqlite3DbFree(v->db, sIter.apSub);
58596 **
58597 */
58598 typedef struct VdbeOpIter VdbeOpIter;
58599 struct VdbeOpIter {
58600   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
58601   SubProgram **apSub;        /* Array of subprograms */
58602   int nSub;                  /* Number of entries in apSub */
58603   int iAddr;                 /* Address of next instruction to return */
58604   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
58605 };
58606 static Op *opIterNext(VdbeOpIter *p){
58607   Vdbe *v = p->v;
58608   Op *pRet = 0;
58609   Op *aOp;
58610   int nOp;
58611 
58612   if( p->iSub<=p->nSub ){
58613 
58614     if( p->iSub==0 ){
58615       aOp = v->aOp;
58616       nOp = v->nOp;
58617     }else{
58618       aOp = p->apSub[p->iSub-1]->aOp;
58619       nOp = p->apSub[p->iSub-1]->nOp;
58620     }
58621     assert( p->iAddr<nOp );
58622 
58623     pRet = &aOp[p->iAddr];
58624     p->iAddr++;
58625     if( p->iAddr==nOp ){
58626       p->iSub++;
58627       p->iAddr = 0;
58628     }
58629 
58630     if( pRet->p4type==P4_SUBPROGRAM ){
58631       int nByte = (p->nSub+1)*sizeof(SubProgram*);
58632       int j;
58633       for(j=0; j<p->nSub; j++){
58634         if( p->apSub[j]==pRet->p4.pProgram ) break;
58635       }
58636       if( j==p->nSub ){
58637         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
58638         if( !p->apSub ){
58639           pRet = 0;
58640         }else{
58641           p->apSub[p->nSub++] = pRet->p4.pProgram;
58642         }
58643       }
58644     }
58645   }
58646 
58647   return pRet;
58648 }
58649 
58650 /*
58651 ** Check if the program stored in the VM associated with pParse may
58652 ** throw an ABORT exception (causing the statement, but not entire transaction
58653 ** to be rolled back). This condition is true if the main program or any
58654 ** sub-programs contains any of the following:
58655 **
58656 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58657 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
58658 **   *  OP_Destroy
58659 **   *  OP_VUpdate
58660 **   *  OP_VRename
58661 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
58662 **
58663 ** Then check that the value of Parse.mayAbort is true if an
58664 ** ABORT may be thrown, or false otherwise. Return true if it does
58665 ** match, or false otherwise. This function is intended to be used as
58666 ** part of an assert statement in the compiler. Similar to:
58667 **
58668 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
58669 */
58670 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
58671   int hasAbort = 0;
58672   Op *pOp;
58673   VdbeOpIter sIter;
58674   memset(&sIter, 0, sizeof(sIter));
58675   sIter.v = v;
58676 
58677   while( (pOp = opIterNext(&sIter))!=0 ){
58678     int opcode = pOp->opcode;
58679     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
58680 #ifndef SQLITE_OMIT_FOREIGN_KEY
58681      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
58682 #endif
58683      || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
58684       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
58685     ){
58686       hasAbort = 1;
58687       break;
58688     }
58689   }
58690   sqlite3DbFree(v->db, sIter.apSub);
58691 
58692   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
58693   ** If malloc failed, then the while() loop above may not have iterated
58694   ** through all opcodes and hasAbort may be set incorrectly. Return
58695   ** true for this case to prevent the assert() in the callers frame
58696   ** from failing.  */
58697   return ( v->db->mallocFailed || hasAbort==mayAbort );
58698 }
58699 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
58700 
58701 /*
58702 ** Loop through the program looking for P2 values that are negative
58703 ** on jump instructions.  Each such value is a label.  Resolve the
58704 ** label by setting the P2 value to its correct non-zero value.
58705 **
58706 ** This routine is called once after all opcodes have been inserted.
58707 **
58708 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
58709 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
58710 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
58711 **
58712 ** The Op.opflags field is set on all opcodes.
58713 */
58714 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
58715   int i;
58716   int nMaxArgs = *pMaxFuncArgs;
58717   Op *pOp;
58718   int *aLabel = p->aLabel;
58719   p->readOnly = 1;
58720   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
58721     u8 opcode = pOp->opcode;
58722 
58723     pOp->opflags = sqlite3OpcodeProperty[opcode];
58724     if( opcode==OP_Function || opcode==OP_AggStep ){
58725       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
58726     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
58727       p->readOnly = 0;
58728 #ifndef SQLITE_OMIT_VIRTUALTABLE
58729     }else if( opcode==OP_VUpdate ){
58730       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
58731     }else if( opcode==OP_VFilter ){
58732       int n;
58733       assert( p->nOp - i >= 3 );
58734       assert( pOp[-1].opcode==OP_Integer );
58735       n = pOp[-1].p1;
58736       if( n>nMaxArgs ) nMaxArgs = n;
58737 #endif
58738     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
58739       pOp->p4.xAdvance = sqlite3BtreeNext;
58740       pOp->p4type = P4_ADVANCE;
58741     }else if( opcode==OP_Prev ){
58742       pOp->p4.xAdvance = sqlite3BtreePrevious;
58743       pOp->p4type = P4_ADVANCE;
58744     }
58745 
58746     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
58747       assert( -1-pOp->p2<p->nLabel );
58748       pOp->p2 = aLabel[-1-pOp->p2];
58749     }
58750   }
58751   sqlite3DbFree(p->db, p->aLabel);
58752   p->aLabel = 0;
58753 
58754   *pMaxFuncArgs = nMaxArgs;
58755 }
58756 
58757 /*
58758 ** Return the address of the next instruction to be inserted.
58759 */
58760 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
58761   assert( p->magic==VDBE_MAGIC_INIT );
58762   return p->nOp;
58763 }
58764 
58765 /*
58766 ** This function returns a pointer to the array of opcodes associated with
58767 ** the Vdbe passed as the first argument. It is the callers responsibility
58768 ** to arrange for the returned array to be eventually freed using the
58769 ** vdbeFreeOpArray() function.
58770 **
58771 ** Before returning, *pnOp is set to the number of entries in the returned
58772 ** array. Also, *pnMaxArg is set to the larger of its current value and
58773 ** the number of entries in the Vdbe.apArg[] array required to execute the
58774 ** returned program.
58775 */
58776 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
58777   VdbeOp *aOp = p->aOp;
58778   assert( aOp && !p->db->mallocFailed );
58779 
58780   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
58781   assert( p->btreeMask==0 );
58782 
58783   resolveP2Values(p, pnMaxArg);
58784   *pnOp = p->nOp;
58785   p->aOp = 0;
58786   return aOp;
58787 }
58788 
58789 /*
58790 ** Add a whole list of operations to the operation stack.  Return the
58791 ** address of the first operation added.
58792 */
58793 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
58794   int addr;
58795   assert( p->magic==VDBE_MAGIC_INIT );
58796   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
58797     return 0;
58798   }
58799   addr = p->nOp;
58800   if( ALWAYS(nOp>0) ){
58801     int i;
58802     VdbeOpList const *pIn = aOp;
58803     for(i=0; i<nOp; i++, pIn++){
58804       int p2 = pIn->p2;
58805       VdbeOp *pOut = &p->aOp[i+addr];
58806       pOut->opcode = pIn->opcode;
58807       pOut->p1 = pIn->p1;
58808       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
58809         pOut->p2 = addr + ADDR(p2);
58810       }else{
58811         pOut->p2 = p2;
58812       }
58813       pOut->p3 = pIn->p3;
58814       pOut->p4type = P4_NOTUSED;
58815       pOut->p4.p = 0;
58816       pOut->p5 = 0;
58817 #ifdef SQLITE_DEBUG
58818       pOut->zComment = 0;
58819       if( sqlite3VdbeAddopTrace ){
58820         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
58821       }
58822 #endif
58823     }
58824     p->nOp += nOp;
58825   }
58826   return addr;
58827 }
58828 
58829 /*
58830 ** Change the value of the P1 operand for a specific instruction.
58831 ** This routine is useful when a large program is loaded from a
58832 ** static array using sqlite3VdbeAddOpList but we want to make a
58833 ** few minor changes to the program.
58834 */
58835 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
58836   assert( p!=0 );
58837   if( ((u32)p->nOp)>addr ){
58838     p->aOp[addr].p1 = val;
58839   }
58840 }
58841 
58842 /*
58843 ** Change the value of the P2 operand for a specific instruction.
58844 ** This routine is useful for setting a jump destination.
58845 */
58846 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
58847   assert( p!=0 );
58848   if( ((u32)p->nOp)>addr ){
58849     p->aOp[addr].p2 = val;
58850   }
58851 }
58852 
58853 /*
58854 ** Change the value of the P3 operand for a specific instruction.
58855 */
58856 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
58857   assert( p!=0 );
58858   if( ((u32)p->nOp)>addr ){
58859     p->aOp[addr].p3 = val;
58860   }
58861 }
58862 
58863 /*
58864 ** Change the value of the P5 operand for the most recently
58865 ** added operation.
58866 */
58867 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
58868   assert( p!=0 );
58869   if( p->aOp ){
58870     assert( p->nOp>0 );
58871     p->aOp[p->nOp-1].p5 = val;
58872   }
58873 }
58874 
58875 /*
58876 ** Change the P2 operand of instruction addr so that it points to
58877 ** the address of the next instruction to be coded.
58878 */
58879 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
58880   assert( addr>=0 );
58881   sqlite3VdbeChangeP2(p, addr, p->nOp);
58882 }
58883 
58884 
58885 /*
58886 ** If the input FuncDef structure is ephemeral, then free it.  If
58887 ** the FuncDef is not ephermal, then do nothing.
58888 */
58889 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
58890   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
58891     sqlite3DbFree(db, pDef);
58892   }
58893 }
58894 
58895 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
58896 
58897 /*
58898 ** Delete a P4 value if necessary.
58899 */
58900 static void freeP4(sqlite3 *db, int p4type, void *p4){
58901   if( p4 ){
58902     assert( db );
58903     switch( p4type ){
58904       case P4_REAL:
58905       case P4_INT64:
58906       case P4_DYNAMIC:
58907       case P4_KEYINFO:
58908       case P4_INTARRAY:
58909       case P4_KEYINFO_HANDOFF: {
58910         sqlite3DbFree(db, p4);
58911         break;
58912       }
58913       case P4_MPRINTF: {
58914         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
58915         break;
58916       }
58917       case P4_VDBEFUNC: {
58918         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
58919         freeEphemeralFunction(db, pVdbeFunc->pFunc);
58920         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
58921         sqlite3DbFree(db, pVdbeFunc);
58922         break;
58923       }
58924       case P4_FUNCDEF: {
58925         freeEphemeralFunction(db, (FuncDef*)p4);
58926         break;
58927       }
58928       case P4_MEM: {
58929         if( db->pnBytesFreed==0 ){
58930           sqlite3ValueFree((sqlite3_value*)p4);
58931         }else{
58932           Mem *p = (Mem*)p4;
58933           sqlite3DbFree(db, p->zMalloc);
58934           sqlite3DbFree(db, p);
58935         }
58936         break;
58937       }
58938       case P4_VTAB : {
58939         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
58940         break;
58941       }
58942     }
58943   }
58944 }
58945 
58946 /*
58947 ** Free the space allocated for aOp and any p4 values allocated for the
58948 ** opcodes contained within. If aOp is not NULL it is assumed to contain
58949 ** nOp entries.
58950 */
58951 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
58952   if( aOp ){
58953     Op *pOp;
58954     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
58955       freeP4(db, pOp->p4type, pOp->p4.p);
58956 #ifdef SQLITE_DEBUG
58957       sqlite3DbFree(db, pOp->zComment);
58958 #endif
58959     }
58960   }
58961   sqlite3DbFree(db, aOp);
58962 }
58963 
58964 /*
58965 ** Link the SubProgram object passed as the second argument into the linked
58966 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
58967 ** objects when the VM is no longer required.
58968 */
58969 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
58970   p->pNext = pVdbe->pProgram;
58971   pVdbe->pProgram = p;
58972 }
58973 
58974 /*
58975 ** Change the opcode at addr into OP_Noop
58976 */
58977 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
58978   if( p->aOp ){
58979     VdbeOp *pOp = &p->aOp[addr];
58980     sqlite3 *db = p->db;
58981     freeP4(db, pOp->p4type, pOp->p4.p);
58982     memset(pOp, 0, sizeof(pOp[0]));
58983     pOp->opcode = OP_Noop;
58984   }
58985 }
58986 
58987 /*
58988 ** Change the value of the P4 operand for a specific instruction.
58989 ** This routine is useful when a large program is loaded from a
58990 ** static array using sqlite3VdbeAddOpList but we want to make a
58991 ** few minor changes to the program.
58992 **
58993 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
58994 ** the string is made into memory obtained from sqlite3_malloc().
58995 ** A value of n==0 means copy bytes of zP4 up to and including the
58996 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
58997 **
58998 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
58999 ** A copy is made of the KeyInfo structure into memory obtained from
59000 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
59001 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
59002 ** stored in memory that the caller has obtained from sqlite3_malloc. The
59003 ** caller should not free the allocation, it will be freed when the Vdbe is
59004 ** finalized.
59005 **
59006 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
59007 ** to a string or structure that is guaranteed to exist for the lifetime of
59008 ** the Vdbe. In these cases we can just copy the pointer.
59009 **
59010 ** If addr<0 then change P4 on the most recently inserted instruction.
59011 */
59012 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
59013   Op *pOp;
59014   sqlite3 *db;
59015   assert( p!=0 );
59016   db = p->db;
59017   assert( p->magic==VDBE_MAGIC_INIT );
59018   if( p->aOp==0 || db->mallocFailed ){
59019     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
59020       freeP4(db, n, (void*)*(char**)&zP4);
59021     }
59022     return;
59023   }
59024   assert( p->nOp>0 );
59025   assert( addr<p->nOp );
59026   if( addr<0 ){
59027     addr = p->nOp - 1;
59028   }
59029   pOp = &p->aOp[addr];
59030   freeP4(db, pOp->p4type, pOp->p4.p);
59031   pOp->p4.p = 0;
59032   if( n==P4_INT32 ){
59033     /* Note: this cast is safe, because the origin data point was an int
59034     ** that was cast to a (const char *). */
59035     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
59036     pOp->p4type = P4_INT32;
59037   }else if( zP4==0 ){
59038     pOp->p4.p = 0;
59039     pOp->p4type = P4_NOTUSED;
59040   }else if( n==P4_KEYINFO ){
59041     KeyInfo *pKeyInfo;
59042     int nField, nByte;
59043 
59044     nField = ((KeyInfo*)zP4)->nField;
59045     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
59046     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
59047     pOp->p4.pKeyInfo = pKeyInfo;
59048     if( pKeyInfo ){
59049       u8 *aSortOrder;
59050       memcpy((char*)pKeyInfo, zP4, nByte - nField);
59051       aSortOrder = pKeyInfo->aSortOrder;
59052       if( aSortOrder ){
59053         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
59054         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
59055       }
59056       pOp->p4type = P4_KEYINFO;
59057     }else{
59058       p->db->mallocFailed = 1;
59059       pOp->p4type = P4_NOTUSED;
59060     }
59061   }else if( n==P4_KEYINFO_HANDOFF ){
59062     pOp->p4.p = (void*)zP4;
59063     pOp->p4type = P4_KEYINFO;
59064   }else if( n==P4_VTAB ){
59065     pOp->p4.p = (void*)zP4;
59066     pOp->p4type = P4_VTAB;
59067     sqlite3VtabLock((VTable *)zP4);
59068     assert( ((VTable *)zP4)->db==p->db );
59069   }else if( n<0 ){
59070     pOp->p4.p = (void*)zP4;
59071     pOp->p4type = (signed char)n;
59072   }else{
59073     if( n==0 ) n = sqlite3Strlen30(zP4);
59074     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
59075     pOp->p4type = P4_DYNAMIC;
59076   }
59077 }
59078 
59079 #ifndef NDEBUG
59080 /*
59081 ** Change the comment on the the most recently coded instruction.  Or
59082 ** insert a No-op and add the comment to that new instruction.  This
59083 ** makes the code easier to read during debugging.  None of this happens
59084 ** in a production build.
59085 */
59086 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
59087   va_list ap;
59088   if( !p ) return;
59089   assert( p->nOp>0 || p->aOp==0 );
59090   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
59091   if( p->nOp ){
59092     char **pz = &p->aOp[p->nOp-1].zComment;
59093     va_start(ap, zFormat);
59094     sqlite3DbFree(p->db, *pz);
59095     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
59096     va_end(ap);
59097   }
59098 }
59099 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
59100   va_list ap;
59101   if( !p ) return;
59102   sqlite3VdbeAddOp0(p, OP_Noop);
59103   assert( p->nOp>0 || p->aOp==0 );
59104   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
59105   if( p->nOp ){
59106     char **pz = &p->aOp[p->nOp-1].zComment;
59107     va_start(ap, zFormat);
59108     sqlite3DbFree(p->db, *pz);
59109     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
59110     va_end(ap);
59111   }
59112 }
59113 #endif  /* NDEBUG */
59114 
59115 /*
59116 ** Return the opcode for a given address.  If the address is -1, then
59117 ** return the most recently inserted opcode.
59118 **
59119 ** If a memory allocation error has occurred prior to the calling of this
59120 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
59121 ** is readable but not writable, though it is cast to a writable value.
59122 ** The return of a dummy opcode allows the call to continue functioning
59123 ** after a OOM fault without having to check to see if the return from
59124 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
59125 ** dummy will never be written to.  This is verified by code inspection and
59126 ** by running with Valgrind.
59127 **
59128 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
59129 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
59130 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
59131 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
59132 ** having to double-check to make sure that the result is non-negative. But
59133 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
59134 ** check the value of p->nOp-1 before continuing.
59135 */
59136 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
59137   /* C89 specifies that the constant "dummy" will be initialized to all
59138   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
59139   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
59140   assert( p->magic==VDBE_MAGIC_INIT );
59141   if( addr<0 ){
59142 #ifdef SQLITE_OMIT_TRACE
59143     if( p->nOp==0 ) return (VdbeOp*)&dummy;
59144 #endif
59145     addr = p->nOp - 1;
59146   }
59147   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
59148   if( p->db->mallocFailed ){
59149     return (VdbeOp*)&dummy;
59150   }else{
59151     return &p->aOp[addr];
59152   }
59153 }
59154 
59155 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
59156      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59157 /*
59158 ** Compute a string that describes the P4 parameter for an opcode.
59159 ** Use zTemp for any required temporary buffer space.
59160 */
59161 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
59162   char *zP4 = zTemp;
59163   assert( nTemp>=20 );
59164   switch( pOp->p4type ){
59165     case P4_KEYINFO_STATIC:
59166     case P4_KEYINFO: {
59167       int i, j;
59168       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
59169       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
59170       i = sqlite3Strlen30(zTemp);
59171       for(j=0; j<pKeyInfo->nField; j++){
59172         CollSeq *pColl = pKeyInfo->aColl[j];
59173         if( pColl ){
59174           int n = sqlite3Strlen30(pColl->zName);
59175           if( i+n>nTemp-6 ){
59176             memcpy(&zTemp[i],",...",4);
59177             break;
59178           }
59179           zTemp[i++] = ',';
59180           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
59181             zTemp[i++] = '-';
59182           }
59183           memcpy(&zTemp[i], pColl->zName,n+1);
59184           i += n;
59185         }else if( i+4<nTemp-6 ){
59186           memcpy(&zTemp[i],",nil",4);
59187           i += 4;
59188         }
59189       }
59190       zTemp[i++] = ')';
59191       zTemp[i] = 0;
59192       assert( i<nTemp );
59193       break;
59194     }
59195     case P4_COLLSEQ: {
59196       CollSeq *pColl = pOp->p4.pColl;
59197       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
59198       break;
59199     }
59200     case P4_FUNCDEF: {
59201       FuncDef *pDef = pOp->p4.pFunc;
59202       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
59203       break;
59204     }
59205     case P4_INT64: {
59206       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
59207       break;
59208     }
59209     case P4_INT32: {
59210       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
59211       break;
59212     }
59213     case P4_REAL: {
59214       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
59215       break;
59216     }
59217     case P4_MEM: {
59218       Mem *pMem = pOp->p4.pMem;
59219       assert( (pMem->flags & MEM_Null)==0 );
59220       if( pMem->flags & MEM_Str ){
59221         zP4 = pMem->z;
59222       }else if( pMem->flags & MEM_Int ){
59223         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
59224       }else if( pMem->flags & MEM_Real ){
59225         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
59226       }else{
59227         assert( pMem->flags & MEM_Blob );
59228         zP4 = "(blob)";
59229       }
59230       break;
59231     }
59232 #ifndef SQLITE_OMIT_VIRTUALTABLE
59233     case P4_VTAB: {
59234       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
59235       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
59236       break;
59237     }
59238 #endif
59239     case P4_INTARRAY: {
59240       sqlite3_snprintf(nTemp, zTemp, "intarray");
59241       break;
59242     }
59243     case P4_SUBPROGRAM: {
59244       sqlite3_snprintf(nTemp, zTemp, "program");
59245       break;
59246     }
59247     case P4_ADVANCE: {
59248       zTemp[0] = 0;
59249       break;
59250     }
59251     default: {
59252       zP4 = pOp->p4.z;
59253       if( zP4==0 ){
59254         zP4 = zTemp;
59255         zTemp[0] = 0;
59256       }
59257     }
59258   }
59259   assert( zP4!=0 );
59260   return zP4;
59261 }
59262 #endif
59263 
59264 /*
59265 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
59266 **
59267 ** The prepared statements need to know in advance the complete set of
59268 ** attached databases that they will be using.  A mask of these databases
59269 ** is maintained in p->btreeMask and is used for locking and other purposes.
59270 */
59271 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
59272   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
59273   assert( i<(int)sizeof(p->btreeMask)*8 );
59274   p->btreeMask |= ((yDbMask)1)<<i;
59275   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
59276     p->lockMask |= ((yDbMask)1)<<i;
59277   }
59278 }
59279 
59280 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59281 /*
59282 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
59283 ** this routine obtains the mutex associated with each BtShared structure
59284 ** that may be accessed by the VM passed as an argument. In doing so it also
59285 ** sets the BtShared.db member of each of the BtShared structures, ensuring
59286 ** that the correct busy-handler callback is invoked if required.
59287 **
59288 ** If SQLite is not threadsafe but does support shared-cache mode, then
59289 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
59290 ** of all of BtShared structures accessible via the database handle
59291 ** associated with the VM.
59292 **
59293 ** If SQLite is not threadsafe and does not support shared-cache mode, this
59294 ** function is a no-op.
59295 **
59296 ** The p->btreeMask field is a bitmask of all btrees that the prepared
59297 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
59298 ** corresponding to btrees that use shared cache.  Then the runtime of
59299 ** this routine is N*N.  But as N is rarely more than 1, this should not
59300 ** be a problem.
59301 */
59302 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
59303   int i;
59304   yDbMask mask;
59305   sqlite3 *db;
59306   Db *aDb;
59307   int nDb;
59308   if( p->lockMask==0 ) return;  /* The common case */
59309   db = p->db;
59310   aDb = db->aDb;
59311   nDb = db->nDb;
59312   for(i=0, mask=1; i<nDb; i++, mask += mask){
59313     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59314       sqlite3BtreeEnter(aDb[i].pBt);
59315     }
59316   }
59317 }
59318 #endif
59319 
59320 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
59321 /*
59322 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
59323 */
59324 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
59325   int i;
59326   yDbMask mask;
59327   sqlite3 *db;
59328   Db *aDb;
59329   int nDb;
59330   if( p->lockMask==0 ) return;  /* The common case */
59331   db = p->db;
59332   aDb = db->aDb;
59333   nDb = db->nDb;
59334   for(i=0, mask=1; i<nDb; i++, mask += mask){
59335     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
59336       sqlite3BtreeLeave(aDb[i].pBt);
59337     }
59338   }
59339 }
59340 #endif
59341 
59342 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
59343 /*
59344 ** Print a single opcode.  This routine is used for debugging only.
59345 */
59346 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
59347   char *zP4;
59348   char zPtr[50];
59349   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
59350   if( pOut==0 ) pOut = stdout;
59351   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
59352   fprintf(pOut, zFormat1, pc,
59353       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
59354 #ifdef SQLITE_DEBUG
59355       pOp->zComment ? pOp->zComment : ""
59356 #else
59357       ""
59358 #endif
59359   );
59360   fflush(pOut);
59361 }
59362 #endif
59363 
59364 /*
59365 ** Release an array of N Mem elements
59366 */
59367 static void releaseMemArray(Mem *p, int N){
59368   if( p && N ){
59369     Mem *pEnd;
59370     sqlite3 *db = p->db;
59371     u8 malloc_failed = db->mallocFailed;
59372     if( db->pnBytesFreed ){
59373       for(pEnd=&p[N]; p<pEnd; p++){
59374         sqlite3DbFree(db, p->zMalloc);
59375       }
59376       return;
59377     }
59378     for(pEnd=&p[N]; p<pEnd; p++){
59379       assert( (&p[1])==pEnd || p[0].db==p[1].db );
59380 
59381       /* This block is really an inlined version of sqlite3VdbeMemRelease()
59382       ** that takes advantage of the fact that the memory cell value is
59383       ** being set to NULL after releasing any dynamic resources.
59384       **
59385       ** The justification for duplicating code is that according to
59386       ** callgrind, this causes a certain test case to hit the CPU 4.7
59387       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
59388       ** sqlite3MemRelease() were called from here. With -O2, this jumps
59389       ** to 6.6 percent. The test case is inserting 1000 rows into a table
59390       ** with no indexes using a single prepared INSERT statement, bind()
59391       ** and reset(). Inserts are grouped into a transaction.
59392       */
59393       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
59394         sqlite3VdbeMemRelease(p);
59395       }else if( p->zMalloc ){
59396         sqlite3DbFree(db, p->zMalloc);
59397         p->zMalloc = 0;
59398       }
59399 
59400       p->flags = MEM_Null;
59401     }
59402     db->mallocFailed = malloc_failed;
59403   }
59404 }
59405 
59406 /*
59407 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
59408 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
59409 */
59410 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
59411   int i;
59412   Mem *aMem = VdbeFrameMem(p);
59413   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
59414   for(i=0; i<p->nChildCsr; i++){
59415     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
59416   }
59417   releaseMemArray(aMem, p->nChildMem);
59418   sqlite3DbFree(p->v->db, p);
59419 }
59420 
59421 #ifndef SQLITE_OMIT_EXPLAIN
59422 /*
59423 ** Give a listing of the program in the virtual machine.
59424 **
59425 ** The interface is the same as sqlite3VdbeExec().  But instead of
59426 ** running the code, it invokes the callback once for each instruction.
59427 ** This feature is used to implement "EXPLAIN".
59428 **
59429 ** When p->explain==1, each instruction is listed.  When
59430 ** p->explain==2, only OP_Explain instructions are listed and these
59431 ** are shown in a different format.  p->explain==2 is used to implement
59432 ** EXPLAIN QUERY PLAN.
59433 **
59434 ** When p->explain==1, first the main program is listed, then each of
59435 ** the trigger subprograms are listed one by one.
59436 */
59437 SQLITE_PRIVATE int sqlite3VdbeList(
59438   Vdbe *p                   /* The VDBE */
59439 ){
59440   int nRow;                            /* Stop when row count reaches this */
59441   int nSub = 0;                        /* Number of sub-vdbes seen so far */
59442   SubProgram **apSub = 0;              /* Array of sub-vdbes */
59443   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
59444   sqlite3 *db = p->db;                 /* The database connection */
59445   int i;                               /* Loop counter */
59446   int rc = SQLITE_OK;                  /* Return code */
59447   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
59448 
59449   assert( p->explain );
59450   assert( p->magic==VDBE_MAGIC_RUN );
59451   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
59452 
59453   /* Even though this opcode does not use dynamic strings for
59454   ** the result, result columns may become dynamic if the user calls
59455   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
59456   */
59457   releaseMemArray(pMem, 8);
59458 
59459   if( p->rc==SQLITE_NOMEM ){
59460     /* This happens if a malloc() inside a call to sqlite3_column_text() or
59461     ** sqlite3_column_text16() failed.  */
59462     db->mallocFailed = 1;
59463     return SQLITE_ERROR;
59464   }
59465 
59466   /* When the number of output rows reaches nRow, that means the
59467   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
59468   ** nRow is the sum of the number of rows in the main program, plus
59469   ** the sum of the number of rows in all trigger subprograms encountered
59470   ** so far.  The nRow value will increase as new trigger subprograms are
59471   ** encountered, but p->pc will eventually catch up to nRow.
59472   */
59473   nRow = p->nOp;
59474   if( p->explain==1 ){
59475     /* The first 8 memory cells are used for the result set.  So we will
59476     ** commandeer the 9th cell to use as storage for an array of pointers
59477     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
59478     ** cells.  */
59479     assert( p->nMem>9 );
59480     pSub = &p->aMem[9];
59481     if( pSub->flags&MEM_Blob ){
59482       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
59483       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
59484       nSub = pSub->n/sizeof(Vdbe*);
59485       apSub = (SubProgram **)pSub->z;
59486     }
59487     for(i=0; i<nSub; i++){
59488       nRow += apSub[i]->nOp;
59489     }
59490   }
59491 
59492   do{
59493     i = p->pc++;
59494   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
59495   if( i>=nRow ){
59496     p->rc = SQLITE_OK;
59497     rc = SQLITE_DONE;
59498   }else if( db->u1.isInterrupted ){
59499     p->rc = SQLITE_INTERRUPT;
59500     rc = SQLITE_ERROR;
59501     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
59502   }else{
59503     char *z;
59504     Op *pOp;
59505     if( i<p->nOp ){
59506       /* The output line number is small enough that we are still in the
59507       ** main program. */
59508       pOp = &p->aOp[i];
59509     }else{
59510       /* We are currently listing subprograms.  Figure out which one and
59511       ** pick up the appropriate opcode. */
59512       int j;
59513       i -= p->nOp;
59514       for(j=0; i>=apSub[j]->nOp; j++){
59515         i -= apSub[j]->nOp;
59516       }
59517       pOp = &apSub[j]->aOp[i];
59518     }
59519     if( p->explain==1 ){
59520       pMem->flags = MEM_Int;
59521       pMem->type = SQLITE_INTEGER;
59522       pMem->u.i = i;                                /* Program counter */
59523       pMem++;
59524 
59525       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
59526       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
59527       assert( pMem->z!=0 );
59528       pMem->n = sqlite3Strlen30(pMem->z);
59529       pMem->type = SQLITE_TEXT;
59530       pMem->enc = SQLITE_UTF8;
59531       pMem++;
59532 
59533       /* When an OP_Program opcode is encounter (the only opcode that has
59534       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
59535       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
59536       ** has not already been seen.
59537       */
59538       if( pOp->p4type==P4_SUBPROGRAM ){
59539         int nByte = (nSub+1)*sizeof(SubProgram*);
59540         int j;
59541         for(j=0; j<nSub; j++){
59542           if( apSub[j]==pOp->p4.pProgram ) break;
59543         }
59544         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
59545           apSub = (SubProgram **)pSub->z;
59546           apSub[nSub++] = pOp->p4.pProgram;
59547           pSub->flags |= MEM_Blob;
59548           pSub->n = nSub*sizeof(SubProgram*);
59549         }
59550       }
59551     }
59552 
59553     pMem->flags = MEM_Int;
59554     pMem->u.i = pOp->p1;                          /* P1 */
59555     pMem->type = SQLITE_INTEGER;
59556     pMem++;
59557 
59558     pMem->flags = MEM_Int;
59559     pMem->u.i = pOp->p2;                          /* P2 */
59560     pMem->type = SQLITE_INTEGER;
59561     pMem++;
59562 
59563     pMem->flags = MEM_Int;
59564     pMem->u.i = pOp->p3;                          /* P3 */
59565     pMem->type = SQLITE_INTEGER;
59566     pMem++;
59567 
59568     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
59569       assert( p->db->mallocFailed );
59570       return SQLITE_ERROR;
59571     }
59572     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59573     z = displayP4(pOp, pMem->z, 32);
59574     if( z!=pMem->z ){
59575       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
59576     }else{
59577       assert( pMem->z!=0 );
59578       pMem->n = sqlite3Strlen30(pMem->z);
59579       pMem->enc = SQLITE_UTF8;
59580     }
59581     pMem->type = SQLITE_TEXT;
59582     pMem++;
59583 
59584     if( p->explain==1 ){
59585       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
59586         assert( p->db->mallocFailed );
59587         return SQLITE_ERROR;
59588       }
59589       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
59590       pMem->n = 2;
59591       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
59592       pMem->type = SQLITE_TEXT;
59593       pMem->enc = SQLITE_UTF8;
59594       pMem++;
59595 
59596 #ifdef SQLITE_DEBUG
59597       if( pOp->zComment ){
59598         pMem->flags = MEM_Str|MEM_Term;
59599         pMem->z = pOp->zComment;
59600         pMem->n = sqlite3Strlen30(pMem->z);
59601         pMem->enc = SQLITE_UTF8;
59602         pMem->type = SQLITE_TEXT;
59603       }else
59604 #endif
59605       {
59606         pMem->flags = MEM_Null;                       /* Comment */
59607         pMem->type = SQLITE_NULL;
59608       }
59609     }
59610 
59611     p->nResColumn = 8 - 4*(p->explain-1);
59612     p->rc = SQLITE_OK;
59613     rc = SQLITE_ROW;
59614   }
59615   return rc;
59616 }
59617 #endif /* SQLITE_OMIT_EXPLAIN */
59618 
59619 #ifdef SQLITE_DEBUG
59620 /*
59621 ** Print the SQL that was used to generate a VDBE program.
59622 */
59623 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
59624   int nOp = p->nOp;
59625   VdbeOp *pOp;
59626   if( nOp<1 ) return;
59627   pOp = &p->aOp[0];
59628   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59629     const char *z = pOp->p4.z;
59630     while( sqlite3Isspace(*z) ) z++;
59631     printf("SQL: [%s]\n", z);
59632   }
59633 }
59634 #endif
59635 
59636 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
59637 /*
59638 ** Print an IOTRACE message showing SQL content.
59639 */
59640 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
59641   int nOp = p->nOp;
59642   VdbeOp *pOp;
59643   if( sqlite3IoTrace==0 ) return;
59644   if( nOp<1 ) return;
59645   pOp = &p->aOp[0];
59646   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
59647     int i, j;
59648     char z[1000];
59649     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
59650     for(i=0; sqlite3Isspace(z[i]); i++){}
59651     for(j=0; z[i]; i++){
59652       if( sqlite3Isspace(z[i]) ){
59653         if( z[i-1]!=' ' ){
59654           z[j++] = ' ';
59655         }
59656       }else{
59657         z[j++] = z[i];
59658       }
59659     }
59660     z[j] = 0;
59661     sqlite3IoTrace("SQL %s\n", z);
59662   }
59663 }
59664 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
59665 
59666 /*
59667 ** Allocate space from a fixed size buffer and return a pointer to
59668 ** that space.  If insufficient space is available, return NULL.
59669 **
59670 ** The pBuf parameter is the initial value of a pointer which will
59671 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
59672 ** NULL, it means that memory space has already been allocated and that
59673 ** this routine should not allocate any new memory.  When pBuf is not
59674 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
59675 ** is NULL.
59676 **
59677 ** nByte is the number of bytes of space needed.
59678 **
59679 ** *ppFrom points to available space and pEnd points to the end of the
59680 ** available space.  When space is allocated, *ppFrom is advanced past
59681 ** the end of the allocated space.
59682 **
59683 ** *pnByte is a counter of the number of bytes of space that have failed
59684 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
59685 ** request, then increment *pnByte by the amount of the request.
59686 */
59687 static void *allocSpace(
59688   void *pBuf,          /* Where return pointer will be stored */
59689   int nByte,           /* Number of bytes to allocate */
59690   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
59691   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
59692   int *pnByte          /* If allocation cannot be made, increment *pnByte */
59693 ){
59694   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
59695   if( pBuf ) return pBuf;
59696   nByte = ROUND8(nByte);
59697   if( &(*ppFrom)[nByte] <= pEnd ){
59698     pBuf = (void*)*ppFrom;
59699     *ppFrom += nByte;
59700   }else{
59701     *pnByte += nByte;
59702   }
59703   return pBuf;
59704 }
59705 
59706 /*
59707 ** Rewind the VDBE back to the beginning in preparation for
59708 ** running it.
59709 */
59710 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
59711 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
59712   int i;
59713 #endif
59714   assert( p!=0 );
59715   assert( p->magic==VDBE_MAGIC_INIT );
59716 
59717   /* There should be at least one opcode.
59718   */
59719   assert( p->nOp>0 );
59720 
59721   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
59722   p->magic = VDBE_MAGIC_RUN;
59723 
59724 #ifdef SQLITE_DEBUG
59725   for(i=1; i<p->nMem; i++){
59726     assert( p->aMem[i].db==p->db );
59727   }
59728 #endif
59729   p->pc = -1;
59730   p->rc = SQLITE_OK;
59731   p->errorAction = OE_Abort;
59732   p->magic = VDBE_MAGIC_RUN;
59733   p->nChange = 0;
59734   p->cacheCtr = 1;
59735   p->minWriteFileFormat = 255;
59736   p->iStatement = 0;
59737   p->nFkConstraint = 0;
59738 #ifdef VDBE_PROFILE
59739   for(i=0; i<p->nOp; i++){
59740     p->aOp[i].cnt = 0;
59741     p->aOp[i].cycles = 0;
59742   }
59743 #endif
59744 }
59745 
59746 /*
59747 ** Prepare a virtual machine for execution for the first time after
59748 ** creating the virtual machine.  This involves things such
59749 ** as allocating stack space and initializing the program counter.
59750 ** After the VDBE has be prepped, it can be executed by one or more
59751 ** calls to sqlite3VdbeExec().
59752 **
59753 ** This function may be called exact once on a each virtual machine.
59754 ** After this routine is called the VM has been "packaged" and is ready
59755 ** to run.  After this routine is called, futher calls to
59756 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
59757 ** the Vdbe from the Parse object that helped generate it so that the
59758 ** the Vdbe becomes an independent entity and the Parse object can be
59759 ** destroyed.
59760 **
59761 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
59762 ** to its initial state after it has been run.
59763 */
59764 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
59765   Vdbe *p,                       /* The VDBE */
59766   Parse *pParse                  /* Parsing context */
59767 ){
59768   sqlite3 *db;                   /* The database connection */
59769   int nVar;                      /* Number of parameters */
59770   int nMem;                      /* Number of VM memory registers */
59771   int nCursor;                   /* Number of cursors required */
59772   int nArg;                      /* Number of arguments in subprograms */
59773   int n;                         /* Loop counter */
59774   u8 *zCsr;                      /* Memory available for allocation */
59775   u8 *zEnd;                      /* First byte past allocated memory */
59776   int nByte;                     /* How much extra memory is needed */
59777 
59778   assert( p!=0 );
59779   assert( p->nOp>0 );
59780   assert( pParse!=0 );
59781   assert( p->magic==VDBE_MAGIC_INIT );
59782   db = p->db;
59783   assert( db->mallocFailed==0 );
59784   nVar = pParse->nVar;
59785   nMem = pParse->nMem;
59786   nCursor = pParse->nTab;
59787   nArg = pParse->nMaxArg;
59788 
59789   /* For each cursor required, also allocate a memory cell. Memory
59790   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
59791   ** the vdbe program. Instead they are used to allocate space for
59792   ** VdbeCursor/BtCursor structures. The blob of memory associated with
59793   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
59794   ** stores the blob of memory associated with cursor 1, etc.
59795   **
59796   ** See also: allocateCursor().
59797   */
59798   nMem += nCursor;
59799 
59800   /* Allocate space for memory registers, SQL variables, VDBE cursors and
59801   ** an array to marshal SQL function arguments in.
59802   */
59803   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
59804   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
59805 
59806   resolveP2Values(p, &nArg);
59807   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
59808   if( pParse->explain && nMem<10 ){
59809     nMem = 10;
59810   }
59811   memset(zCsr, 0, zEnd-zCsr);
59812   zCsr += (zCsr - (u8*)0)&7;
59813   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
59814   p->expired = 0;
59815 
59816   /* Memory for registers, parameters, cursor, etc, is allocated in two
59817   ** passes.  On the first pass, we try to reuse unused space at the
59818   ** end of the opcode array.  If we are unable to satisfy all memory
59819   ** requirements by reusing the opcode array tail, then the second
59820   ** pass will fill in the rest using a fresh allocation.
59821   **
59822   ** This two-pass approach that reuses as much memory as possible from
59823   ** the leftover space at the end of the opcode array can significantly
59824   ** reduce the amount of memory held by a prepared statement.
59825   */
59826   do {
59827     nByte = 0;
59828     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
59829     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
59830     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
59831     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
59832     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
59833                           &zCsr, zEnd, &nByte);
59834     if( nByte ){
59835       p->pFree = sqlite3DbMallocZero(db, nByte);
59836     }
59837     zCsr = p->pFree;
59838     zEnd = &zCsr[nByte];
59839   }while( nByte && !db->mallocFailed );
59840 
59841   p->nCursor = (u16)nCursor;
59842   if( p->aVar ){
59843     p->nVar = (ynVar)nVar;
59844     for(n=0; n<nVar; n++){
59845       p->aVar[n].flags = MEM_Null;
59846       p->aVar[n].db = db;
59847     }
59848   }
59849   if( p->azVar ){
59850     p->nzVar = pParse->nzVar;
59851     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
59852     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
59853   }
59854   if( p->aMem ){
59855     p->aMem--;                      /* aMem[] goes from 1..nMem */
59856     p->nMem = nMem;                 /*       not from 0..nMem-1 */
59857     for(n=1; n<=nMem; n++){
59858       p->aMem[n].flags = MEM_Null;
59859       p->aMem[n].db = db;
59860     }
59861   }
59862   p->explain = pParse->explain;
59863   sqlite3VdbeRewind(p);
59864 }
59865 
59866 /*
59867 ** Close a VDBE cursor and release all the resources that cursor
59868 ** happens to hold.
59869 */
59870 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
59871   if( pCx==0 ){
59872     return;
59873   }
59874   sqlite3VdbeSorterClose(p->db, pCx);
59875   if( pCx->pBt ){
59876     sqlite3BtreeClose(pCx->pBt);
59877     /* The pCx->pCursor will be close automatically, if it exists, by
59878     ** the call above. */
59879   }else if( pCx->pCursor ){
59880     sqlite3BtreeCloseCursor(pCx->pCursor);
59881   }
59882 #ifndef SQLITE_OMIT_VIRTUALTABLE
59883   if( pCx->pVtabCursor ){
59884     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
59885     const sqlite3_module *pModule = pCx->pModule;
59886     p->inVtabMethod = 1;
59887     pModule->xClose(pVtabCursor);
59888     p->inVtabMethod = 0;
59889   }
59890 #endif
59891 }
59892 
59893 /*
59894 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
59895 ** is used, for example, when a trigger sub-program is halted to restore
59896 ** control to the main program.
59897 */
59898 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
59899   Vdbe *v = pFrame->v;
59900   v->aOp = pFrame->aOp;
59901   v->nOp = pFrame->nOp;
59902   v->aMem = pFrame->aMem;
59903   v->nMem = pFrame->nMem;
59904   v->apCsr = pFrame->apCsr;
59905   v->nCursor = pFrame->nCursor;
59906   v->db->lastRowid = pFrame->lastRowid;
59907   v->nChange = pFrame->nChange;
59908   return pFrame->pc;
59909 }
59910 
59911 /*
59912 ** Close all cursors.
59913 **
59914 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
59915 ** cell array. This is necessary as the memory cell array may contain
59916 ** pointers to VdbeFrame objects, which may in turn contain pointers to
59917 ** open cursors.
59918 */
59919 static void closeAllCursors(Vdbe *p){
59920   if( p->pFrame ){
59921     VdbeFrame *pFrame;
59922     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
59923     sqlite3VdbeFrameRestore(pFrame);
59924   }
59925   p->pFrame = 0;
59926   p->nFrame = 0;
59927 
59928   if( p->apCsr ){
59929     int i;
59930     for(i=0; i<p->nCursor; i++){
59931       VdbeCursor *pC = p->apCsr[i];
59932       if( pC ){
59933         sqlite3VdbeFreeCursor(p, pC);
59934         p->apCsr[i] = 0;
59935       }
59936     }
59937   }
59938   if( p->aMem ){
59939     releaseMemArray(&p->aMem[1], p->nMem);
59940   }
59941   while( p->pDelFrame ){
59942     VdbeFrame *pDel = p->pDelFrame;
59943     p->pDelFrame = pDel->pParent;
59944     sqlite3VdbeFrameDelete(pDel);
59945   }
59946 }
59947 
59948 /*
59949 ** Clean up the VM after execution.
59950 **
59951 ** This routine will automatically close any cursors, lists, and/or
59952 ** sorters that were left open.  It also deletes the values of
59953 ** variables in the aVar[] array.
59954 */
59955 static void Cleanup(Vdbe *p){
59956   sqlite3 *db = p->db;
59957 
59958 #ifdef SQLITE_DEBUG
59959   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
59960   ** Vdbe.aMem[] arrays have already been cleaned up.  */
59961   int i;
59962   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
59963   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
59964 #endif
59965 
59966   sqlite3DbFree(db, p->zErrMsg);
59967   p->zErrMsg = 0;
59968   p->pResultSet = 0;
59969 }
59970 
59971 /*
59972 ** Set the number of result columns that will be returned by this SQL
59973 ** statement. This is now set at compile time, rather than during
59974 ** execution of the vdbe program so that sqlite3_column_count() can
59975 ** be called on an SQL statement before sqlite3_step().
59976 */
59977 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
59978   Mem *pColName;
59979   int n;
59980   sqlite3 *db = p->db;
59981 
59982   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
59983   sqlite3DbFree(db, p->aColName);
59984   n = nResColumn*COLNAME_N;
59985   p->nResColumn = (u16)nResColumn;
59986   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
59987   if( p->aColName==0 ) return;
59988   while( n-- > 0 ){
59989     pColName->flags = MEM_Null;
59990     pColName->db = p->db;
59991     pColName++;
59992   }
59993 }
59994 
59995 /*
59996 ** Set the name of the idx'th column to be returned by the SQL statement.
59997 ** zName must be a pointer to a nul terminated string.
59998 **
59999 ** This call must be made after a call to sqlite3VdbeSetNumCols().
60000 **
60001 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
60002 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
60003 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
60004 */
60005 SQLITE_PRIVATE int sqlite3VdbeSetColName(
60006   Vdbe *p,                         /* Vdbe being configured */
60007   int idx,                         /* Index of column zName applies to */
60008   int var,                         /* One of the COLNAME_* constants */
60009   const char *zName,               /* Pointer to buffer containing name */
60010   void (*xDel)(void*)              /* Memory management strategy for zName */
60011 ){
60012   int rc;
60013   Mem *pColName;
60014   assert( idx<p->nResColumn );
60015   assert( var<COLNAME_N );
60016   if( p->db->mallocFailed ){
60017     assert( !zName || xDel!=SQLITE_DYNAMIC );
60018     return SQLITE_NOMEM;
60019   }
60020   assert( p->aColName!=0 );
60021   pColName = &(p->aColName[idx+var*p->nResColumn]);
60022   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
60023   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
60024   return rc;
60025 }
60026 
60027 /*
60028 ** A read or write transaction may or may not be active on database handle
60029 ** db. If a transaction is active, commit it. If there is a
60030 ** write-transaction spanning more than one database file, this routine
60031 ** takes care of the master journal trickery.
60032 */
60033 static int vdbeCommit(sqlite3 *db, Vdbe *p){
60034   int i;
60035   int nTrans = 0;  /* Number of databases with an active write-transaction */
60036   int rc = SQLITE_OK;
60037   int needXcommit = 0;
60038 
60039 #ifdef SQLITE_OMIT_VIRTUALTABLE
60040   /* With this option, sqlite3VtabSync() is defined to be simply
60041   ** SQLITE_OK so p is not used.
60042   */
60043   UNUSED_PARAMETER(p);
60044 #endif
60045 
60046   /* Before doing anything else, call the xSync() callback for any
60047   ** virtual module tables written in this transaction. This has to
60048   ** be done before determining whether a master journal file is
60049   ** required, as an xSync() callback may add an attached database
60050   ** to the transaction.
60051   */
60052   rc = sqlite3VtabSync(db, &p->zErrMsg);
60053 
60054   /* This loop determines (a) if the commit hook should be invoked and
60055   ** (b) how many database files have open write transactions, not
60056   ** including the temp database. (b) is important because if more than
60057   ** one database file has an open write transaction, a master journal
60058   ** file is required for an atomic commit.
60059   */
60060   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60061     Btree *pBt = db->aDb[i].pBt;
60062     if( sqlite3BtreeIsInTrans(pBt) ){
60063       needXcommit = 1;
60064       if( i!=1 ) nTrans++;
60065       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
60066     }
60067   }
60068   if( rc!=SQLITE_OK ){
60069     return rc;
60070   }
60071 
60072   /* If there are any write-transactions at all, invoke the commit hook */
60073   if( needXcommit && db->xCommitCallback ){
60074     rc = db->xCommitCallback(db->pCommitArg);
60075     if( rc ){
60076       return SQLITE_CONSTRAINT;
60077     }
60078   }
60079 
60080   /* The simple case - no more than one database file (not counting the
60081   ** TEMP database) has a transaction active.   There is no need for the
60082   ** master-journal.
60083   **
60084   ** If the return value of sqlite3BtreeGetFilename() is a zero length
60085   ** string, it means the main database is :memory: or a temp file.  In
60086   ** that case we do not support atomic multi-file commits, so use the
60087   ** simple case then too.
60088   */
60089   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
60090    || nTrans<=1
60091   ){
60092     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60093       Btree *pBt = db->aDb[i].pBt;
60094       if( pBt ){
60095         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
60096       }
60097     }
60098 
60099     /* Do the commit only if all databases successfully complete phase 1.
60100     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
60101     ** IO error while deleting or truncating a journal file. It is unlikely,
60102     ** but could happen. In this case abandon processing and return the error.
60103     */
60104     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60105       Btree *pBt = db->aDb[i].pBt;
60106       if( pBt ){
60107         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
60108       }
60109     }
60110     if( rc==SQLITE_OK ){
60111       sqlite3VtabCommit(db);
60112     }
60113   }
60114 
60115   /* The complex case - There is a multi-file write-transaction active.
60116   ** This requires a master journal file to ensure the transaction is
60117   ** committed atomicly.
60118   */
60119 #ifndef SQLITE_OMIT_DISKIO
60120   else{
60121     sqlite3_vfs *pVfs = db->pVfs;
60122     int needSync = 0;
60123     char *zMaster = 0;   /* File-name for the master journal */
60124     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
60125     sqlite3_file *pMaster = 0;
60126     i64 offset = 0;
60127     int res;
60128 
60129     /* Select a master journal file name */
60130     do {
60131       u32 iRandom;
60132       sqlite3DbFree(db, zMaster);
60133       sqlite3_randomness(sizeof(iRandom), &iRandom);
60134       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
60135       if( !zMaster ){
60136         return SQLITE_NOMEM;
60137       }
60138       sqlite3FileSuffix3(zMainFile, zMaster);
60139       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
60140     }while( rc==SQLITE_OK && res );
60141     if( rc==SQLITE_OK ){
60142       /* Open the master journal. */
60143       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
60144           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
60145           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
60146       );
60147     }
60148     if( rc!=SQLITE_OK ){
60149       sqlite3DbFree(db, zMaster);
60150       return rc;
60151     }
60152 
60153     /* Write the name of each database file in the transaction into the new
60154     ** master journal file. If an error occurs at this point close
60155     ** and delete the master journal file. All the individual journal files
60156     ** still have 'null' as the master journal pointer, so they will roll
60157     ** back independently if a failure occurs.
60158     */
60159     for(i=0; i<db->nDb; i++){
60160       Btree *pBt = db->aDb[i].pBt;
60161       if( sqlite3BtreeIsInTrans(pBt) ){
60162         char const *zFile = sqlite3BtreeGetJournalname(pBt);
60163         if( zFile==0 ){
60164           continue;  /* Ignore TEMP and :memory: databases */
60165         }
60166         assert( zFile[0]!=0 );
60167         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
60168           needSync = 1;
60169         }
60170         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
60171         offset += sqlite3Strlen30(zFile)+1;
60172         if( rc!=SQLITE_OK ){
60173           sqlite3OsCloseFree(pMaster);
60174           sqlite3OsDelete(pVfs, zMaster, 0);
60175           sqlite3DbFree(db, zMaster);
60176           return rc;
60177         }
60178       }
60179     }
60180 
60181     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
60182     ** flag is set this is not required.
60183     */
60184     if( needSync
60185      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
60186      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
60187     ){
60188       sqlite3OsCloseFree(pMaster);
60189       sqlite3OsDelete(pVfs, zMaster, 0);
60190       sqlite3DbFree(db, zMaster);
60191       return rc;
60192     }
60193 
60194     /* Sync all the db files involved in the transaction. The same call
60195     ** sets the master journal pointer in each individual journal. If
60196     ** an error occurs here, do not delete the master journal file.
60197     **
60198     ** If the error occurs during the first call to
60199     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
60200     ** master journal file will be orphaned. But we cannot delete it,
60201     ** in case the master journal file name was written into the journal
60202     ** file before the failure occurred.
60203     */
60204     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
60205       Btree *pBt = db->aDb[i].pBt;
60206       if( pBt ){
60207         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
60208       }
60209     }
60210     sqlite3OsCloseFree(pMaster);
60211     assert( rc!=SQLITE_BUSY );
60212     if( rc!=SQLITE_OK ){
60213       sqlite3DbFree(db, zMaster);
60214       return rc;
60215     }
60216 
60217     /* Delete the master journal file. This commits the transaction. After
60218     ** doing this the directory is synced again before any individual
60219     ** transaction files are deleted.
60220     */
60221     rc = sqlite3OsDelete(pVfs, zMaster, 1);
60222     sqlite3DbFree(db, zMaster);
60223     zMaster = 0;
60224     if( rc ){
60225       return rc;
60226     }
60227 
60228     /* All files and directories have already been synced, so the following
60229     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
60230     ** deleting or truncating journals. If something goes wrong while
60231     ** this is happening we don't really care. The integrity of the
60232     ** transaction is already guaranteed, but some stray 'cold' journals
60233     ** may be lying around. Returning an error code won't help matters.
60234     */
60235     disable_simulated_io_errors();
60236     sqlite3BeginBenignMalloc();
60237     for(i=0; i<db->nDb; i++){
60238       Btree *pBt = db->aDb[i].pBt;
60239       if( pBt ){
60240         sqlite3BtreeCommitPhaseTwo(pBt, 1);
60241       }
60242     }
60243     sqlite3EndBenignMalloc();
60244     enable_simulated_io_errors();
60245 
60246     sqlite3VtabCommit(db);
60247   }
60248 #endif
60249 
60250   return rc;
60251 }
60252 
60253 /*
60254 ** This routine checks that the sqlite3.activeVdbeCnt count variable
60255 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
60256 ** currently active. An assertion fails if the two counts do not match.
60257 ** This is an internal self-check only - it is not an essential processing
60258 ** step.
60259 **
60260 ** This is a no-op if NDEBUG is defined.
60261 */
60262 #ifndef NDEBUG
60263 static void checkActiveVdbeCnt(sqlite3 *db){
60264   Vdbe *p;
60265   int cnt = 0;
60266   int nWrite = 0;
60267   p = db->pVdbe;
60268   while( p ){
60269     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
60270       cnt++;
60271       if( p->readOnly==0 ) nWrite++;
60272     }
60273     p = p->pNext;
60274   }
60275   assert( cnt==db->activeVdbeCnt );
60276   assert( nWrite==db->writeVdbeCnt );
60277 }
60278 #else
60279 #define checkActiveVdbeCnt(x)
60280 #endif
60281 
60282 /*
60283 ** For every Btree that in database connection db which
60284 ** has been modified, "trip" or invalidate each cursor in
60285 ** that Btree might have been modified so that the cursor
60286 ** can never be used again.  This happens when a rollback
60287 *** occurs.  We have to trip all the other cursors, even
60288 ** cursor from other VMs in different database connections,
60289 ** so that none of them try to use the data at which they
60290 ** were pointing and which now may have been changed due
60291 ** to the rollback.
60292 **
60293 ** Remember that a rollback can delete tables complete and
60294 ** reorder rootpages.  So it is not sufficient just to save
60295 ** the state of the cursor.  We have to invalidate the cursor
60296 ** so that it is never used again.
60297 */
60298 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
60299   int i;
60300   for(i=0; i<db->nDb; i++){
60301     Btree *p = db->aDb[i].pBt;
60302     if( p && sqlite3BtreeIsInTrans(p) ){
60303       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
60304     }
60305   }
60306 }
60307 
60308 /*
60309 ** If the Vdbe passed as the first argument opened a statement-transaction,
60310 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
60311 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
60312 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
60313 ** statement transaction is commtted.
60314 **
60315 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
60316 ** Otherwise SQLITE_OK.
60317 */
60318 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
60319   sqlite3 *const db = p->db;
60320   int rc = SQLITE_OK;
60321 
60322   /* If p->iStatement is greater than zero, then this Vdbe opened a
60323   ** statement transaction that should be closed here. The only exception
60324   ** is that an IO error may have occured, causing an emergency rollback.
60325   ** In this case (db->nStatement==0), and there is nothing to do.
60326   */
60327   if( db->nStatement && p->iStatement ){
60328     int i;
60329     const int iSavepoint = p->iStatement-1;
60330 
60331     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
60332     assert( db->nStatement>0 );
60333     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
60334 
60335     for(i=0; i<db->nDb; i++){
60336       int rc2 = SQLITE_OK;
60337       Btree *pBt = db->aDb[i].pBt;
60338       if( pBt ){
60339         if( eOp==SAVEPOINT_ROLLBACK ){
60340           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
60341         }
60342         if( rc2==SQLITE_OK ){
60343           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
60344         }
60345         if( rc==SQLITE_OK ){
60346           rc = rc2;
60347         }
60348       }
60349     }
60350     db->nStatement--;
60351     p->iStatement = 0;
60352 
60353     if( rc==SQLITE_OK ){
60354       if( eOp==SAVEPOINT_ROLLBACK ){
60355         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
60356       }
60357       if( rc==SQLITE_OK ){
60358         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
60359       }
60360     }
60361 
60362     /* If the statement transaction is being rolled back, also restore the
60363     ** database handles deferred constraint counter to the value it had when
60364     ** the statement transaction was opened.  */
60365     if( eOp==SAVEPOINT_ROLLBACK ){
60366       db->nDeferredCons = p->nStmtDefCons;
60367     }
60368   }
60369   return rc;
60370 }
60371 
60372 /*
60373 ** This function is called when a transaction opened by the database
60374 ** handle associated with the VM passed as an argument is about to be
60375 ** committed. If there are outstanding deferred foreign key constraint
60376 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
60377 **
60378 ** If there are outstanding FK violations and this function returns
60379 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
60380 ** an error message to it. Then return SQLITE_ERROR.
60381 */
60382 #ifndef SQLITE_OMIT_FOREIGN_KEY
60383 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
60384   sqlite3 *db = p->db;
60385   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
60386     p->rc = SQLITE_CONSTRAINT;
60387     p->errorAction = OE_Abort;
60388     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
60389     return SQLITE_ERROR;
60390   }
60391   return SQLITE_OK;
60392 }
60393 #endif
60394 
60395 /*
60396 ** This routine is called the when a VDBE tries to halt.  If the VDBE
60397 ** has made changes and is in autocommit mode, then commit those
60398 ** changes.  If a rollback is needed, then do the rollback.
60399 **
60400 ** This routine is the only way to move the state of a VM from
60401 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
60402 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
60403 **
60404 ** Return an error code.  If the commit could not complete because of
60405 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
60406 ** means the close did not happen and needs to be repeated.
60407 */
60408 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
60409   int rc;                         /* Used to store transient return codes */
60410   sqlite3 *db = p->db;
60411 
60412   /* This function contains the logic that determines if a statement or
60413   ** transaction will be committed or rolled back as a result of the
60414   ** execution of this virtual machine.
60415   **
60416   ** If any of the following errors occur:
60417   **
60418   **     SQLITE_NOMEM
60419   **     SQLITE_IOERR
60420   **     SQLITE_FULL
60421   **     SQLITE_INTERRUPT
60422   **
60423   ** Then the internal cache might have been left in an inconsistent
60424   ** state.  We need to rollback the statement transaction, if there is
60425   ** one, or the complete transaction if there is no statement transaction.
60426   */
60427 
60428   if( p->db->mallocFailed ){
60429     p->rc = SQLITE_NOMEM;
60430   }
60431   closeAllCursors(p);
60432   if( p->magic!=VDBE_MAGIC_RUN ){
60433     return SQLITE_OK;
60434   }
60435   checkActiveVdbeCnt(db);
60436 
60437   /* No commit or rollback needed if the program never started */
60438   if( p->pc>=0 ){
60439     int mrc;   /* Primary error code from p->rc */
60440     int eStatementOp = 0;
60441     int isSpecialError;            /* Set to true if a 'special' error */
60442 
60443     /* Lock all btrees used by the statement */
60444     sqlite3VdbeEnter(p);
60445 
60446     /* Check for one of the special errors */
60447     mrc = p->rc & 0xff;
60448     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
60449     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
60450                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
60451     if( isSpecialError ){
60452       /* If the query was read-only and the error code is SQLITE_INTERRUPT,
60453       ** no rollback is necessary. Otherwise, at least a savepoint
60454       ** transaction must be rolled back to restore the database to a
60455       ** consistent state.
60456       **
60457       ** Even if the statement is read-only, it is important to perform
60458       ** a statement or transaction rollback operation. If the error
60459       ** occured while writing to the journal, sub-journal or database
60460       ** file as part of an effort to free up cache space (see function
60461       ** pagerStress() in pager.c), the rollback is required to restore
60462       ** the pager to a consistent state.
60463       */
60464       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
60465         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
60466           eStatementOp = SAVEPOINT_ROLLBACK;
60467         }else{
60468           /* We are forced to roll back the active transaction. Before doing
60469           ** so, abort any other statements this handle currently has active.
60470           */
60471           invalidateCursorsOnModifiedBtrees(db);
60472           sqlite3RollbackAll(db);
60473           sqlite3CloseSavepoints(db);
60474           db->autoCommit = 1;
60475         }
60476       }
60477     }
60478 
60479     /* Check for immediate foreign key violations. */
60480     if( p->rc==SQLITE_OK ){
60481       sqlite3VdbeCheckFk(p, 0);
60482     }
60483 
60484     /* If the auto-commit flag is set and this is the only active writer
60485     ** VM, then we do either a commit or rollback of the current transaction.
60486     **
60487     ** Note: This block also runs if one of the special errors handled
60488     ** above has occurred.
60489     */
60490     if( !sqlite3VtabInSync(db)
60491      && db->autoCommit
60492      && db->writeVdbeCnt==(p->readOnly==0)
60493     ){
60494       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
60495         rc = sqlite3VdbeCheckFk(p, 1);
60496         if( rc!=SQLITE_OK ){
60497           if( NEVER(p->readOnly) ){
60498             sqlite3VdbeLeave(p);
60499             return SQLITE_ERROR;
60500           }
60501           rc = SQLITE_CONSTRAINT;
60502         }else{
60503           /* The auto-commit flag is true, the vdbe program was successful
60504           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
60505           ** key constraints to hold up the transaction. This means a commit
60506           ** is required. */
60507           rc = vdbeCommit(db, p);
60508         }
60509         if( rc==SQLITE_BUSY && p->readOnly ){
60510           sqlite3VdbeLeave(p);
60511           return SQLITE_BUSY;
60512         }else if( rc!=SQLITE_OK ){
60513           p->rc = rc;
60514           sqlite3RollbackAll(db);
60515         }else{
60516           db->nDeferredCons = 0;
60517           sqlite3CommitInternalChanges(db);
60518         }
60519       }else{
60520         sqlite3RollbackAll(db);
60521       }
60522       db->nStatement = 0;
60523     }else if( eStatementOp==0 ){
60524       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
60525         eStatementOp = SAVEPOINT_RELEASE;
60526       }else if( p->errorAction==OE_Abort ){
60527         eStatementOp = SAVEPOINT_ROLLBACK;
60528       }else{
60529         invalidateCursorsOnModifiedBtrees(db);
60530         sqlite3RollbackAll(db);
60531         sqlite3CloseSavepoints(db);
60532         db->autoCommit = 1;
60533       }
60534     }
60535 
60536     /* If eStatementOp is non-zero, then a statement transaction needs to
60537     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
60538     ** do so. If this operation returns an error, and the current statement
60539     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
60540     ** current statement error code.
60541     */
60542     if( eStatementOp ){
60543       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
60544       if( rc ){
60545         if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
60546           p->rc = rc;
60547           sqlite3DbFree(db, p->zErrMsg);
60548           p->zErrMsg = 0;
60549         }
60550         invalidateCursorsOnModifiedBtrees(db);
60551         sqlite3RollbackAll(db);
60552         sqlite3CloseSavepoints(db);
60553         db->autoCommit = 1;
60554       }
60555     }
60556 
60557     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
60558     ** has been rolled back, update the database connection change-counter.
60559     */
60560     if( p->changeCntOn ){
60561       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
60562         sqlite3VdbeSetChanges(db, p->nChange);
60563       }else{
60564         sqlite3VdbeSetChanges(db, 0);
60565       }
60566       p->nChange = 0;
60567     }
60568 
60569     /* Rollback or commit any schema changes that occurred. */
60570     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
60571       sqlite3ResetInternalSchema(db, -1);
60572       db->flags = (db->flags | SQLITE_InternChanges);
60573     }
60574 
60575     /* Release the locks */
60576     sqlite3VdbeLeave(p);
60577   }
60578 
60579   /* We have successfully halted and closed the VM.  Record this fact. */
60580   if( p->pc>=0 ){
60581     db->activeVdbeCnt--;
60582     if( !p->readOnly ){
60583       db->writeVdbeCnt--;
60584     }
60585     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
60586   }
60587   p->magic = VDBE_MAGIC_HALT;
60588   checkActiveVdbeCnt(db);
60589   if( p->db->mallocFailed ){
60590     p->rc = SQLITE_NOMEM;
60591   }
60592 
60593   /* If the auto-commit flag is set to true, then any locks that were held
60594   ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
60595   ** to invoke any required unlock-notify callbacks.
60596   */
60597   if( db->autoCommit ){
60598     sqlite3ConnectionUnlocked(db);
60599   }
60600 
60601   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
60602   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
60603 }
60604 
60605 
60606 /*
60607 ** Each VDBE holds the result of the most recent sqlite3_step() call
60608 ** in p->rc.  This routine sets that result back to SQLITE_OK.
60609 */
60610 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
60611   p->rc = SQLITE_OK;
60612 }
60613 
60614 /*
60615 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
60616 ** Write any error messages into *pzErrMsg.  Return the result code.
60617 **
60618 ** After this routine is run, the VDBE should be ready to be executed
60619 ** again.
60620 **
60621 ** To look at it another way, this routine resets the state of the
60622 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
60623 ** VDBE_MAGIC_INIT.
60624 */
60625 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
60626   sqlite3 *db;
60627   db = p->db;
60628 
60629   /* If the VM did not run to completion or if it encountered an
60630   ** error, then it might not have been halted properly.  So halt
60631   ** it now.
60632   */
60633   sqlite3VdbeHalt(p);
60634 
60635   /* If the VDBE has be run even partially, then transfer the error code
60636   ** and error message from the VDBE into the main database structure.  But
60637   ** if the VDBE has just been set to run but has not actually executed any
60638   ** instructions yet, leave the main database error information unchanged.
60639   */
60640   if( p->pc>=0 ){
60641     if( p->zErrMsg ){
60642       sqlite3BeginBenignMalloc();
60643       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
60644       sqlite3EndBenignMalloc();
60645       db->errCode = p->rc;
60646       sqlite3DbFree(db, p->zErrMsg);
60647       p->zErrMsg = 0;
60648     }else if( p->rc ){
60649       sqlite3Error(db, p->rc, 0);
60650     }else{
60651       sqlite3Error(db, SQLITE_OK, 0);
60652     }
60653     if( p->runOnlyOnce ) p->expired = 1;
60654   }else if( p->rc && p->expired ){
60655     /* The expired flag was set on the VDBE before the first call
60656     ** to sqlite3_step(). For consistency (since sqlite3_step() was
60657     ** called), set the database error in this case as well.
60658     */
60659     sqlite3Error(db, p->rc, 0);
60660     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
60661     sqlite3DbFree(db, p->zErrMsg);
60662     p->zErrMsg = 0;
60663   }
60664 
60665   /* Reclaim all memory used by the VDBE
60666   */
60667   Cleanup(p);
60668 
60669   /* Save profiling information from this VDBE run.
60670   */
60671 #ifdef VDBE_PROFILE
60672   {
60673     FILE *out = fopen("vdbe_profile.out", "a");
60674     if( out ){
60675       int i;
60676       fprintf(out, "---- ");
60677       for(i=0; i<p->nOp; i++){
60678         fprintf(out, "%02x", p->aOp[i].opcode);
60679       }
60680       fprintf(out, "\n");
60681       for(i=0; i<p->nOp; i++){
60682         fprintf(out, "%6d %10lld %8lld ",
60683            p->aOp[i].cnt,
60684            p->aOp[i].cycles,
60685            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
60686         );
60687         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
60688       }
60689       fclose(out);
60690     }
60691   }
60692 #endif
60693   p->magic = VDBE_MAGIC_INIT;
60694   return p->rc & db->errMask;
60695 }
60696 
60697 /*
60698 ** Clean up and delete a VDBE after execution.  Return an integer which is
60699 ** the result code.  Write any error message text into *pzErrMsg.
60700 */
60701 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
60702   int rc = SQLITE_OK;
60703   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
60704     rc = sqlite3VdbeReset(p);
60705     assert( (rc & p->db->errMask)==rc );
60706   }
60707   sqlite3VdbeDelete(p);
60708   return rc;
60709 }
60710 
60711 /*
60712 ** Call the destructor for each auxdata entry in pVdbeFunc for which
60713 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
60714 ** are always destroyed.  To destroy all auxdata entries, call this
60715 ** routine with mask==0.
60716 */
60717 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
60718   int i;
60719   for(i=0; i<pVdbeFunc->nAux; i++){
60720     struct AuxData *pAux = &pVdbeFunc->apAux[i];
60721     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
60722       if( pAux->xDelete ){
60723         pAux->xDelete(pAux->pAux);
60724       }
60725       pAux->pAux = 0;
60726     }
60727   }
60728 }
60729 
60730 /*
60731 ** Free all memory associated with the Vdbe passed as the second argument.
60732 ** The difference between this function and sqlite3VdbeDelete() is that
60733 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
60734 ** the database connection.
60735 */
60736 SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
60737   SubProgram *pSub, *pNext;
60738   int i;
60739   assert( p->db==0 || p->db==db );
60740   releaseMemArray(p->aVar, p->nVar);
60741   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
60742   for(pSub=p->pProgram; pSub; pSub=pNext){
60743     pNext = pSub->pNext;
60744     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
60745     sqlite3DbFree(db, pSub);
60746   }
60747   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
60748   vdbeFreeOpArray(db, p->aOp, p->nOp);
60749   sqlite3DbFree(db, p->aLabel);
60750   sqlite3DbFree(db, p->aColName);
60751   sqlite3DbFree(db, p->zSql);
60752   sqlite3DbFree(db, p->pFree);
60753   sqlite3DbFree(db, p);
60754 }
60755 
60756 /*
60757 ** Delete an entire VDBE.
60758 */
60759 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
60760   sqlite3 *db;
60761 
60762   if( NEVER(p==0) ) return;
60763   db = p->db;
60764   if( p->pPrev ){
60765     p->pPrev->pNext = p->pNext;
60766   }else{
60767     assert( db->pVdbe==p );
60768     db->pVdbe = p->pNext;
60769   }
60770   if( p->pNext ){
60771     p->pNext->pPrev = p->pPrev;
60772   }
60773   p->magic = VDBE_MAGIC_DEAD;
60774   p->db = 0;
60775   sqlite3VdbeDeleteObject(db, p);
60776 }
60777 
60778 /*
60779 ** Make sure the cursor p is ready to read or write the row to which it
60780 ** was last positioned.  Return an error code if an OOM fault or I/O error
60781 ** prevents us from positioning the cursor to its correct position.
60782 **
60783 ** If a MoveTo operation is pending on the given cursor, then do that
60784 ** MoveTo now.  If no move is pending, check to see if the row has been
60785 ** deleted out from under the cursor and if it has, mark the row as
60786 ** a NULL row.
60787 **
60788 ** If the cursor is already pointing to the correct row and that row has
60789 ** not been deleted out from under the cursor, then this routine is a no-op.
60790 */
60791 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
60792   if( p->deferredMoveto ){
60793     int res, rc;
60794 #ifdef SQLITE_TEST
60795     extern int sqlite3_search_count;
60796 #endif
60797     assert( p->isTable );
60798     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
60799     if( rc ) return rc;
60800     p->lastRowid = p->movetoTarget;
60801     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
60802     p->rowidIsValid = 1;
60803 #ifdef SQLITE_TEST
60804     sqlite3_search_count++;
60805 #endif
60806     p->deferredMoveto = 0;
60807     p->cacheStatus = CACHE_STALE;
60808   }else if( ALWAYS(p->pCursor) ){
60809     int hasMoved;
60810     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
60811     if( rc ) return rc;
60812     if( hasMoved ){
60813       p->cacheStatus = CACHE_STALE;
60814       p->nullRow = 1;
60815     }
60816   }
60817   return SQLITE_OK;
60818 }
60819 
60820 /*
60821 ** The following functions:
60822 **
60823 ** sqlite3VdbeSerialType()
60824 ** sqlite3VdbeSerialTypeLen()
60825 ** sqlite3VdbeSerialLen()
60826 ** sqlite3VdbeSerialPut()
60827 ** sqlite3VdbeSerialGet()
60828 **
60829 ** encapsulate the code that serializes values for storage in SQLite
60830 ** data and index records. Each serialized value consists of a
60831 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
60832 ** integer, stored as a varint.
60833 **
60834 ** In an SQLite index record, the serial type is stored directly before
60835 ** the blob of data that it corresponds to. In a table record, all serial
60836 ** types are stored at the start of the record, and the blobs of data at
60837 ** the end. Hence these functions allow the caller to handle the
60838 ** serial-type and data blob seperately.
60839 **
60840 ** The following table describes the various storage classes for data:
60841 **
60842 **   serial type        bytes of data      type
60843 **   --------------     ---------------    ---------------
60844 **      0                     0            NULL
60845 **      1                     1            signed integer
60846 **      2                     2            signed integer
60847 **      3                     3            signed integer
60848 **      4                     4            signed integer
60849 **      5                     6            signed integer
60850 **      6                     8            signed integer
60851 **      7                     8            IEEE float
60852 **      8                     0            Integer constant 0
60853 **      9                     0            Integer constant 1
60854 **     10,11                               reserved for expansion
60855 **    N>=12 and even       (N-12)/2        BLOB
60856 **    N>=13 and odd        (N-13)/2        text
60857 **
60858 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
60859 ** of SQLite will not understand those serial types.
60860 */
60861 
60862 /*
60863 ** Return the serial-type for the value stored in pMem.
60864 */
60865 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
60866   int flags = pMem->flags;
60867   int n;
60868 
60869   if( flags&MEM_Null ){
60870     return 0;
60871   }
60872   if( flags&MEM_Int ){
60873     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
60874 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
60875     i64 i = pMem->u.i;
60876     u64 u;
60877     if( file_format>=4 && (i&1)==i ){
60878       return 8+(u32)i;
60879     }
60880     if( i<0 ){
60881       if( i<(-MAX_6BYTE) ) return 6;
60882       /* Previous test prevents:  u = -(-9223372036854775808) */
60883       u = -i;
60884     }else{
60885       u = i;
60886     }
60887     if( u<=127 ) return 1;
60888     if( u<=32767 ) return 2;
60889     if( u<=8388607 ) return 3;
60890     if( u<=2147483647 ) return 4;
60891     if( u<=MAX_6BYTE ) return 5;
60892     return 6;
60893   }
60894   if( flags&MEM_Real ){
60895     return 7;
60896   }
60897   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
60898   n = pMem->n;
60899   if( flags & MEM_Zero ){
60900     n += pMem->u.nZero;
60901   }
60902   assert( n>=0 );
60903   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
60904 }
60905 
60906 /*
60907 ** Return the length of the data corresponding to the supplied serial-type.
60908 */
60909 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
60910   if( serial_type>=12 ){
60911     return (serial_type-12)/2;
60912   }else{
60913     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
60914     return aSize[serial_type];
60915   }
60916 }
60917 
60918 /*
60919 ** If we are on an architecture with mixed-endian floating
60920 ** points (ex: ARM7) then swap the lower 4 bytes with the
60921 ** upper 4 bytes.  Return the result.
60922 **
60923 ** For most architectures, this is a no-op.
60924 **
60925 ** (later):  It is reported to me that the mixed-endian problem
60926 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
60927 ** that early versions of GCC stored the two words of a 64-bit
60928 ** float in the wrong order.  And that error has been propagated
60929 ** ever since.  The blame is not necessarily with GCC, though.
60930 ** GCC might have just copying the problem from a prior compiler.
60931 ** I am also told that newer versions of GCC that follow a different
60932 ** ABI get the byte order right.
60933 **
60934 ** Developers using SQLite on an ARM7 should compile and run their
60935 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
60936 ** enabled, some asserts below will ensure that the byte order of
60937 ** floating point values is correct.
60938 **
60939 ** (2007-08-30)  Frank van Vugt has studied this problem closely
60940 ** and has send his findings to the SQLite developers.  Frank
60941 ** writes that some Linux kernels offer floating point hardware
60942 ** emulation that uses only 32-bit mantissas instead of a full
60943 ** 48-bits as required by the IEEE standard.  (This is the
60944 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
60945 ** byte swapping becomes very complicated.  To avoid problems,
60946 ** the necessary byte swapping is carried out using a 64-bit integer
60947 ** rather than a 64-bit float.  Frank assures us that the code here
60948 ** works for him.  We, the developers, have no way to independently
60949 ** verify this, but Frank seems to know what he is talking about
60950 ** so we trust him.
60951 */
60952 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
60953 static u64 floatSwap(u64 in){
60954   union {
60955     u64 r;
60956     u32 i[2];
60957   } u;
60958   u32 t;
60959 
60960   u.r = in;
60961   t = u.i[0];
60962   u.i[0] = u.i[1];
60963   u.i[1] = t;
60964   return u.r;
60965 }
60966 # define swapMixedEndianFloat(X)  X = floatSwap(X)
60967 #else
60968 # define swapMixedEndianFloat(X)
60969 #endif
60970 
60971 /*
60972 ** Write the serialized data blob for the value stored in pMem into
60973 ** buf. It is assumed that the caller has allocated sufficient space.
60974 ** Return the number of bytes written.
60975 **
60976 ** nBuf is the amount of space left in buf[].  nBuf must always be
60977 ** large enough to hold the entire field.  Except, if the field is
60978 ** a blob with a zero-filled tail, then buf[] might be just the right
60979 ** size to hold everything except for the zero-filled tail.  If buf[]
60980 ** is only big enough to hold the non-zero prefix, then only write that
60981 ** prefix into buf[].  But if buf[] is large enough to hold both the
60982 ** prefix and the tail then write the prefix and set the tail to all
60983 ** zeros.
60984 **
60985 ** Return the number of bytes actually written into buf[].  The number
60986 ** of bytes in the zero-filled tail is included in the return value only
60987 ** if those bytes were zeroed in buf[].
60988 */
60989 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
60990   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
60991   u32 len;
60992 
60993   /* Integer and Real */
60994   if( serial_type<=7 && serial_type>0 ){
60995     u64 v;
60996     u32 i;
60997     if( serial_type==7 ){
60998       assert( sizeof(v)==sizeof(pMem->r) );
60999       memcpy(&v, &pMem->r, sizeof(v));
61000       swapMixedEndianFloat(v);
61001     }else{
61002       v = pMem->u.i;
61003     }
61004     len = i = sqlite3VdbeSerialTypeLen(serial_type);
61005     assert( len<=(u32)nBuf );
61006     while( i-- ){
61007       buf[i] = (u8)(v&0xFF);
61008       v >>= 8;
61009     }
61010     return len;
61011   }
61012 
61013   /* String or blob */
61014   if( serial_type>=12 ){
61015     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
61016              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
61017     assert( pMem->n<=nBuf );
61018     len = pMem->n;
61019     memcpy(buf, pMem->z, len);
61020     if( pMem->flags & MEM_Zero ){
61021       len += pMem->u.nZero;
61022       assert( nBuf>=0 );
61023       if( len > (u32)nBuf ){
61024         len = (u32)nBuf;
61025       }
61026       memset(&buf[pMem->n], 0, len-pMem->n);
61027     }
61028     return len;
61029   }
61030 
61031   /* NULL or constants 0 or 1 */
61032   return 0;
61033 }
61034 
61035 /*
61036 ** Deserialize the data blob pointed to by buf as serial type serial_type
61037 ** and store the result in pMem.  Return the number of bytes read.
61038 */
61039 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
61040   const unsigned char *buf,     /* Buffer to deserialize from */
61041   u32 serial_type,              /* Serial type to deserialize */
61042   Mem *pMem                     /* Memory cell to write value into */
61043 ){
61044   switch( serial_type ){
61045     case 10:   /* Reserved for future use */
61046     case 11:   /* Reserved for future use */
61047     case 0: {  /* NULL */
61048       pMem->flags = MEM_Null;
61049       break;
61050     }
61051     case 1: { /* 1-byte signed integer */
61052       pMem->u.i = (signed char)buf[0];
61053       pMem->flags = MEM_Int;
61054       return 1;
61055     }
61056     case 2: { /* 2-byte signed integer */
61057       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
61058       pMem->flags = MEM_Int;
61059       return 2;
61060     }
61061     case 3: { /* 3-byte signed integer */
61062       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
61063       pMem->flags = MEM_Int;
61064       return 3;
61065     }
61066     case 4: { /* 4-byte signed integer */
61067       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61068       pMem->flags = MEM_Int;
61069       return 4;
61070     }
61071     case 5: { /* 6-byte signed integer */
61072       u64 x = (((signed char)buf[0])<<8) | buf[1];
61073       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
61074       x = (x<<32) | y;
61075       pMem->u.i = *(i64*)&x;
61076       pMem->flags = MEM_Int;
61077       return 6;
61078     }
61079     case 6:   /* 8-byte signed integer */
61080     case 7: { /* IEEE floating point */
61081       u64 x;
61082       u32 y;
61083 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
61084       /* Verify that integers and floating point values use the same
61085       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
61086       ** defined that 64-bit floating point values really are mixed
61087       ** endian.
61088       */
61089       static const u64 t1 = ((u64)0x3ff00000)<<32;
61090       static const double r1 = 1.0;
61091       u64 t2 = t1;
61092       swapMixedEndianFloat(t2);
61093       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
61094 #endif
61095 
61096       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
61097       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
61098       x = (x<<32) | y;
61099       if( serial_type==6 ){
61100         pMem->u.i = *(i64*)&x;
61101         pMem->flags = MEM_Int;
61102       }else{
61103         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
61104         swapMixedEndianFloat(x);
61105         memcpy(&pMem->r, &x, sizeof(x));
61106         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
61107       }
61108       return 8;
61109     }
61110     case 8:    /* Integer 0 */
61111     case 9: {  /* Integer 1 */
61112       pMem->u.i = serial_type-8;
61113       pMem->flags = MEM_Int;
61114       return 0;
61115     }
61116     default: {
61117       u32 len = (serial_type-12)/2;
61118       pMem->z = (char *)buf;
61119       pMem->n = len;
61120       pMem->xDel = 0;
61121       if( serial_type&0x01 ){
61122         pMem->flags = MEM_Str | MEM_Ephem;
61123       }else{
61124         pMem->flags = MEM_Blob | MEM_Ephem;
61125       }
61126       return len;
61127     }
61128   }
61129   return 0;
61130 }
61131 
61132 /*
61133 ** This routine is used to allocate sufficient space for an UnpackedRecord
61134 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
61135 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
61136 **
61137 ** The space is either allocated using sqlite3DbMallocRaw() or from within
61138 ** the unaligned buffer passed via the second and third arguments (presumably
61139 ** stack space). If the former, then *ppFree is set to a pointer that should
61140 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
61141 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
61142 ** before returning.
61143 **
61144 ** If an OOM error occurs, NULL is returned.
61145 */
61146 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
61147   KeyInfo *pKeyInfo,              /* Description of the record */
61148   char *pSpace,                   /* Unaligned space available */
61149   int szSpace,                    /* Size of pSpace[] in bytes */
61150   char **ppFree                   /* OUT: Caller should free this pointer */
61151 ){
61152   UnpackedRecord *p;              /* Unpacked record to return */
61153   int nOff;                       /* Increment pSpace by nOff to align it */
61154   int nByte;                      /* Number of bytes required for *p */
61155 
61156   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
61157   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
61158   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
61159   */
61160   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
61161   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
61162   if( nByte>szSpace+nOff ){
61163     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
61164     *ppFree = (char *)p;
61165     if( !p ) return 0;
61166   }else{
61167     p = (UnpackedRecord*)&pSpace[nOff];
61168     *ppFree = 0;
61169   }
61170 
61171   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
61172   p->pKeyInfo = pKeyInfo;
61173   p->nField = pKeyInfo->nField + 1;
61174   return p;
61175 }
61176 
61177 /*
61178 ** Given the nKey-byte encoding of a record in pKey[], populate the
61179 ** UnpackedRecord structure indicated by the fourth argument with the
61180 ** contents of the decoded record.
61181 */
61182 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
61183   KeyInfo *pKeyInfo,     /* Information about the record format */
61184   int nKey,              /* Size of the binary record */
61185   const void *pKey,      /* The binary record */
61186   UnpackedRecord *p      /* Populate this structure before returning. */
61187 ){
61188   const unsigned char *aKey = (const unsigned char *)pKey;
61189   int d;
61190   u32 idx;                        /* Offset in aKey[] to read from */
61191   u16 u;                          /* Unsigned loop counter */
61192   u32 szHdr;
61193   Mem *pMem = p->aMem;
61194 
61195   p->flags = 0;
61196   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
61197   idx = getVarint32(aKey, szHdr);
61198   d = szHdr;
61199   u = 0;
61200   while( idx<szHdr && u<p->nField && d<=nKey ){
61201     u32 serial_type;
61202 
61203     idx += getVarint32(&aKey[idx], serial_type);
61204     pMem->enc = pKeyInfo->enc;
61205     pMem->db = pKeyInfo->db;
61206     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
61207     pMem->zMalloc = 0;
61208     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
61209     pMem++;
61210     u++;
61211   }
61212   assert( u<=pKeyInfo->nField + 1 );
61213   p->nField = u;
61214 }
61215 
61216 /*
61217 ** This function compares the two table rows or index records
61218 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
61219 ** or positive integer if key1 is less than, equal to or
61220 ** greater than key2.  The {nKey1, pKey1} key must be a blob
61221 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
61222 ** key must be a parsed key such as obtained from
61223 ** sqlite3VdbeParseRecord.
61224 **
61225 ** Key1 and Key2 do not have to contain the same number of fields.
61226 ** The key with fewer fields is usually compares less than the
61227 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
61228 ** and the common prefixes are equal, then key1 is less than key2.
61229 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
61230 ** equal, then the keys are considered to be equal and
61231 ** the parts beyond the common prefix are ignored.
61232 **
61233 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
61234 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
61235 ** an index key, and thus ends with a rowid value.  The last byte
61236 ** of the header will therefore be the serial type of the rowid:
61237 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
61238 ** The serial type of the final rowid will always be a single byte.
61239 ** By ignoring this last byte of the header, we force the comparison
61240 ** to ignore the rowid at the end of key1.
61241 */
61242 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
61243   int nKey1, const void *pKey1, /* Left key */
61244   UnpackedRecord *pPKey2        /* Right key */
61245 ){
61246   int d1;            /* Offset into aKey[] of next data element */
61247   u32 idx1;          /* Offset into aKey[] of next header element */
61248   u32 szHdr1;        /* Number of bytes in header */
61249   int i = 0;
61250   int nField;
61251   int rc = 0;
61252   const unsigned char *aKey1 = (const unsigned char *)pKey1;
61253   KeyInfo *pKeyInfo;
61254   Mem mem1;
61255 
61256   pKeyInfo = pPKey2->pKeyInfo;
61257   mem1.enc = pKeyInfo->enc;
61258   mem1.db = pKeyInfo->db;
61259   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
61260   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
61261 
61262   /* Compilers may complain that mem1.u.i is potentially uninitialized.
61263   ** We could initialize it, as shown here, to silence those complaints.
61264   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
61265   ** the unnecessary initialization has a measurable negative performance
61266   ** impact, since this routine is a very high runner.  And so, we choose
61267   ** to ignore the compiler warnings and leave this variable uninitialized.
61268   */
61269   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
61270 
61271   idx1 = getVarint32(aKey1, szHdr1);
61272   d1 = szHdr1;
61273   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
61274     szHdr1--;
61275   }
61276   nField = pKeyInfo->nField;
61277   while( idx1<szHdr1 && i<pPKey2->nField ){
61278     u32 serial_type1;
61279 
61280     /* Read the serial types for the next element in each key. */
61281     idx1 += getVarint32( aKey1+idx1, serial_type1 );
61282     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
61283 
61284     /* Extract the values to be compared.
61285     */
61286     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
61287 
61288     /* Do the comparison
61289     */
61290     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
61291                            i<nField ? pKeyInfo->aColl[i] : 0);
61292     if( rc!=0 ){
61293       assert( mem1.zMalloc==0 );  /* See comment below */
61294 
61295       /* Invert the result if we are using DESC sort order. */
61296       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
61297         rc = -rc;
61298       }
61299 
61300       /* If the PREFIX_SEARCH flag is set and all fields except the final
61301       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
61302       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
61303       ** This is used by the OP_IsUnique opcode.
61304       */
61305       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
61306         assert( idx1==szHdr1 && rc );
61307         assert( mem1.flags & MEM_Int );
61308         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
61309         pPKey2->rowid = mem1.u.i;
61310       }
61311 
61312       return rc;
61313     }
61314     i++;
61315   }
61316 
61317   /* No memory allocation is ever used on mem1.  Prove this using
61318   ** the following assert().  If the assert() fails, it indicates a
61319   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
61320   */
61321   assert( mem1.zMalloc==0 );
61322 
61323   /* rc==0 here means that one of the keys ran out of fields and
61324   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
61325   ** flag is set, then break the tie by treating key2 as larger.
61326   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
61327   ** are considered to be equal.  Otherwise, the longer key is the
61328   ** larger.  As it happens, the pPKey2 will always be the longer
61329   ** if there is a difference.
61330   */
61331   assert( rc==0 );
61332   if( pPKey2->flags & UNPACKED_INCRKEY ){
61333     rc = -1;
61334   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
61335     /* Leave rc==0 */
61336   }else if( idx1<szHdr1 ){
61337     rc = 1;
61338   }
61339   return rc;
61340 }
61341 
61342 
61343 /*
61344 ** pCur points at an index entry created using the OP_MakeRecord opcode.
61345 ** Read the rowid (the last field in the record) and store it in *rowid.
61346 ** Return SQLITE_OK if everything works, or an error code otherwise.
61347 **
61348 ** pCur might be pointing to text obtained from a corrupt database file.
61349 ** So the content cannot be trusted.  Do appropriate checks on the content.
61350 */
61351 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
61352   i64 nCellKey = 0;
61353   int rc;
61354   u32 szHdr;        /* Size of the header */
61355   u32 typeRowid;    /* Serial type of the rowid */
61356   u32 lenRowid;     /* Size of the rowid */
61357   Mem m, v;
61358 
61359   UNUSED_PARAMETER(db);
61360 
61361   /* Get the size of the index entry.  Only indices entries of less
61362   ** than 2GiB are support - anything large must be database corruption.
61363   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
61364   ** this code can safely assume that nCellKey is 32-bits
61365   */
61366   assert( sqlite3BtreeCursorIsValid(pCur) );
61367   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
61368   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
61369   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
61370 
61371   /* Read in the complete content of the index entry */
61372   memset(&m, 0, sizeof(m));
61373   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
61374   if( rc ){
61375     return rc;
61376   }
61377 
61378   /* The index entry must begin with a header size */
61379   (void)getVarint32((u8*)m.z, szHdr);
61380   testcase( szHdr==3 );
61381   testcase( szHdr==m.n );
61382   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
61383     goto idx_rowid_corruption;
61384   }
61385 
61386   /* The last field of the index should be an integer - the ROWID.
61387   ** Verify that the last entry really is an integer. */
61388   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
61389   testcase( typeRowid==1 );
61390   testcase( typeRowid==2 );
61391   testcase( typeRowid==3 );
61392   testcase( typeRowid==4 );
61393   testcase( typeRowid==5 );
61394   testcase( typeRowid==6 );
61395   testcase( typeRowid==8 );
61396   testcase( typeRowid==9 );
61397   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
61398     goto idx_rowid_corruption;
61399   }
61400   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
61401   testcase( (u32)m.n==szHdr+lenRowid );
61402   if( unlikely((u32)m.n<szHdr+lenRowid) ){
61403     goto idx_rowid_corruption;
61404   }
61405 
61406   /* Fetch the integer off the end of the index record */
61407   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
61408   *rowid = v.u.i;
61409   sqlite3VdbeMemRelease(&m);
61410   return SQLITE_OK;
61411 
61412   /* Jump here if database corruption is detected after m has been
61413   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
61414 idx_rowid_corruption:
61415   testcase( m.zMalloc!=0 );
61416   sqlite3VdbeMemRelease(&m);
61417   return SQLITE_CORRUPT_BKPT;
61418 }
61419 
61420 /*
61421 ** Compare the key of the index entry that cursor pC is pointing to against
61422 ** the key string in pUnpacked.  Write into *pRes a number
61423 ** that is negative, zero, or positive if pC is less than, equal to,
61424 ** or greater than pUnpacked.  Return SQLITE_OK on success.
61425 **
61426 ** pUnpacked is either created without a rowid or is truncated so that it
61427 ** omits the rowid at the end.  The rowid at the end of the index entry
61428 ** is ignored as well.  Hence, this routine only compares the prefixes
61429 ** of the keys prior to the final rowid, not the entire key.
61430 */
61431 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
61432   VdbeCursor *pC,             /* The cursor to compare against */
61433   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
61434   int *res                    /* Write the comparison result here */
61435 ){
61436   i64 nCellKey = 0;
61437   int rc;
61438   BtCursor *pCur = pC->pCursor;
61439   Mem m;
61440 
61441   assert( sqlite3BtreeCursorIsValid(pCur) );
61442   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
61443   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
61444   /* nCellKey will always be between 0 and 0xffffffff because of the say
61445   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
61446   if( nCellKey<=0 || nCellKey>0x7fffffff ){
61447     *res = 0;
61448     return SQLITE_CORRUPT_BKPT;
61449   }
61450   memset(&m, 0, sizeof(m));
61451   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
61452   if( rc ){
61453     return rc;
61454   }
61455   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
61456   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
61457   sqlite3VdbeMemRelease(&m);
61458   return SQLITE_OK;
61459 }
61460 
61461 /*
61462 ** This routine sets the value to be returned by subsequent calls to
61463 ** sqlite3_changes() on the database handle 'db'.
61464 */
61465 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
61466   assert( sqlite3_mutex_held(db->mutex) );
61467   db->nChange = nChange;
61468   db->nTotalChange += nChange;
61469 }
61470 
61471 /*
61472 ** Set a flag in the vdbe to update the change counter when it is finalised
61473 ** or reset.
61474 */
61475 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
61476   v->changeCntOn = 1;
61477 }
61478 
61479 /*
61480 ** Mark every prepared statement associated with a database connection
61481 ** as expired.
61482 **
61483 ** An expired statement means that recompilation of the statement is
61484 ** recommend.  Statements expire when things happen that make their
61485 ** programs obsolete.  Removing user-defined functions or collating
61486 ** sequences, or changing an authorization function are the types of
61487 ** things that make prepared statements obsolete.
61488 */
61489 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
61490   Vdbe *p;
61491   for(p = db->pVdbe; p; p=p->pNext){
61492     p->expired = 1;
61493   }
61494 }
61495 
61496 /*
61497 ** Return the database associated with the Vdbe.
61498 */
61499 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
61500   return v->db;
61501 }
61502 
61503 /*
61504 ** Return a pointer to an sqlite3_value structure containing the value bound
61505 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
61506 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
61507 ** constants) to the value before returning it.
61508 **
61509 ** The returned value must be freed by the caller using sqlite3ValueFree().
61510 */
61511 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
61512   assert( iVar>0 );
61513   if( v ){
61514     Mem *pMem = &v->aVar[iVar-1];
61515     if( 0==(pMem->flags & MEM_Null) ){
61516       sqlite3_value *pRet = sqlite3ValueNew(v->db);
61517       if( pRet ){
61518         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
61519         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
61520         sqlite3VdbeMemStoreType((Mem *)pRet);
61521       }
61522       return pRet;
61523     }
61524   }
61525   return 0;
61526 }
61527 
61528 /*
61529 ** Configure SQL variable iVar so that binding a new value to it signals
61530 ** to sqlite3_reoptimize() that re-preparing the statement may result
61531 ** in a better query plan.
61532 */
61533 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
61534   assert( iVar>0 );
61535   if( iVar>32 ){
61536     v->expmask = 0xffffffff;
61537   }else{
61538     v->expmask |= ((u32)1 << (iVar-1));
61539   }
61540 }
61541 
61542 /************** End of vdbeaux.c *********************************************/
61543 /************** Begin file vdbeapi.c *****************************************/
61544 /*
61545 ** 2004 May 26
61546 **
61547 ** The author disclaims copyright to this source code.  In place of
61548 ** a legal notice, here is a blessing:
61549 **
61550 **    May you do good and not evil.
61551 **    May you find forgiveness for yourself and forgive others.
61552 **    May you share freely, never taking more than you give.
61553 **
61554 *************************************************************************
61555 **
61556 ** This file contains code use to implement APIs that are part of the
61557 ** VDBE.
61558 */
61559 
61560 #ifndef SQLITE_OMIT_DEPRECATED
61561 /*
61562 ** Return TRUE (non-zero) of the statement supplied as an argument needs
61563 ** to be recompiled.  A statement needs to be recompiled whenever the
61564 ** execution environment changes in a way that would alter the program
61565 ** that sqlite3_prepare() generates.  For example, if new functions or
61566 ** collating sequences are registered or if an authorizer function is
61567 ** added or changed.
61568 */
61569 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
61570   Vdbe *p = (Vdbe*)pStmt;
61571   return p==0 || p->expired;
61572 }
61573 #endif
61574 
61575 /*
61576 ** Check on a Vdbe to make sure it has not been finalized.  Log
61577 ** an error and return true if it has been finalized (or is otherwise
61578 ** invalid).  Return false if it is ok.
61579 */
61580 static int vdbeSafety(Vdbe *p){
61581   if( p->db==0 ){
61582     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
61583     return 1;
61584   }else{
61585     return 0;
61586   }
61587 }
61588 static int vdbeSafetyNotNull(Vdbe *p){
61589   if( p==0 ){
61590     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
61591     return 1;
61592   }else{
61593     return vdbeSafety(p);
61594   }
61595 }
61596 
61597 /*
61598 ** The following routine destroys a virtual machine that is created by
61599 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
61600 ** success/failure code that describes the result of executing the virtual
61601 ** machine.
61602 **
61603 ** This routine sets the error code and string returned by
61604 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61605 */
61606 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
61607   int rc;
61608   if( pStmt==0 ){
61609     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
61610     ** pointer is a harmless no-op. */
61611     rc = SQLITE_OK;
61612   }else{
61613     Vdbe *v = (Vdbe*)pStmt;
61614     sqlite3 *db = v->db;
61615 #if SQLITE_THREADSAFE
61616     sqlite3_mutex *mutex;
61617 #endif
61618     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
61619 #if SQLITE_THREADSAFE
61620     mutex = v->db->mutex;
61621 #endif
61622     sqlite3_mutex_enter(mutex);
61623     rc = sqlite3VdbeFinalize(v);
61624     rc = sqlite3ApiExit(db, rc);
61625     sqlite3_mutex_leave(mutex);
61626   }
61627   return rc;
61628 }
61629 
61630 /*
61631 ** Terminate the current execution of an SQL statement and reset it
61632 ** back to its starting state so that it can be reused. A success code from
61633 ** the prior execution is returned.
61634 **
61635 ** This routine sets the error code and string returned by
61636 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
61637 */
61638 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
61639   int rc;
61640   if( pStmt==0 ){
61641     rc = SQLITE_OK;
61642   }else{
61643     Vdbe *v = (Vdbe*)pStmt;
61644     sqlite3_mutex_enter(v->db->mutex);
61645     rc = sqlite3VdbeReset(v);
61646     sqlite3VdbeRewind(v);
61647     assert( (rc & (v->db->errMask))==rc );
61648     rc = sqlite3ApiExit(v->db, rc);
61649     sqlite3_mutex_leave(v->db->mutex);
61650   }
61651   return rc;
61652 }
61653 
61654 /*
61655 ** Set all the parameters in the compiled SQL statement to NULL.
61656 */
61657 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
61658   int i;
61659   int rc = SQLITE_OK;
61660   Vdbe *p = (Vdbe*)pStmt;
61661 #if SQLITE_THREADSAFE
61662   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
61663 #endif
61664   sqlite3_mutex_enter(mutex);
61665   for(i=0; i<p->nVar; i++){
61666     sqlite3VdbeMemRelease(&p->aVar[i]);
61667     p->aVar[i].flags = MEM_Null;
61668   }
61669   if( p->isPrepareV2 && p->expmask ){
61670     p->expired = 1;
61671   }
61672   sqlite3_mutex_leave(mutex);
61673   return rc;
61674 }
61675 
61676 
61677 /**************************** sqlite3_value_  *******************************
61678 ** The following routines extract information from a Mem or sqlite3_value
61679 ** structure.
61680 */
61681 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
61682   Mem *p = (Mem*)pVal;
61683   if( p->flags & (MEM_Blob|MEM_Str) ){
61684     sqlite3VdbeMemExpandBlob(p);
61685     p->flags &= ~MEM_Str;
61686     p->flags |= MEM_Blob;
61687     return p->n ? p->z : 0;
61688   }else{
61689     return sqlite3_value_text(pVal);
61690   }
61691 }
61692 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
61693   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
61694 }
61695 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
61696   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
61697 }
61698 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
61699   return sqlite3VdbeRealValue((Mem*)pVal);
61700 }
61701 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
61702   return (int)sqlite3VdbeIntValue((Mem*)pVal);
61703 }
61704 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
61705   return sqlite3VdbeIntValue((Mem*)pVal);
61706 }
61707 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
61708   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
61709 }
61710 #ifndef SQLITE_OMIT_UTF16
61711 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
61712   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
61713 }
61714 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
61715   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
61716 }
61717 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
61718   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
61719 }
61720 #endif /* SQLITE_OMIT_UTF16 */
61721 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
61722   return pVal->type;
61723 }
61724 
61725 /**************************** sqlite3_result_  *******************************
61726 ** The following routines are used by user-defined functions to specify
61727 ** the function result.
61728 **
61729 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
61730 ** result as a string or blob but if the string or blob is too large, it
61731 ** then sets the error code to SQLITE_TOOBIG
61732 */
61733 static void setResultStrOrError(
61734   sqlite3_context *pCtx,  /* Function context */
61735   const char *z,          /* String pointer */
61736   int n,                  /* Bytes in string, or negative */
61737   u8 enc,                 /* Encoding of z.  0 for BLOBs */
61738   void (*xDel)(void*)     /* Destructor function */
61739 ){
61740   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
61741     sqlite3_result_error_toobig(pCtx);
61742   }
61743 }
61744 SQLITE_API void sqlite3_result_blob(
61745   sqlite3_context *pCtx,
61746   const void *z,
61747   int n,
61748   void (*xDel)(void *)
61749 ){
61750   assert( n>=0 );
61751   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61752   setResultStrOrError(pCtx, z, n, 0, xDel);
61753 }
61754 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
61755   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61756   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
61757 }
61758 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
61759   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61760   pCtx->isError = SQLITE_ERROR;
61761   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
61762 }
61763 #ifndef SQLITE_OMIT_UTF16
61764 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
61765   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61766   pCtx->isError = SQLITE_ERROR;
61767   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
61768 }
61769 #endif
61770 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
61771   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61772   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
61773 }
61774 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
61775   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61776   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
61777 }
61778 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
61779   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61780   sqlite3VdbeMemSetNull(&pCtx->s);
61781 }
61782 SQLITE_API void sqlite3_result_text(
61783   sqlite3_context *pCtx,
61784   const char *z,
61785   int n,
61786   void (*xDel)(void *)
61787 ){
61788   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61789   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
61790 }
61791 #ifndef SQLITE_OMIT_UTF16
61792 SQLITE_API void sqlite3_result_text16(
61793   sqlite3_context *pCtx,
61794   const void *z,
61795   int n,
61796   void (*xDel)(void *)
61797 ){
61798   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61799   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
61800 }
61801 SQLITE_API void sqlite3_result_text16be(
61802   sqlite3_context *pCtx,
61803   const void *z,
61804   int n,
61805   void (*xDel)(void *)
61806 ){
61807   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61808   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
61809 }
61810 SQLITE_API void sqlite3_result_text16le(
61811   sqlite3_context *pCtx,
61812   const void *z,
61813   int n,
61814   void (*xDel)(void *)
61815 ){
61816   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61817   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
61818 }
61819 #endif /* SQLITE_OMIT_UTF16 */
61820 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
61821   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61822   sqlite3VdbeMemCopy(&pCtx->s, pValue);
61823 }
61824 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
61825   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61826   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
61827 }
61828 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
61829   pCtx->isError = errCode;
61830   if( pCtx->s.flags & MEM_Null ){
61831     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
61832                          SQLITE_UTF8, SQLITE_STATIC);
61833   }
61834 }
61835 
61836 /* Force an SQLITE_TOOBIG error. */
61837 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
61838   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61839   pCtx->isError = SQLITE_TOOBIG;
61840   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
61841                        SQLITE_UTF8, SQLITE_STATIC);
61842 }
61843 
61844 /* An SQLITE_NOMEM error. */
61845 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
61846   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
61847   sqlite3VdbeMemSetNull(&pCtx->s);
61848   pCtx->isError = SQLITE_NOMEM;
61849   pCtx->s.db->mallocFailed = 1;
61850 }
61851 
61852 /*
61853 ** This function is called after a transaction has been committed. It
61854 ** invokes callbacks registered with sqlite3_wal_hook() as required.
61855 */
61856 static int doWalCallbacks(sqlite3 *db){
61857   int rc = SQLITE_OK;
61858 #ifndef SQLITE_OMIT_WAL
61859   int i;
61860   for(i=0; i<db->nDb; i++){
61861     Btree *pBt = db->aDb[i].pBt;
61862     if( pBt ){
61863       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
61864       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
61865         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
61866       }
61867     }
61868   }
61869 #endif
61870   return rc;
61871 }
61872 
61873 /*
61874 ** Execute the statement pStmt, either until a row of data is ready, the
61875 ** statement is completely executed or an error occurs.
61876 **
61877 ** This routine implements the bulk of the logic behind the sqlite_step()
61878 ** API.  The only thing omitted is the automatic recompile if a
61879 ** schema change has occurred.  That detail is handled by the
61880 ** outer sqlite3_step() wrapper procedure.
61881 */
61882 static int sqlite3Step(Vdbe *p){
61883   sqlite3 *db;
61884   int rc;
61885 
61886   assert(p);
61887   if( p->magic!=VDBE_MAGIC_RUN ){
61888     /* We used to require that sqlite3_reset() be called before retrying
61889     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
61890     ** with version 3.7.0, we changed this so that sqlite3_reset() would
61891     ** be called automatically instead of throwing the SQLITE_MISUSE error.
61892     ** This "automatic-reset" change is not technically an incompatibility,
61893     ** since any application that receives an SQLITE_MISUSE is broken by
61894     ** definition.
61895     **
61896     ** Nevertheless, some published applications that were originally written
61897     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
61898     ** returns, and the so were broken by the automatic-reset change.  As a
61899     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
61900     ** legacy behavior of returning SQLITE_MISUSE for cases where the
61901     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
61902     ** or SQLITE_BUSY error.
61903     */
61904 #ifdef SQLITE_OMIT_AUTORESET
61905     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
61906       sqlite3_reset((sqlite3_stmt*)p);
61907     }else{
61908       return SQLITE_MISUSE_BKPT;
61909     }
61910 #else
61911     sqlite3_reset((sqlite3_stmt*)p);
61912 #endif
61913   }
61914 
61915   /* Check that malloc() has not failed. If it has, return early. */
61916   db = p->db;
61917   if( db->mallocFailed ){
61918     p->rc = SQLITE_NOMEM;
61919     return SQLITE_NOMEM;
61920   }
61921 
61922   if( p->pc<=0 && p->expired ){
61923     p->rc = SQLITE_SCHEMA;
61924     rc = SQLITE_ERROR;
61925     goto end_of_step;
61926   }
61927   if( p->pc<0 ){
61928     /* If there are no other statements currently running, then
61929     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
61930     ** from interrupting a statement that has not yet started.
61931     */
61932     if( db->activeVdbeCnt==0 ){
61933       db->u1.isInterrupted = 0;
61934     }
61935 
61936     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
61937 
61938 #ifndef SQLITE_OMIT_TRACE
61939     if( db->xProfile && !db->init.busy ){
61940       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
61941     }
61942 #endif
61943 
61944     db->activeVdbeCnt++;
61945     if( p->readOnly==0 ) db->writeVdbeCnt++;
61946     p->pc = 0;
61947   }
61948 #ifndef SQLITE_OMIT_EXPLAIN
61949   if( p->explain ){
61950     rc = sqlite3VdbeList(p);
61951   }else
61952 #endif /* SQLITE_OMIT_EXPLAIN */
61953   {
61954     db->vdbeExecCnt++;
61955     rc = sqlite3VdbeExec(p);
61956     db->vdbeExecCnt--;
61957   }
61958 
61959 #ifndef SQLITE_OMIT_TRACE
61960   /* Invoke the profile callback if there is one
61961   */
61962   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
61963     sqlite3_int64 iNow;
61964     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
61965     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
61966   }
61967 #endif
61968 
61969   if( rc==SQLITE_DONE ){
61970     assert( p->rc==SQLITE_OK );
61971     p->rc = doWalCallbacks(db);
61972     if( p->rc!=SQLITE_OK ){
61973       rc = SQLITE_ERROR;
61974     }
61975   }
61976 
61977   db->errCode = rc;
61978   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
61979     p->rc = SQLITE_NOMEM;
61980   }
61981 end_of_step:
61982   /* At this point local variable rc holds the value that should be
61983   ** returned if this statement was compiled using the legacy
61984   ** sqlite3_prepare() interface. According to the docs, this can only
61985   ** be one of the values in the first assert() below. Variable p->rc
61986   ** contains the value that would be returned if sqlite3_finalize()
61987   ** were called on statement p.
61988   */
61989   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
61990        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
61991   );
61992   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
61993   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
61994     /* If this statement was prepared using sqlite3_prepare_v2(), and an
61995     ** error has occured, then return the error code in p->rc to the
61996     ** caller. Set the error code in the database handle to the same value.
61997     */
61998     rc = db->errCode = p->rc;
61999   }
62000   return (rc&db->errMask);
62001 }
62002 
62003 /*
62004 ** The maximum number of times that a statement will try to reparse
62005 ** itself before giving up and returning SQLITE_SCHEMA.
62006 */
62007 #ifndef SQLITE_MAX_SCHEMA_RETRY
62008 # define SQLITE_MAX_SCHEMA_RETRY 5
62009 #endif
62010 
62011 /*
62012 ** This is the top-level implementation of sqlite3_step().  Call
62013 ** sqlite3Step() to do most of the work.  If a schema error occurs,
62014 ** call sqlite3Reprepare() and try again.
62015 */
62016 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
62017   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
62018   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
62019   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
62020   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
62021   sqlite3 *db;             /* The database connection */
62022 
62023   if( vdbeSafetyNotNull(v) ){
62024     return SQLITE_MISUSE_BKPT;
62025   }
62026   db = v->db;
62027   sqlite3_mutex_enter(db->mutex);
62028   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
62029          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
62030          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
62031     sqlite3_reset(pStmt);
62032     assert( v->expired==0 );
62033   }
62034   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
62035     /* This case occurs after failing to recompile an sql statement.
62036     ** The error message from the SQL compiler has already been loaded
62037     ** into the database handle. This block copies the error message
62038     ** from the database handle into the statement and sets the statement
62039     ** program counter to 0 to ensure that when the statement is
62040     ** finalized or reset the parser error message is available via
62041     ** sqlite3_errmsg() and sqlite3_errcode().
62042     */
62043     const char *zErr = (const char *)sqlite3_value_text(db->pErr);
62044     sqlite3DbFree(db, v->zErrMsg);
62045     if( !db->mallocFailed ){
62046       v->zErrMsg = sqlite3DbStrDup(db, zErr);
62047       v->rc = rc2;
62048     } else {
62049       v->zErrMsg = 0;
62050       v->rc = rc = SQLITE_NOMEM;
62051     }
62052   }
62053   rc = sqlite3ApiExit(db, rc);
62054   sqlite3_mutex_leave(db->mutex);
62055   return rc;
62056 }
62057 
62058 /*
62059 ** Extract the user data from a sqlite3_context structure and return a
62060 ** pointer to it.
62061 */
62062 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
62063   assert( p && p->pFunc );
62064   return p->pFunc->pUserData;
62065 }
62066 
62067 /*
62068 ** Extract the user data from a sqlite3_context structure and return a
62069 ** pointer to it.
62070 **
62071 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
62072 ** returns a copy of the pointer to the database connection (the 1st
62073 ** parameter) of the sqlite3_create_function() and
62074 ** sqlite3_create_function16() routines that originally registered the
62075 ** application defined function.
62076 */
62077 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
62078   assert( p && p->pFunc );
62079   return p->s.db;
62080 }
62081 
62082 /*
62083 ** The following is the implementation of an SQL function that always
62084 ** fails with an error message stating that the function is used in the
62085 ** wrong context.  The sqlite3_overload_function() API might construct
62086 ** SQL function that use this routine so that the functions will exist
62087 ** for name resolution but are actually overloaded by the xFindFunction
62088 ** method of virtual tables.
62089 */
62090 SQLITE_PRIVATE void sqlite3InvalidFunction(
62091   sqlite3_context *context,  /* The function calling context */
62092   int NotUsed,               /* Number of arguments to the function */
62093   sqlite3_value **NotUsed2   /* Value of each argument */
62094 ){
62095   const char *zName = context->pFunc->zName;
62096   char *zErr;
62097   UNUSED_PARAMETER2(NotUsed, NotUsed2);
62098   zErr = sqlite3_mprintf(
62099       "unable to use function %s in the requested context", zName);
62100   sqlite3_result_error(context, zErr, -1);
62101   sqlite3_free(zErr);
62102 }
62103 
62104 /*
62105 ** Allocate or return the aggregate context for a user function.  A new
62106 ** context is allocated on the first call.  Subsequent calls return the
62107 ** same context that was returned on prior calls.
62108 */
62109 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
62110   Mem *pMem;
62111   assert( p && p->pFunc && p->pFunc->xStep );
62112   assert( sqlite3_mutex_held(p->s.db->mutex) );
62113   pMem = p->pMem;
62114   testcase( nByte<0 );
62115   if( (pMem->flags & MEM_Agg)==0 ){
62116     if( nByte<=0 ){
62117       sqlite3VdbeMemReleaseExternal(pMem);
62118       pMem->flags = MEM_Null;
62119       pMem->z = 0;
62120     }else{
62121       sqlite3VdbeMemGrow(pMem, nByte, 0);
62122       pMem->flags = MEM_Agg;
62123       pMem->u.pDef = p->pFunc;
62124       if( pMem->z ){
62125         memset(pMem->z, 0, nByte);
62126       }
62127     }
62128   }
62129   return (void*)pMem->z;
62130 }
62131 
62132 /*
62133 ** Return the auxilary data pointer, if any, for the iArg'th argument to
62134 ** the user-function defined by pCtx.
62135 */
62136 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
62137   VdbeFunc *pVdbeFunc;
62138 
62139   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62140   pVdbeFunc = pCtx->pVdbeFunc;
62141   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
62142     return 0;
62143   }
62144   return pVdbeFunc->apAux[iArg].pAux;
62145 }
62146 
62147 /*
62148 ** Set the auxilary data pointer and delete function, for the iArg'th
62149 ** argument to the user-function defined by pCtx. Any previous value is
62150 ** deleted by calling the delete function specified when it was set.
62151 */
62152 SQLITE_API void sqlite3_set_auxdata(
62153   sqlite3_context *pCtx,
62154   int iArg,
62155   void *pAux,
62156   void (*xDelete)(void*)
62157 ){
62158   struct AuxData *pAuxData;
62159   VdbeFunc *pVdbeFunc;
62160   if( iArg<0 ) goto failed;
62161 
62162   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62163   pVdbeFunc = pCtx->pVdbeFunc;
62164   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
62165     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
62166     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
62167     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
62168     if( !pVdbeFunc ){
62169       goto failed;
62170     }
62171     pCtx->pVdbeFunc = pVdbeFunc;
62172     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
62173     pVdbeFunc->nAux = iArg+1;
62174     pVdbeFunc->pFunc = pCtx->pFunc;
62175   }
62176 
62177   pAuxData = &pVdbeFunc->apAux[iArg];
62178   if( pAuxData->pAux && pAuxData->xDelete ){
62179     pAuxData->xDelete(pAuxData->pAux);
62180   }
62181   pAuxData->pAux = pAux;
62182   pAuxData->xDelete = xDelete;
62183   return;
62184 
62185 failed:
62186   if( xDelete ){
62187     xDelete(pAux);
62188   }
62189 }
62190 
62191 #ifndef SQLITE_OMIT_DEPRECATED
62192 /*
62193 ** Return the number of times the Step function of a aggregate has been
62194 ** called.
62195 **
62196 ** This function is deprecated.  Do not use it for new code.  It is
62197 ** provide only to avoid breaking legacy code.  New aggregate function
62198 ** implementations should keep their own counts within their aggregate
62199 ** context.
62200 */
62201 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
62202   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
62203   return p->pMem->n;
62204 }
62205 #endif
62206 
62207 /*
62208 ** Return the number of columns in the result set for the statement pStmt.
62209 */
62210 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
62211   Vdbe *pVm = (Vdbe *)pStmt;
62212   return pVm ? pVm->nResColumn : 0;
62213 }
62214 
62215 /*
62216 ** Return the number of values available from the current row of the
62217 ** currently executing statement pStmt.
62218 */
62219 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
62220   Vdbe *pVm = (Vdbe *)pStmt;
62221   if( pVm==0 || pVm->pResultSet==0 ) return 0;
62222   return pVm->nResColumn;
62223 }
62224 
62225 
62226 /*
62227 ** Check to see if column iCol of the given statement is valid.  If
62228 ** it is, return a pointer to the Mem for the value of that column.
62229 ** If iCol is not valid, return a pointer to a Mem which has a value
62230 ** of NULL.
62231 */
62232 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
62233   Vdbe *pVm;
62234   Mem *pOut;
62235 
62236   pVm = (Vdbe *)pStmt;
62237   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
62238     sqlite3_mutex_enter(pVm->db->mutex);
62239     pOut = &pVm->pResultSet[i];
62240   }else{
62241     /* If the value passed as the second argument is out of range, return
62242     ** a pointer to the following static Mem object which contains the
62243     ** value SQL NULL. Even though the Mem structure contains an element
62244     ** of type i64, on certain architecture (x86) with certain compiler
62245     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
62246     ** instead of an 8-byte one. This all works fine, except that when
62247     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
62248     ** that a Mem structure is located on an 8-byte boundary. To prevent
62249     ** this assert() from failing, when building with SQLITE_DEBUG defined
62250     ** using gcc, force nullMem to be 8-byte aligned using the magical
62251     ** __attribute__((aligned(8))) macro.  */
62252     static const Mem nullMem
62253 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
62254       __attribute__((aligned(8)))
62255 #endif
62256       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
62257 #ifdef SQLITE_DEBUG
62258          0, 0,  /* pScopyFrom, pFiller */
62259 #endif
62260          0, 0 };
62261 
62262     if( pVm && ALWAYS(pVm->db) ){
62263       sqlite3_mutex_enter(pVm->db->mutex);
62264       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
62265     }
62266     pOut = (Mem*)&nullMem;
62267   }
62268   return pOut;
62269 }
62270 
62271 /*
62272 ** This function is called after invoking an sqlite3_value_XXX function on a
62273 ** column value (i.e. a value returned by evaluating an SQL expression in the
62274 ** select list of a SELECT statement) that may cause a malloc() failure. If
62275 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
62276 ** code of statement pStmt set to SQLITE_NOMEM.
62277 **
62278 ** Specifically, this is called from within:
62279 **
62280 **     sqlite3_column_int()
62281 **     sqlite3_column_int64()
62282 **     sqlite3_column_text()
62283 **     sqlite3_column_text16()
62284 **     sqlite3_column_real()
62285 **     sqlite3_column_bytes()
62286 **     sqlite3_column_bytes16()
62287 **     sqiite3_column_blob()
62288 */
62289 static void columnMallocFailure(sqlite3_stmt *pStmt)
62290 {
62291   /* If malloc() failed during an encoding conversion within an
62292   ** sqlite3_column_XXX API, then set the return code of the statement to
62293   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
62294   ** and _finalize() will return NOMEM.
62295   */
62296   Vdbe *p = (Vdbe *)pStmt;
62297   if( p ){
62298     p->rc = sqlite3ApiExit(p->db, p->rc);
62299     sqlite3_mutex_leave(p->db->mutex);
62300   }
62301 }
62302 
62303 /**************************** sqlite3_column_  *******************************
62304 ** The following routines are used to access elements of the current row
62305 ** in the result set.
62306 */
62307 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
62308   const void *val;
62309   val = sqlite3_value_blob( columnMem(pStmt,i) );
62310   /* Even though there is no encoding conversion, value_blob() might
62311   ** need to call malloc() to expand the result of a zeroblob()
62312   ** expression.
62313   */
62314   columnMallocFailure(pStmt);
62315   return val;
62316 }
62317 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
62318   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
62319   columnMallocFailure(pStmt);
62320   return val;
62321 }
62322 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
62323   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
62324   columnMallocFailure(pStmt);
62325   return val;
62326 }
62327 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
62328   double val = sqlite3_value_double( columnMem(pStmt,i) );
62329   columnMallocFailure(pStmt);
62330   return val;
62331 }
62332 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
62333   int val = sqlite3_value_int( columnMem(pStmt,i) );
62334   columnMallocFailure(pStmt);
62335   return val;
62336 }
62337 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
62338   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
62339   columnMallocFailure(pStmt);
62340   return val;
62341 }
62342 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
62343   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
62344   columnMallocFailure(pStmt);
62345   return val;
62346 }
62347 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
62348   Mem *pOut = columnMem(pStmt, i);
62349   if( pOut->flags&MEM_Static ){
62350     pOut->flags &= ~MEM_Static;
62351     pOut->flags |= MEM_Ephem;
62352   }
62353   columnMallocFailure(pStmt);
62354   return (sqlite3_value *)pOut;
62355 }
62356 #ifndef SQLITE_OMIT_UTF16
62357 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
62358   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
62359   columnMallocFailure(pStmt);
62360   return val;
62361 }
62362 #endif /* SQLITE_OMIT_UTF16 */
62363 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
62364   int iType = sqlite3_value_type( columnMem(pStmt,i) );
62365   columnMallocFailure(pStmt);
62366   return iType;
62367 }
62368 
62369 /* The following function is experimental and subject to change or
62370 ** removal */
62371 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
62372 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
62373 **}
62374 */
62375 
62376 /*
62377 ** Convert the N-th element of pStmt->pColName[] into a string using
62378 ** xFunc() then return that string.  If N is out of range, return 0.
62379 **
62380 ** There are up to 5 names for each column.  useType determines which
62381 ** name is returned.  Here are the names:
62382 **
62383 **    0      The column name as it should be displayed for output
62384 **    1      The datatype name for the column
62385 **    2      The name of the database that the column derives from
62386 **    3      The name of the table that the column derives from
62387 **    4      The name of the table column that the result column derives from
62388 **
62389 ** If the result is not a simple column reference (if it is an expression
62390 ** or a constant) then useTypes 2, 3, and 4 return NULL.
62391 */
62392 static const void *columnName(
62393   sqlite3_stmt *pStmt,
62394   int N,
62395   const void *(*xFunc)(Mem*),
62396   int useType
62397 ){
62398   const void *ret = 0;
62399   Vdbe *p = (Vdbe *)pStmt;
62400   int n;
62401   sqlite3 *db = p->db;
62402 
62403   assert( db!=0 );
62404   n = sqlite3_column_count(pStmt);
62405   if( N<n && N>=0 ){
62406     N += useType*n;
62407     sqlite3_mutex_enter(db->mutex);
62408     assert( db->mallocFailed==0 );
62409     ret = xFunc(&p->aColName[N]);
62410      /* A malloc may have failed inside of the xFunc() call. If this
62411     ** is the case, clear the mallocFailed flag and return NULL.
62412     */
62413     if( db->mallocFailed ){
62414       db->mallocFailed = 0;
62415       ret = 0;
62416     }
62417     sqlite3_mutex_leave(db->mutex);
62418   }
62419   return ret;
62420 }
62421 
62422 /*
62423 ** Return the name of the Nth column of the result set returned by SQL
62424 ** statement pStmt.
62425 */
62426 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
62427   return columnName(
62428       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
62429 }
62430 #ifndef SQLITE_OMIT_UTF16
62431 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
62432   return columnName(
62433       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
62434 }
62435 #endif
62436 
62437 /*
62438 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
62439 ** not define OMIT_DECLTYPE.
62440 */
62441 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
62442 # error "Must not define both SQLITE_OMIT_DECLTYPE \
62443          and SQLITE_ENABLE_COLUMN_METADATA"
62444 #endif
62445 
62446 #ifndef SQLITE_OMIT_DECLTYPE
62447 /*
62448 ** Return the column declaration type (if applicable) of the 'i'th column
62449 ** of the result set of SQL statement pStmt.
62450 */
62451 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
62452   return columnName(
62453       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
62454 }
62455 #ifndef SQLITE_OMIT_UTF16
62456 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
62457   return columnName(
62458       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
62459 }
62460 #endif /* SQLITE_OMIT_UTF16 */
62461 #endif /* SQLITE_OMIT_DECLTYPE */
62462 
62463 #ifdef SQLITE_ENABLE_COLUMN_METADATA
62464 /*
62465 ** Return the name of the database from which a result column derives.
62466 ** NULL is returned if the result column is an expression or constant or
62467 ** anything else which is not an unabiguous reference to a database column.
62468 */
62469 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
62470   return columnName(
62471       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
62472 }
62473 #ifndef SQLITE_OMIT_UTF16
62474 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
62475   return columnName(
62476       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
62477 }
62478 #endif /* SQLITE_OMIT_UTF16 */
62479 
62480 /*
62481 ** Return the name of the table from which a result column derives.
62482 ** NULL is returned if the result column is an expression or constant or
62483 ** anything else which is not an unabiguous reference to a database column.
62484 */
62485 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
62486   return columnName(
62487       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
62488 }
62489 #ifndef SQLITE_OMIT_UTF16
62490 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
62491   return columnName(
62492       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
62493 }
62494 #endif /* SQLITE_OMIT_UTF16 */
62495 
62496 /*
62497 ** Return the name of the table column from which a result column derives.
62498 ** NULL is returned if the result column is an expression or constant or
62499 ** anything else which is not an unabiguous reference to a database column.
62500 */
62501 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
62502   return columnName(
62503       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
62504 }
62505 #ifndef SQLITE_OMIT_UTF16
62506 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
62507   return columnName(
62508       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
62509 }
62510 #endif /* SQLITE_OMIT_UTF16 */
62511 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
62512 
62513 
62514 /******************************* sqlite3_bind_  ***************************
62515 **
62516 ** Routines used to attach values to wildcards in a compiled SQL statement.
62517 */
62518 /*
62519 ** Unbind the value bound to variable i in virtual machine p. This is the
62520 ** the same as binding a NULL value to the column. If the "i" parameter is
62521 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
62522 **
62523 ** A successful evaluation of this routine acquires the mutex on p.
62524 ** the mutex is released if any kind of error occurs.
62525 **
62526 ** The error code stored in database p->db is overwritten with the return
62527 ** value in any case.
62528 */
62529 static int vdbeUnbind(Vdbe *p, int i){
62530   Mem *pVar;
62531   if( vdbeSafetyNotNull(p) ){
62532     return SQLITE_MISUSE_BKPT;
62533   }
62534   sqlite3_mutex_enter(p->db->mutex);
62535   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
62536     sqlite3Error(p->db, SQLITE_MISUSE, 0);
62537     sqlite3_mutex_leave(p->db->mutex);
62538     sqlite3_log(SQLITE_MISUSE,
62539         "bind on a busy prepared statement: [%s]", p->zSql);
62540     return SQLITE_MISUSE_BKPT;
62541   }
62542   if( i<1 || i>p->nVar ){
62543     sqlite3Error(p->db, SQLITE_RANGE, 0);
62544     sqlite3_mutex_leave(p->db->mutex);
62545     return SQLITE_RANGE;
62546   }
62547   i--;
62548   pVar = &p->aVar[i];
62549   sqlite3VdbeMemRelease(pVar);
62550   pVar->flags = MEM_Null;
62551   sqlite3Error(p->db, SQLITE_OK, 0);
62552 
62553   /* If the bit corresponding to this variable in Vdbe.expmask is set, then
62554   ** binding a new value to this variable invalidates the current query plan.
62555   **
62556   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
62557   ** parameter in the WHERE clause might influence the choice of query plan
62558   ** for a statement, then the statement will be automatically recompiled,
62559   ** as if there had been a schema change, on the first sqlite3_step() call
62560   ** following any change to the bindings of that parameter.
62561   */
62562   if( p->isPrepareV2 &&
62563      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
62564   ){
62565     p->expired = 1;
62566   }
62567   return SQLITE_OK;
62568 }
62569 
62570 /*
62571 ** Bind a text or BLOB value.
62572 */
62573 static int bindText(
62574   sqlite3_stmt *pStmt,   /* The statement to bind against */
62575   int i,                 /* Index of the parameter to bind */
62576   const void *zData,     /* Pointer to the data to be bound */
62577   int nData,             /* Number of bytes of data to be bound */
62578   void (*xDel)(void*),   /* Destructor for the data */
62579   u8 encoding            /* Encoding for the data */
62580 ){
62581   Vdbe *p = (Vdbe *)pStmt;
62582   Mem *pVar;
62583   int rc;
62584 
62585   rc = vdbeUnbind(p, i);
62586   if( rc==SQLITE_OK ){
62587     if( zData!=0 ){
62588       pVar = &p->aVar[i-1];
62589       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
62590       if( rc==SQLITE_OK && encoding!=0 ){
62591         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
62592       }
62593       sqlite3Error(p->db, rc, 0);
62594       rc = sqlite3ApiExit(p->db, rc);
62595     }
62596     sqlite3_mutex_leave(p->db->mutex);
62597   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
62598     xDel((void*)zData);
62599   }
62600   return rc;
62601 }
62602 
62603 
62604 /*
62605 ** Bind a blob value to an SQL statement variable.
62606 */
62607 SQLITE_API int sqlite3_bind_blob(
62608   sqlite3_stmt *pStmt,
62609   int i,
62610   const void *zData,
62611   int nData,
62612   void (*xDel)(void*)
62613 ){
62614   return bindText(pStmt, i, zData, nData, xDel, 0);
62615 }
62616 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
62617   int rc;
62618   Vdbe *p = (Vdbe *)pStmt;
62619   rc = vdbeUnbind(p, i);
62620   if( rc==SQLITE_OK ){
62621     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
62622     sqlite3_mutex_leave(p->db->mutex);
62623   }
62624   return rc;
62625 }
62626 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
62627   return sqlite3_bind_int64(p, i, (i64)iValue);
62628 }
62629 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
62630   int rc;
62631   Vdbe *p = (Vdbe *)pStmt;
62632   rc = vdbeUnbind(p, i);
62633   if( rc==SQLITE_OK ){
62634     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
62635     sqlite3_mutex_leave(p->db->mutex);
62636   }
62637   return rc;
62638 }
62639 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
62640   int rc;
62641   Vdbe *p = (Vdbe*)pStmt;
62642   rc = vdbeUnbind(p, i);
62643   if( rc==SQLITE_OK ){
62644     sqlite3_mutex_leave(p->db->mutex);
62645   }
62646   return rc;
62647 }
62648 SQLITE_API int sqlite3_bind_text(
62649   sqlite3_stmt *pStmt,
62650   int i,
62651   const char *zData,
62652   int nData,
62653   void (*xDel)(void*)
62654 ){
62655   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
62656 }
62657 #ifndef SQLITE_OMIT_UTF16
62658 SQLITE_API int sqlite3_bind_text16(
62659   sqlite3_stmt *pStmt,
62660   int i,
62661   const void *zData,
62662   int nData,
62663   void (*xDel)(void*)
62664 ){
62665   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
62666 }
62667 #endif /* SQLITE_OMIT_UTF16 */
62668 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
62669   int rc;
62670   switch( pValue->type ){
62671     case SQLITE_INTEGER: {
62672       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
62673       break;
62674     }
62675     case SQLITE_FLOAT: {
62676       rc = sqlite3_bind_double(pStmt, i, pValue->r);
62677       break;
62678     }
62679     case SQLITE_BLOB: {
62680       if( pValue->flags & MEM_Zero ){
62681         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
62682       }else{
62683         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
62684       }
62685       break;
62686     }
62687     case SQLITE_TEXT: {
62688       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
62689                               pValue->enc);
62690       break;
62691     }
62692     default: {
62693       rc = sqlite3_bind_null(pStmt, i);
62694       break;
62695     }
62696   }
62697   return rc;
62698 }
62699 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
62700   int rc;
62701   Vdbe *p = (Vdbe *)pStmt;
62702   rc = vdbeUnbind(p, i);
62703   if( rc==SQLITE_OK ){
62704     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
62705     sqlite3_mutex_leave(p->db->mutex);
62706   }
62707   return rc;
62708 }
62709 
62710 /*
62711 ** Return the number of wildcards that can be potentially bound to.
62712 ** This routine is added to support DBD::SQLite.
62713 */
62714 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
62715   Vdbe *p = (Vdbe*)pStmt;
62716   return p ? p->nVar : 0;
62717 }
62718 
62719 /*
62720 ** Return the name of a wildcard parameter.  Return NULL if the index
62721 ** is out of range or if the wildcard is unnamed.
62722 **
62723 ** The result is always UTF-8.
62724 */
62725 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
62726   Vdbe *p = (Vdbe*)pStmt;
62727   if( p==0 || i<1 || i>p->nzVar ){
62728     return 0;
62729   }
62730   return p->azVar[i-1];
62731 }
62732 
62733 /*
62734 ** Given a wildcard parameter name, return the index of the variable
62735 ** with that name.  If there is no variable with the given name,
62736 ** return 0.
62737 */
62738 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
62739   int i;
62740   if( p==0 ){
62741     return 0;
62742   }
62743   if( zName ){
62744     for(i=0; i<p->nzVar; i++){
62745       const char *z = p->azVar[i];
62746       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
62747         return i+1;
62748       }
62749     }
62750   }
62751   return 0;
62752 }
62753 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
62754   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
62755 }
62756 
62757 /*
62758 ** Transfer all bindings from the first statement over to the second.
62759 */
62760 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62761   Vdbe *pFrom = (Vdbe*)pFromStmt;
62762   Vdbe *pTo = (Vdbe*)pToStmt;
62763   int i;
62764   assert( pTo->db==pFrom->db );
62765   assert( pTo->nVar==pFrom->nVar );
62766   sqlite3_mutex_enter(pTo->db->mutex);
62767   for(i=0; i<pFrom->nVar; i++){
62768     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
62769   }
62770   sqlite3_mutex_leave(pTo->db->mutex);
62771   return SQLITE_OK;
62772 }
62773 
62774 #ifndef SQLITE_OMIT_DEPRECATED
62775 /*
62776 ** Deprecated external interface.  Internal/core SQLite code
62777 ** should call sqlite3TransferBindings.
62778 **
62779 ** Is is misuse to call this routine with statements from different
62780 ** database connections.  But as this is a deprecated interface, we
62781 ** will not bother to check for that condition.
62782 **
62783 ** If the two statements contain a different number of bindings, then
62784 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
62785 ** SQLITE_OK is returned.
62786 */
62787 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
62788   Vdbe *pFrom = (Vdbe*)pFromStmt;
62789   Vdbe *pTo = (Vdbe*)pToStmt;
62790   if( pFrom->nVar!=pTo->nVar ){
62791     return SQLITE_ERROR;
62792   }
62793   if( pTo->isPrepareV2 && pTo->expmask ){
62794     pTo->expired = 1;
62795   }
62796   if( pFrom->isPrepareV2 && pFrom->expmask ){
62797     pFrom->expired = 1;
62798   }
62799   return sqlite3TransferBindings(pFromStmt, pToStmt);
62800 }
62801 #endif
62802 
62803 /*
62804 ** Return the sqlite3* database handle to which the prepared statement given
62805 ** in the argument belongs.  This is the same database handle that was
62806 ** the first argument to the sqlite3_prepare() that was used to create
62807 ** the statement in the first place.
62808 */
62809 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
62810   return pStmt ? ((Vdbe*)pStmt)->db : 0;
62811 }
62812 
62813 /*
62814 ** Return true if the prepared statement is guaranteed to not modify the
62815 ** database.
62816 */
62817 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
62818   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
62819 }
62820 
62821 /*
62822 ** Return a pointer to the next prepared statement after pStmt associated
62823 ** with database connection pDb.  If pStmt is NULL, return the first
62824 ** prepared statement for the database connection.  Return NULL if there
62825 ** are no more.
62826 */
62827 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
62828   sqlite3_stmt *pNext;
62829   sqlite3_mutex_enter(pDb->mutex);
62830   if( pStmt==0 ){
62831     pNext = (sqlite3_stmt*)pDb->pVdbe;
62832   }else{
62833     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
62834   }
62835   sqlite3_mutex_leave(pDb->mutex);
62836   return pNext;
62837 }
62838 
62839 /*
62840 ** Return the value of a status counter for a prepared statement
62841 */
62842 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
62843   Vdbe *pVdbe = (Vdbe*)pStmt;
62844   int v = pVdbe->aCounter[op-1];
62845   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
62846   return v;
62847 }
62848 
62849 /************** End of vdbeapi.c *********************************************/
62850 /************** Begin file vdbetrace.c ***************************************/
62851 /*
62852 ** 2009 November 25
62853 **
62854 ** The author disclaims copyright to this source code.  In place of
62855 ** a legal notice, here is a blessing:
62856 **
62857 **    May you do good and not evil.
62858 **    May you find forgiveness for yourself and forgive others.
62859 **    May you share freely, never taking more than you give.
62860 **
62861 *************************************************************************
62862 **
62863 ** This file contains code used to insert the values of host parameters
62864 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
62865 */
62866 
62867 #ifndef SQLITE_OMIT_TRACE
62868 
62869 /*
62870 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
62871 ** bytes in this text up to but excluding the first character in
62872 ** a host parameter.  If the text contains no host parameters, return
62873 ** the total number of bytes in the text.
62874 */
62875 static int findNextHostParameter(const char *zSql, int *pnToken){
62876   int tokenType;
62877   int nTotal = 0;
62878   int n;
62879 
62880   *pnToken = 0;
62881   while( zSql[0] ){
62882     n = sqlite3GetToken((u8*)zSql, &tokenType);
62883     assert( n>0 && tokenType!=TK_ILLEGAL );
62884     if( tokenType==TK_VARIABLE ){
62885       *pnToken = n;
62886       break;
62887     }
62888     nTotal += n;
62889     zSql += n;
62890   }
62891   return nTotal;
62892 }
62893 
62894 /*
62895 ** This function returns a pointer to a nul-terminated string in memory
62896 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
62897 ** string contains a copy of zRawSql but with host parameters expanded to
62898 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
62899 ** then the returned string holds a copy of zRawSql with "-- " prepended
62900 ** to each line of text.
62901 **
62902 ** The calling function is responsible for making sure the memory returned
62903 ** is eventually freed.
62904 **
62905 ** ALGORITHM:  Scan the input string looking for host parameters in any of
62906 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
62907 ** string literals, quoted identifier names, and comments.  For text forms,
62908 ** the host parameter index is found by scanning the perpared
62909 ** statement for the corresponding OP_Variable opcode.  Once the host
62910 ** parameter index is known, locate the value in p->aVar[].  Then render
62911 ** the value as a literal in place of the host parameter name.
62912 */
62913 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
62914   Vdbe *p,                 /* The prepared statement being evaluated */
62915   const char *zRawSql      /* Raw text of the SQL statement */
62916 ){
62917   sqlite3 *db;             /* The database connection */
62918   int idx = 0;             /* Index of a host parameter */
62919   int nextIndex = 1;       /* Index of next ? host parameter */
62920   int n;                   /* Length of a token prefix */
62921   int nToken;              /* Length of the parameter token */
62922   int i;                   /* Loop counter */
62923   Mem *pVar;               /* Value of a host parameter */
62924   StrAccum out;            /* Accumulate the output here */
62925   char zBase[100];         /* Initial working space */
62926 
62927   db = p->db;
62928   sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
62929                       db->aLimit[SQLITE_LIMIT_LENGTH]);
62930   out.db = db;
62931   if( db->vdbeExecCnt>1 ){
62932     while( *zRawSql ){
62933       const char *zStart = zRawSql;
62934       while( *(zRawSql++)!='\n' && *zRawSql );
62935       sqlite3StrAccumAppend(&out, "-- ", 3);
62936       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
62937     }
62938   }else{
62939     while( zRawSql[0] ){
62940       n = findNextHostParameter(zRawSql, &nToken);
62941       assert( n>0 );
62942       sqlite3StrAccumAppend(&out, zRawSql, n);
62943       zRawSql += n;
62944       assert( zRawSql[0] || nToken==0 );
62945       if( nToken==0 ) break;
62946       if( zRawSql[0]=='?' ){
62947         if( nToken>1 ){
62948           assert( sqlite3Isdigit(zRawSql[1]) );
62949           sqlite3GetInt32(&zRawSql[1], &idx);
62950         }else{
62951           idx = nextIndex;
62952         }
62953       }else{
62954         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
62955         testcase( zRawSql[0]==':' );
62956         testcase( zRawSql[0]=='$' );
62957         testcase( zRawSql[0]=='@' );
62958         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
62959         assert( idx>0 );
62960       }
62961       zRawSql += nToken;
62962       nextIndex = idx + 1;
62963       assert( idx>0 && idx<=p->nVar );
62964       pVar = &p->aVar[idx-1];
62965       if( pVar->flags & MEM_Null ){
62966         sqlite3StrAccumAppend(&out, "NULL", 4);
62967       }else if( pVar->flags & MEM_Int ){
62968         sqlite3XPrintf(&out, "%lld", pVar->u.i);
62969       }else if( pVar->flags & MEM_Real ){
62970         sqlite3XPrintf(&out, "%!.15g", pVar->r);
62971       }else if( pVar->flags & MEM_Str ){
62972 #ifndef SQLITE_OMIT_UTF16
62973         u8 enc = ENC(db);
62974         if( enc!=SQLITE_UTF8 ){
62975           Mem utf8;
62976           memset(&utf8, 0, sizeof(utf8));
62977           utf8.db = db;
62978           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
62979           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
62980           sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
62981           sqlite3VdbeMemRelease(&utf8);
62982         }else
62983 #endif
62984         {
62985           sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
62986         }
62987       }else if( pVar->flags & MEM_Zero ){
62988         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
62989       }else{
62990         assert( pVar->flags & MEM_Blob );
62991         sqlite3StrAccumAppend(&out, "x'", 2);
62992         for(i=0; i<pVar->n; i++){
62993           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
62994         }
62995         sqlite3StrAccumAppend(&out, "'", 1);
62996       }
62997     }
62998   }
62999   return sqlite3StrAccumFinish(&out);
63000 }
63001 
63002 #endif /* #ifndef SQLITE_OMIT_TRACE */
63003 
63004 /************** End of vdbetrace.c *******************************************/
63005 /************** Begin file vdbe.c ********************************************/
63006 /*
63007 ** 2001 September 15
63008 **
63009 ** The author disclaims copyright to this source code.  In place of
63010 ** a legal notice, here is a blessing:
63011 **
63012 **    May you do good and not evil.
63013 **    May you find forgiveness for yourself and forgive others.
63014 **    May you share freely, never taking more than you give.
63015 **
63016 *************************************************************************
63017 ** The code in this file implements execution method of the
63018 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
63019 ** handles housekeeping details such as creating and deleting
63020 ** VDBE instances.  This file is solely interested in executing
63021 ** the VDBE program.
63022 **
63023 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
63024 ** to a VDBE.
63025 **
63026 ** The SQL parser generates a program which is then executed by
63027 ** the VDBE to do the work of the SQL statement.  VDBE programs are
63028 ** similar in form to assembly language.  The program consists of
63029 ** a linear sequence of operations.  Each operation has an opcode
63030 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
63031 ** is a null-terminated string.  Operand P5 is an unsigned character.
63032 ** Few opcodes use all 5 operands.
63033 **
63034 ** Computation results are stored on a set of registers numbered beginning
63035 ** with 1 and going up to Vdbe.nMem.  Each register can store
63036 ** either an integer, a null-terminated string, a floating point
63037 ** number, or the SQL "NULL" value.  An implicit conversion from one
63038 ** type to the other occurs as necessary.
63039 **
63040 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
63041 ** function which does the work of interpreting a VDBE program.
63042 ** But other routines are also provided to help in building up
63043 ** a program instruction by instruction.
63044 **
63045 ** Various scripts scan this source file in order to generate HTML
63046 ** documentation, headers files, or other derived files.  The formatting
63047 ** of the code in this file is, therefore, important.  See other comments
63048 ** in this file for details.  If in doubt, do not deviate from existing
63049 ** commenting and indentation practices when changing or adding code.
63050 */
63051 
63052 /*
63053 ** Invoke this macro on memory cells just prior to changing the
63054 ** value of the cell.  This macro verifies that shallow copies are
63055 ** not misused.
63056 */
63057 #ifdef SQLITE_DEBUG
63058 # define memAboutToChange(P,M) sqlite3VdbeMemPrepareToChange(P,M)
63059 #else
63060 # define memAboutToChange(P,M)
63061 #endif
63062 
63063 /*
63064 ** The following global variable is incremented every time a cursor
63065 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
63066 ** procedures use this information to make sure that indices are
63067 ** working correctly.  This variable has no function other than to
63068 ** help verify the correct operation of the library.
63069 */
63070 #ifdef SQLITE_TEST
63071 SQLITE_API int sqlite3_search_count = 0;
63072 #endif
63073 
63074 /*
63075 ** When this global variable is positive, it gets decremented once before
63076 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
63077 ** field of the sqlite3 structure is set in order to simulate and interrupt.
63078 **
63079 ** This facility is used for testing purposes only.  It does not function
63080 ** in an ordinary build.
63081 */
63082 #ifdef SQLITE_TEST
63083 SQLITE_API int sqlite3_interrupt_count = 0;
63084 #endif
63085 
63086 /*
63087 ** The next global variable is incremented each type the OP_Sort opcode
63088 ** is executed.  The test procedures use this information to make sure that
63089 ** sorting is occurring or not occurring at appropriate times.   This variable
63090 ** has no function other than to help verify the correct operation of the
63091 ** library.
63092 */
63093 #ifdef SQLITE_TEST
63094 SQLITE_API int sqlite3_sort_count = 0;
63095 #endif
63096 
63097 /*
63098 ** The next global variable records the size of the largest MEM_Blob
63099 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
63100 ** use this information to make sure that the zero-blob functionality
63101 ** is working correctly.   This variable has no function other than to
63102 ** help verify the correct operation of the library.
63103 */
63104 #ifdef SQLITE_TEST
63105 SQLITE_API int sqlite3_max_blobsize = 0;
63106 static void updateMaxBlobsize(Mem *p){
63107   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
63108     sqlite3_max_blobsize = p->n;
63109   }
63110 }
63111 #endif
63112 
63113 /*
63114 ** The next global variable is incremented each type the OP_Found opcode
63115 ** is executed. This is used to test whether or not the foreign key
63116 ** operation implemented using OP_FkIsZero is working. This variable
63117 ** has no function other than to help verify the correct operation of the
63118 ** library.
63119 */
63120 #ifdef SQLITE_TEST
63121 SQLITE_API int sqlite3_found_count = 0;
63122 #endif
63123 
63124 /*
63125 ** Test a register to see if it exceeds the current maximum blob size.
63126 ** If it does, record the new maximum blob size.
63127 */
63128 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
63129 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
63130 #else
63131 # define UPDATE_MAX_BLOBSIZE(P)
63132 #endif
63133 
63134 /*
63135 ** Convert the given register into a string if it isn't one
63136 ** already. Return non-zero if a malloc() fails.
63137 */
63138 #define Stringify(P, enc) \
63139    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
63140      { goto no_mem; }
63141 
63142 /*
63143 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
63144 ** a pointer to a dynamically allocated string where some other entity
63145 ** is responsible for deallocating that string.  Because the register
63146 ** does not control the string, it might be deleted without the register
63147 ** knowing it.
63148 **
63149 ** This routine converts an ephemeral string into a dynamically allocated
63150 ** string that the register itself controls.  In other words, it
63151 ** converts an MEM_Ephem string into an MEM_Dyn string.
63152 */
63153 #define Deephemeralize(P) \
63154    if( ((P)->flags&MEM_Ephem)!=0 \
63155        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
63156 
63157 /*
63158 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
63159 ** P if required.
63160 */
63161 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
63162 
63163 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
63164 #ifdef SQLITE_OMIT_MERGE_SORT
63165 # define isSorter(x) 0
63166 #else
63167 # define isSorter(x) ((x)->pSorter!=0)
63168 #endif
63169 
63170 /*
63171 ** Argument pMem points at a register that will be passed to a
63172 ** user-defined function or returned to the user as the result of a query.
63173 ** This routine sets the pMem->type variable used by the sqlite3_value_*()
63174 ** routines.
63175 */
63176 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
63177   int flags = pMem->flags;
63178   if( flags & MEM_Null ){
63179     pMem->type = SQLITE_NULL;
63180   }
63181   else if( flags & MEM_Int ){
63182     pMem->type = SQLITE_INTEGER;
63183   }
63184   else if( flags & MEM_Real ){
63185     pMem->type = SQLITE_FLOAT;
63186   }
63187   else if( flags & MEM_Str ){
63188     pMem->type = SQLITE_TEXT;
63189   }else{
63190     pMem->type = SQLITE_BLOB;
63191   }
63192 }
63193 
63194 /*
63195 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
63196 ** if we run out of memory.
63197 */
63198 static VdbeCursor *allocateCursor(
63199   Vdbe *p,              /* The virtual machine */
63200   int iCur,             /* Index of the new VdbeCursor */
63201   int nField,           /* Number of fields in the table or index */
63202   int iDb,              /* When database the cursor belongs to, or -1 */
63203   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
63204 ){
63205   /* Find the memory cell that will be used to store the blob of memory
63206   ** required for this VdbeCursor structure. It is convenient to use a
63207   ** vdbe memory cell to manage the memory allocation required for a
63208   ** VdbeCursor structure for the following reasons:
63209   **
63210   **   * Sometimes cursor numbers are used for a couple of different
63211   **     purposes in a vdbe program. The different uses might require
63212   **     different sized allocations. Memory cells provide growable
63213   **     allocations.
63214   **
63215   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
63216   **     be freed lazily via the sqlite3_release_memory() API. This
63217   **     minimizes the number of malloc calls made by the system.
63218   **
63219   ** Memory cells for cursors are allocated at the top of the address
63220   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
63221   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
63222   */
63223   Mem *pMem = &p->aMem[p->nMem-iCur];
63224 
63225   int nByte;
63226   VdbeCursor *pCx = 0;
63227   nByte =
63228       ROUND8(sizeof(VdbeCursor)) +
63229       (isBtreeCursor?sqlite3BtreeCursorSize():0) +
63230       2*nField*sizeof(u32);
63231 
63232   assert( iCur<p->nCursor );
63233   if( p->apCsr[iCur] ){
63234     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
63235     p->apCsr[iCur] = 0;
63236   }
63237   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
63238     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
63239     memset(pCx, 0, sizeof(VdbeCursor));
63240     pCx->iDb = iDb;
63241     pCx->nField = nField;
63242     if( nField ){
63243       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
63244     }
63245     if( isBtreeCursor ){
63246       pCx->pCursor = (BtCursor*)
63247           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
63248       sqlite3BtreeCursorZero(pCx->pCursor);
63249     }
63250   }
63251   return pCx;
63252 }
63253 
63254 /*
63255 ** Try to convert a value into a numeric representation if we can
63256 ** do so without loss of information.  In other words, if the string
63257 ** looks like a number, convert it into a number.  If it does not
63258 ** look like a number, leave it alone.
63259 */
63260 static void applyNumericAffinity(Mem *pRec){
63261   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
63262     double rValue;
63263     i64 iValue;
63264     u8 enc = pRec->enc;
63265     if( (pRec->flags&MEM_Str)==0 ) return;
63266     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
63267     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
63268       pRec->u.i = iValue;
63269       pRec->flags |= MEM_Int;
63270     }else{
63271       pRec->r = rValue;
63272       pRec->flags |= MEM_Real;
63273     }
63274   }
63275 }
63276 
63277 /*
63278 ** Processing is determine by the affinity parameter:
63279 **
63280 ** SQLITE_AFF_INTEGER:
63281 ** SQLITE_AFF_REAL:
63282 ** SQLITE_AFF_NUMERIC:
63283 **    Try to convert pRec to an integer representation or a
63284 **    floating-point representation if an integer representation
63285 **    is not possible.  Note that the integer representation is
63286 **    always preferred, even if the affinity is REAL, because
63287 **    an integer representation is more space efficient on disk.
63288 **
63289 ** SQLITE_AFF_TEXT:
63290 **    Convert pRec to a text representation.
63291 **
63292 ** SQLITE_AFF_NONE:
63293 **    No-op.  pRec is unchanged.
63294 */
63295 static void applyAffinity(
63296   Mem *pRec,          /* The value to apply affinity to */
63297   char affinity,      /* The affinity to be applied */
63298   u8 enc              /* Use this text encoding */
63299 ){
63300   if( affinity==SQLITE_AFF_TEXT ){
63301     /* Only attempt the conversion to TEXT if there is an integer or real
63302     ** representation (blob and NULL do not get converted) but no string
63303     ** representation.
63304     */
63305     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
63306       sqlite3VdbeMemStringify(pRec, enc);
63307     }
63308     pRec->flags &= ~(MEM_Real|MEM_Int);
63309   }else if( affinity!=SQLITE_AFF_NONE ){
63310     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
63311              || affinity==SQLITE_AFF_NUMERIC );
63312     applyNumericAffinity(pRec);
63313     if( pRec->flags & MEM_Real ){
63314       sqlite3VdbeIntegerAffinity(pRec);
63315     }
63316   }
63317 }
63318 
63319 /*
63320 ** Try to convert the type of a function argument or a result column
63321 ** into a numeric representation.  Use either INTEGER or REAL whichever
63322 ** is appropriate.  But only do the conversion if it is possible without
63323 ** loss of information and return the revised type of the argument.
63324 */
63325 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
63326   Mem *pMem = (Mem*)pVal;
63327   if( pMem->type==SQLITE_TEXT ){
63328     applyNumericAffinity(pMem);
63329     sqlite3VdbeMemStoreType(pMem);
63330   }
63331   return pMem->type;
63332 }
63333 
63334 /*
63335 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
63336 ** not the internal Mem* type.
63337 */
63338 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
63339   sqlite3_value *pVal,
63340   u8 affinity,
63341   u8 enc
63342 ){
63343   applyAffinity((Mem *)pVal, affinity, enc);
63344 }
63345 
63346 #ifdef SQLITE_DEBUG
63347 /*
63348 ** Write a nice string representation of the contents of cell pMem
63349 ** into buffer zBuf, length nBuf.
63350 */
63351 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
63352   char *zCsr = zBuf;
63353   int f = pMem->flags;
63354 
63355   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
63356 
63357   if( f&MEM_Blob ){
63358     int i;
63359     char c;
63360     if( f & MEM_Dyn ){
63361       c = 'z';
63362       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63363     }else if( f & MEM_Static ){
63364       c = 't';
63365       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63366     }else if( f & MEM_Ephem ){
63367       c = 'e';
63368       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63369     }else{
63370       c = 's';
63371     }
63372 
63373     sqlite3_snprintf(100, zCsr, "%c", c);
63374     zCsr += sqlite3Strlen30(zCsr);
63375     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
63376     zCsr += sqlite3Strlen30(zCsr);
63377     for(i=0; i<16 && i<pMem->n; i++){
63378       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
63379       zCsr += sqlite3Strlen30(zCsr);
63380     }
63381     for(i=0; i<16 && i<pMem->n; i++){
63382       char z = pMem->z[i];
63383       if( z<32 || z>126 ) *zCsr++ = '.';
63384       else *zCsr++ = z;
63385     }
63386 
63387     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
63388     zCsr += sqlite3Strlen30(zCsr);
63389     if( f & MEM_Zero ){
63390       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
63391       zCsr += sqlite3Strlen30(zCsr);
63392     }
63393     *zCsr = '\0';
63394   }else if( f & MEM_Str ){
63395     int j, k;
63396     zBuf[0] = ' ';
63397     if( f & MEM_Dyn ){
63398       zBuf[1] = 'z';
63399       assert( (f & (MEM_Static|MEM_Ephem))==0 );
63400     }else if( f & MEM_Static ){
63401       zBuf[1] = 't';
63402       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
63403     }else if( f & MEM_Ephem ){
63404       zBuf[1] = 'e';
63405       assert( (f & (MEM_Static|MEM_Dyn))==0 );
63406     }else{
63407       zBuf[1] = 's';
63408     }
63409     k = 2;
63410     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
63411     k += sqlite3Strlen30(&zBuf[k]);
63412     zBuf[k++] = '[';
63413     for(j=0; j<15 && j<pMem->n; j++){
63414       u8 c = pMem->z[j];
63415       if( c>=0x20 && c<0x7f ){
63416         zBuf[k++] = c;
63417       }else{
63418         zBuf[k++] = '.';
63419       }
63420     }
63421     zBuf[k++] = ']';
63422     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
63423     k += sqlite3Strlen30(&zBuf[k]);
63424     zBuf[k++] = 0;
63425   }
63426 }
63427 #endif
63428 
63429 #ifdef SQLITE_DEBUG
63430 /*
63431 ** Print the value of a register for tracing purposes:
63432 */
63433 static void memTracePrint(FILE *out, Mem *p){
63434   if( p->flags & MEM_Null ){
63435     fprintf(out, " NULL");
63436   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
63437     fprintf(out, " si:%lld", p->u.i);
63438   }else if( p->flags & MEM_Int ){
63439     fprintf(out, " i:%lld", p->u.i);
63440 #ifndef SQLITE_OMIT_FLOATING_POINT
63441   }else if( p->flags & MEM_Real ){
63442     fprintf(out, " r:%g", p->r);
63443 #endif
63444   }else if( p->flags & MEM_RowSet ){
63445     fprintf(out, " (rowset)");
63446   }else{
63447     char zBuf[200];
63448     sqlite3VdbeMemPrettyPrint(p, zBuf);
63449     fprintf(out, " ");
63450     fprintf(out, "%s", zBuf);
63451   }
63452 }
63453 static void registerTrace(FILE *out, int iReg, Mem *p){
63454   fprintf(out, "REG[%d] = ", iReg);
63455   memTracePrint(out, p);
63456   fprintf(out, "\n");
63457 }
63458 #endif
63459 
63460 #ifdef SQLITE_DEBUG
63461 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
63462 #else
63463 #  define REGISTER_TRACE(R,M)
63464 #endif
63465 
63466 
63467 #ifdef VDBE_PROFILE
63468 
63469 /*
63470 ** hwtime.h contains inline assembler code for implementing
63471 ** high-performance timing routines.
63472 */
63473 /************** Include hwtime.h in the middle of vdbe.c *********************/
63474 /************** Begin file hwtime.h ******************************************/
63475 /*
63476 ** 2008 May 27
63477 **
63478 ** The author disclaims copyright to this source code.  In place of
63479 ** a legal notice, here is a blessing:
63480 **
63481 **    May you do good and not evil.
63482 **    May you find forgiveness for yourself and forgive others.
63483 **    May you share freely, never taking more than you give.
63484 **
63485 ******************************************************************************
63486 **
63487 ** This file contains inline asm code for retrieving "high-performance"
63488 ** counters for x86 class CPUs.
63489 */
63490 #ifndef _HWTIME_H_
63491 #define _HWTIME_H_
63492 
63493 /*
63494 ** The following routine only works on pentium-class (or newer) processors.
63495 ** It uses the RDTSC opcode to read the cycle count value out of the
63496 ** processor and returns that value.  This can be used for high-res
63497 ** profiling.
63498 */
63499 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
63500       (defined(i386) || defined(__i386__) || defined(_M_IX86))
63501 
63502   #if defined(__GNUC__)
63503 
63504   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63505      unsigned int lo, hi;
63506      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
63507      return (sqlite_uint64)hi << 32 | lo;
63508   }
63509 
63510   #elif defined(_MSC_VER)
63511 
63512   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
63513      __asm {
63514         rdtsc
63515         ret       ; return value at EDX:EAX
63516      }
63517   }
63518 
63519   #endif
63520 
63521 #elif (defined(__GNUC__) && defined(__x86_64__))
63522 
63523   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63524       unsigned long val;
63525       __asm__ __volatile__ ("rdtsc" : "=A" (val));
63526       return val;
63527   }
63528 
63529 #elif (defined(__GNUC__) && defined(__ppc__))
63530 
63531   __inline__ sqlite_uint64 sqlite3Hwtime(void){
63532       unsigned long long retval;
63533       unsigned long junk;
63534       __asm__ __volatile__ ("\n\
63535           1:      mftbu   %1\n\
63536                   mftb    %L0\n\
63537                   mftbu   %0\n\
63538                   cmpw    %0,%1\n\
63539                   bne     1b"
63540                   : "=r" (retval), "=r" (junk));
63541       return retval;
63542   }
63543 
63544 #else
63545 
63546   #error Need implementation of sqlite3Hwtime() for your platform.
63547 
63548   /*
63549   ** To compile without implementing sqlite3Hwtime() for your platform,
63550   ** you can remove the above #error and use the following
63551   ** stub function.  You will lose timing support for many
63552   ** of the debugging and testing utilities, but it should at
63553   ** least compile and run.
63554   */
63555 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
63556 
63557 #endif
63558 
63559 #endif /* !defined(_HWTIME_H_) */
63560 
63561 /************** End of hwtime.h **********************************************/
63562 /************** Continuing where we left off in vdbe.c ***********************/
63563 
63564 #endif
63565 
63566 /*
63567 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
63568 ** sqlite3_interrupt() routine has been called.  If it has been, then
63569 ** processing of the VDBE program is interrupted.
63570 **
63571 ** This macro added to every instruction that does a jump in order to
63572 ** implement a loop.  This test used to be on every single instruction,
63573 ** but that meant we more testing that we needed.  By only testing the
63574 ** flag on jump instructions, we get a (small) speed improvement.
63575 */
63576 #define CHECK_FOR_INTERRUPT \
63577    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
63578 
63579 
63580 #ifndef NDEBUG
63581 /*
63582 ** This function is only called from within an assert() expression. It
63583 ** checks that the sqlite3.nTransaction variable is correctly set to
63584 ** the number of non-transaction savepoints currently in the
63585 ** linked list starting at sqlite3.pSavepoint.
63586 **
63587 ** Usage:
63588 **
63589 **     assert( checkSavepointCount(db) );
63590 */
63591 static int checkSavepointCount(sqlite3 *db){
63592   int n = 0;
63593   Savepoint *p;
63594   for(p=db->pSavepoint; p; p=p->pNext) n++;
63595   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
63596   return 1;
63597 }
63598 #endif
63599 
63600 /*
63601 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
63602 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
63603 ** in memory obtained from sqlite3DbMalloc).
63604 */
63605 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
63606   sqlite3 *db = p->db;
63607   sqlite3DbFree(db, p->zErrMsg);
63608   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
63609   sqlite3_free(pVtab->zErrMsg);
63610   pVtab->zErrMsg = 0;
63611 }
63612 
63613 
63614 /*
63615 ** Execute as much of a VDBE program as we can then return.
63616 **
63617 ** sqlite3VdbeMakeReady() must be called before this routine in order to
63618 ** close the program with a final OP_Halt and to set up the callbacks
63619 ** and the error message pointer.
63620 **
63621 ** Whenever a row or result data is available, this routine will either
63622 ** invoke the result callback (if there is one) or return with
63623 ** SQLITE_ROW.
63624 **
63625 ** If an attempt is made to open a locked database, then this routine
63626 ** will either invoke the busy callback (if there is one) or it will
63627 ** return SQLITE_BUSY.
63628 **
63629 ** If an error occurs, an error message is written to memory obtained
63630 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
63631 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
63632 **
63633 ** If the callback ever returns non-zero, then the program exits
63634 ** immediately.  There will be no error message but the p->rc field is
63635 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
63636 **
63637 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
63638 ** routine to return SQLITE_ERROR.
63639 **
63640 ** Other fatal errors return SQLITE_ERROR.
63641 **
63642 ** After this routine has finished, sqlite3VdbeFinalize() should be
63643 ** used to clean up the mess that was left behind.
63644 */
63645 SQLITE_PRIVATE int sqlite3VdbeExec(
63646   Vdbe *p                    /* The VDBE */
63647 ){
63648   int pc=0;                  /* The program counter */
63649   Op *aOp = p->aOp;          /* Copy of p->aOp */
63650   Op *pOp;                   /* Current operation */
63651   int rc = SQLITE_OK;        /* Value to return */
63652   sqlite3 *db = p->db;       /* The database */
63653   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
63654   u8 encoding = ENC(db);     /* The database encoding */
63655 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
63656   int checkProgress;         /* True if progress callbacks are enabled */
63657   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
63658 #endif
63659   Mem *aMem = p->aMem;       /* Copy of p->aMem */
63660   Mem *pIn1 = 0;             /* 1st input operand */
63661   Mem *pIn2 = 0;             /* 2nd input operand */
63662   Mem *pIn3 = 0;             /* 3rd input operand */
63663   Mem *pOut = 0;             /* Output operand */
63664   int iCompare = 0;          /* Result of last OP_Compare operation */
63665   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
63666   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
63667 #ifdef VDBE_PROFILE
63668   u64 start;                 /* CPU clock count at start of opcode */
63669   int origPc;                /* Program counter at start of opcode */
63670 #endif
63671   /********************************************************************
63672   ** Automatically generated code
63673   **
63674   ** The following union is automatically generated by the
63675   ** vdbe-compress.tcl script.  The purpose of this union is to
63676   ** reduce the amount of stack space required by this function.
63677   ** See comments in the vdbe-compress.tcl script for details.
63678   */
63679   union vdbeExecUnion {
63680     struct OP_Yield_stack_vars {
63681       int pcDest;
63682     } aa;
63683     struct OP_Variable_stack_vars {
63684       Mem *pVar;       /* Value being transferred */
63685     } ab;
63686     struct OP_Move_stack_vars {
63687       char *zMalloc;   /* Holding variable for allocated memory */
63688       int n;           /* Number of registers left to copy */
63689       int p1;          /* Register to copy from */
63690       int p2;          /* Register to copy to */
63691     } ac;
63692     struct OP_ResultRow_stack_vars {
63693       Mem *pMem;
63694       int i;
63695     } ad;
63696     struct OP_Concat_stack_vars {
63697       i64 nByte;
63698     } ae;
63699     struct OP_Remainder_stack_vars {
63700       int flags;      /* Combined MEM_* flags from both inputs */
63701       i64 iA;         /* Integer value of left operand */
63702       i64 iB;         /* Integer value of right operand */
63703       double rA;      /* Real value of left operand */
63704       double rB;      /* Real value of right operand */
63705     } af;
63706     struct OP_Function_stack_vars {
63707       int i;
63708       Mem *pArg;
63709       sqlite3_context ctx;
63710       sqlite3_value **apVal;
63711       int n;
63712     } ag;
63713     struct OP_ShiftRight_stack_vars {
63714       i64 iA;
63715       u64 uA;
63716       i64 iB;
63717       u8 op;
63718     } ah;
63719     struct OP_Ge_stack_vars {
63720       int res;            /* Result of the comparison of pIn1 against pIn3 */
63721       char affinity;      /* Affinity to use for comparison */
63722       u16 flags1;         /* Copy of initial value of pIn1->flags */
63723       u16 flags3;         /* Copy of initial value of pIn3->flags */
63724     } ai;
63725     struct OP_Compare_stack_vars {
63726       int n;
63727       int i;
63728       int p1;
63729       int p2;
63730       const KeyInfo *pKeyInfo;
63731       int idx;
63732       CollSeq *pColl;    /* Collating sequence to use on this term */
63733       int bRev;          /* True for DESCENDING sort order */
63734     } aj;
63735     struct OP_Or_stack_vars {
63736       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63737       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
63738     } ak;
63739     struct OP_IfNot_stack_vars {
63740       int c;
63741     } al;
63742     struct OP_Column_stack_vars {
63743       u32 payloadSize;   /* Number of bytes in the record */
63744       i64 payloadSize64; /* Number of bytes in the record */
63745       int p1;            /* P1 value of the opcode */
63746       int p2;            /* column number to retrieve */
63747       VdbeCursor *pC;    /* The VDBE cursor */
63748       char *zRec;        /* Pointer to complete record-data */
63749       BtCursor *pCrsr;   /* The BTree cursor */
63750       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
63751       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
63752       int nField;        /* number of fields in the record */
63753       int len;           /* The length of the serialized data for the column */
63754       int i;             /* Loop counter */
63755       char *zData;       /* Part of the record being decoded */
63756       Mem *pDest;        /* Where to write the extracted value */
63757       Mem sMem;          /* For storing the record being decoded */
63758       u8 *zIdx;          /* Index into header */
63759       u8 *zEndHdr;       /* Pointer to first byte after the header */
63760       u32 offset;        /* Offset into the data */
63761       u32 szField;       /* Number of bytes in the content of a field */
63762       int szHdr;         /* Size of the header size field at start of record */
63763       int avail;         /* Number of bytes of available data */
63764       u32 t;             /* A type code from the record header */
63765       Mem *pReg;         /* PseudoTable input register */
63766     } am;
63767     struct OP_Affinity_stack_vars {
63768       const char *zAffinity;   /* The affinity to be applied */
63769       char cAff;               /* A single character of affinity */
63770     } an;
63771     struct OP_MakeRecord_stack_vars {
63772       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
63773       Mem *pRec;             /* The new record */
63774       u64 nData;             /* Number of bytes of data space */
63775       int nHdr;              /* Number of bytes of header space */
63776       i64 nByte;             /* Data space required for this record */
63777       int nZero;             /* Number of zero bytes at the end of the record */
63778       int nVarint;           /* Number of bytes in a varint */
63779       u32 serial_type;       /* Type field */
63780       Mem *pData0;           /* First field to be combined into the record */
63781       Mem *pLast;            /* Last field of the record */
63782       int nField;            /* Number of fields in the record */
63783       char *zAffinity;       /* The affinity string for the record */
63784       int file_format;       /* File format to use for encoding */
63785       int i;                 /* Space used in zNewRecord[] */
63786       int len;               /* Length of a field */
63787     } ao;
63788     struct OP_Count_stack_vars {
63789       i64 nEntry;
63790       BtCursor *pCrsr;
63791     } ap;
63792     struct OP_Savepoint_stack_vars {
63793       int p1;                         /* Value of P1 operand */
63794       char *zName;                    /* Name of savepoint */
63795       int nName;
63796       Savepoint *pNew;
63797       Savepoint *pSavepoint;
63798       Savepoint *pTmp;
63799       int iSavepoint;
63800       int ii;
63801     } aq;
63802     struct OP_AutoCommit_stack_vars {
63803       int desiredAutoCommit;
63804       int iRollback;
63805       int turnOnAC;
63806     } ar;
63807     struct OP_Transaction_stack_vars {
63808       Btree *pBt;
63809     } as;
63810     struct OP_ReadCookie_stack_vars {
63811       int iMeta;
63812       int iDb;
63813       int iCookie;
63814     } at;
63815     struct OP_SetCookie_stack_vars {
63816       Db *pDb;
63817     } au;
63818     struct OP_VerifyCookie_stack_vars {
63819       int iMeta;
63820       int iGen;
63821       Btree *pBt;
63822     } av;
63823     struct OP_OpenWrite_stack_vars {
63824       int nField;
63825       KeyInfo *pKeyInfo;
63826       int p2;
63827       int iDb;
63828       int wrFlag;
63829       Btree *pX;
63830       VdbeCursor *pCur;
63831       Db *pDb;
63832     } aw;
63833     struct OP_OpenEphemeral_stack_vars {
63834       VdbeCursor *pCx;
63835     } ax;
63836     struct OP_SorterOpen_stack_vars {
63837       VdbeCursor *pCx;
63838     } ay;
63839     struct OP_OpenPseudo_stack_vars {
63840       VdbeCursor *pCx;
63841     } az;
63842     struct OP_SeekGt_stack_vars {
63843       int res;
63844       int oc;
63845       VdbeCursor *pC;
63846       UnpackedRecord r;
63847       int nField;
63848       i64 iKey;      /* The rowid we are to seek to */
63849     } ba;
63850     struct OP_Seek_stack_vars {
63851       VdbeCursor *pC;
63852     } bb;
63853     struct OP_Found_stack_vars {
63854       int alreadyExists;
63855       VdbeCursor *pC;
63856       int res;
63857       char *pFree;
63858       UnpackedRecord *pIdxKey;
63859       UnpackedRecord r;
63860       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
63861     } bc;
63862     struct OP_IsUnique_stack_vars {
63863       u16 ii;
63864       VdbeCursor *pCx;
63865       BtCursor *pCrsr;
63866       u16 nField;
63867       Mem *aMx;
63868       UnpackedRecord r;                  /* B-Tree index search key */
63869       i64 R;                             /* Rowid stored in register P3 */
63870     } bd;
63871     struct OP_NotExists_stack_vars {
63872       VdbeCursor *pC;
63873       BtCursor *pCrsr;
63874       int res;
63875       u64 iKey;
63876     } be;
63877     struct OP_NewRowid_stack_vars {
63878       i64 v;                 /* The new rowid */
63879       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
63880       int res;               /* Result of an sqlite3BtreeLast() */
63881       int cnt;               /* Counter to limit the number of searches */
63882       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
63883       VdbeFrame *pFrame;     /* Root frame of VDBE */
63884     } bf;
63885     struct OP_InsertInt_stack_vars {
63886       Mem *pData;       /* MEM cell holding data for the record to be inserted */
63887       Mem *pKey;        /* MEM cell holding key  for the record */
63888       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
63889       VdbeCursor *pC;   /* Cursor to table into which insert is written */
63890       int nZero;        /* Number of zero-bytes to append */
63891       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
63892       const char *zDb;  /* database name - used by the update hook */
63893       const char *zTbl; /* Table name - used by the opdate hook */
63894       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
63895     } bg;
63896     struct OP_Delete_stack_vars {
63897       i64 iKey;
63898       VdbeCursor *pC;
63899     } bh;
63900     struct OP_SorterCompare_stack_vars {
63901       VdbeCursor *pC;
63902       int res;
63903     } bi;
63904     struct OP_SorterData_stack_vars {
63905       VdbeCursor *pC;
63906     } bj;
63907     struct OP_RowData_stack_vars {
63908       VdbeCursor *pC;
63909       BtCursor *pCrsr;
63910       u32 n;
63911       i64 n64;
63912     } bk;
63913     struct OP_Rowid_stack_vars {
63914       VdbeCursor *pC;
63915       i64 v;
63916       sqlite3_vtab *pVtab;
63917       const sqlite3_module *pModule;
63918     } bl;
63919     struct OP_NullRow_stack_vars {
63920       VdbeCursor *pC;
63921     } bm;
63922     struct OP_Last_stack_vars {
63923       VdbeCursor *pC;
63924       BtCursor *pCrsr;
63925       int res;
63926     } bn;
63927     struct OP_Rewind_stack_vars {
63928       VdbeCursor *pC;
63929       BtCursor *pCrsr;
63930       int res;
63931     } bo;
63932     struct OP_Next_stack_vars {
63933       VdbeCursor *pC;
63934       int res;
63935     } bp;
63936     struct OP_IdxInsert_stack_vars {
63937       VdbeCursor *pC;
63938       BtCursor *pCrsr;
63939       int nKey;
63940       const char *zKey;
63941     } bq;
63942     struct OP_IdxDelete_stack_vars {
63943       VdbeCursor *pC;
63944       BtCursor *pCrsr;
63945       int res;
63946       UnpackedRecord r;
63947     } br;
63948     struct OP_IdxRowid_stack_vars {
63949       BtCursor *pCrsr;
63950       VdbeCursor *pC;
63951       i64 rowid;
63952     } bs;
63953     struct OP_IdxGE_stack_vars {
63954       VdbeCursor *pC;
63955       int res;
63956       UnpackedRecord r;
63957     } bt;
63958     struct OP_Destroy_stack_vars {
63959       int iMoved;
63960       int iCnt;
63961       Vdbe *pVdbe;
63962       int iDb;
63963     } bu;
63964     struct OP_Clear_stack_vars {
63965       int nChange;
63966     } bv;
63967     struct OP_CreateTable_stack_vars {
63968       int pgno;
63969       int flags;
63970       Db *pDb;
63971     } bw;
63972     struct OP_ParseSchema_stack_vars {
63973       int iDb;
63974       const char *zMaster;
63975       char *zSql;
63976       InitData initData;
63977     } bx;
63978     struct OP_IntegrityCk_stack_vars {
63979       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
63980       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
63981       int j;          /* Loop counter */
63982       int nErr;       /* Number of errors reported */
63983       char *z;        /* Text of the error report */
63984       Mem *pnErr;     /* Register keeping track of errors remaining */
63985     } by;
63986     struct OP_RowSetRead_stack_vars {
63987       i64 val;
63988     } bz;
63989     struct OP_RowSetTest_stack_vars {
63990       int iSet;
63991       int exists;
63992     } ca;
63993     struct OP_Program_stack_vars {
63994       int nMem;               /* Number of memory registers for sub-program */
63995       int nByte;              /* Bytes of runtime space required for sub-program */
63996       Mem *pRt;               /* Register to allocate runtime space */
63997       Mem *pMem;              /* Used to iterate through memory cells */
63998       Mem *pEnd;              /* Last memory cell in new array */
63999       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
64000       SubProgram *pProgram;   /* Sub-program to execute */
64001       void *t;                /* Token identifying trigger */
64002     } cb;
64003     struct OP_Param_stack_vars {
64004       VdbeFrame *pFrame;
64005       Mem *pIn;
64006     } cc;
64007     struct OP_MemMax_stack_vars {
64008       Mem *pIn1;
64009       VdbeFrame *pFrame;
64010     } cd;
64011     struct OP_AggStep_stack_vars {
64012       int n;
64013       int i;
64014       Mem *pMem;
64015       Mem *pRec;
64016       sqlite3_context ctx;
64017       sqlite3_value **apVal;
64018     } ce;
64019     struct OP_AggFinal_stack_vars {
64020       Mem *pMem;
64021     } cf;
64022     struct OP_Checkpoint_stack_vars {
64023       int i;                          /* Loop counter */
64024       int aRes[3];                    /* Results */
64025       Mem *pMem;                      /* Write results here */
64026     } cg;
64027     struct OP_JournalMode_stack_vars {
64028       Btree *pBt;                     /* Btree to change journal mode of */
64029       Pager *pPager;                  /* Pager associated with pBt */
64030       int eNew;                       /* New journal mode */
64031       int eOld;                       /* The old journal mode */
64032       const char *zFilename;          /* Name of database file for pPager */
64033     } ch;
64034     struct OP_IncrVacuum_stack_vars {
64035       Btree *pBt;
64036     } ci;
64037     struct OP_VBegin_stack_vars {
64038       VTable *pVTab;
64039     } cj;
64040     struct OP_VOpen_stack_vars {
64041       VdbeCursor *pCur;
64042       sqlite3_vtab_cursor *pVtabCursor;
64043       sqlite3_vtab *pVtab;
64044       sqlite3_module *pModule;
64045     } ck;
64046     struct OP_VFilter_stack_vars {
64047       int nArg;
64048       int iQuery;
64049       const sqlite3_module *pModule;
64050       Mem *pQuery;
64051       Mem *pArgc;
64052       sqlite3_vtab_cursor *pVtabCursor;
64053       sqlite3_vtab *pVtab;
64054       VdbeCursor *pCur;
64055       int res;
64056       int i;
64057       Mem **apArg;
64058     } cl;
64059     struct OP_VColumn_stack_vars {
64060       sqlite3_vtab *pVtab;
64061       const sqlite3_module *pModule;
64062       Mem *pDest;
64063       sqlite3_context sContext;
64064     } cm;
64065     struct OP_VNext_stack_vars {
64066       sqlite3_vtab *pVtab;
64067       const sqlite3_module *pModule;
64068       int res;
64069       VdbeCursor *pCur;
64070     } cn;
64071     struct OP_VRename_stack_vars {
64072       sqlite3_vtab *pVtab;
64073       Mem *pName;
64074     } co;
64075     struct OP_VUpdate_stack_vars {
64076       sqlite3_vtab *pVtab;
64077       sqlite3_module *pModule;
64078       int nArg;
64079       int i;
64080       sqlite_int64 rowid;
64081       Mem **apArg;
64082       Mem *pX;
64083     } cp;
64084     struct OP_Trace_stack_vars {
64085       char *zTrace;
64086       char *z;
64087     } cq;
64088   } u;
64089   /* End automatically generated code
64090   ********************************************************************/
64091 
64092   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
64093   sqlite3VdbeEnter(p);
64094   if( p->rc==SQLITE_NOMEM ){
64095     /* This happens if a malloc() inside a call to sqlite3_column_text() or
64096     ** sqlite3_column_text16() failed.  */
64097     goto no_mem;
64098   }
64099   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
64100   p->rc = SQLITE_OK;
64101   assert( p->explain==0 );
64102   p->pResultSet = 0;
64103   db->busyHandler.nBusy = 0;
64104   CHECK_FOR_INTERRUPT;
64105   sqlite3VdbeIOTraceSql(p);
64106 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64107   checkProgress = db->xProgress!=0;
64108 #endif
64109 #ifdef SQLITE_DEBUG
64110   sqlite3BeginBenignMalloc();
64111   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
64112     int i;
64113     printf("VDBE Program Listing:\n");
64114     sqlite3VdbePrintSql(p);
64115     for(i=0; i<p->nOp; i++){
64116       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
64117     }
64118   }
64119   sqlite3EndBenignMalloc();
64120 #endif
64121   for(pc=p->pc; rc==SQLITE_OK; pc++){
64122     assert( pc>=0 && pc<p->nOp );
64123     if( db->mallocFailed ) goto no_mem;
64124 #ifdef VDBE_PROFILE
64125     origPc = pc;
64126     start = sqlite3Hwtime();
64127 #endif
64128     pOp = &aOp[pc];
64129 
64130     /* Only allow tracing if SQLITE_DEBUG is defined.
64131     */
64132 #ifdef SQLITE_DEBUG
64133     if( p->trace ){
64134       if( pc==0 ){
64135         printf("VDBE Execution Trace:\n");
64136         sqlite3VdbePrintSql(p);
64137       }
64138       sqlite3VdbePrintOp(p->trace, pc, pOp);
64139     }
64140 #endif
64141 
64142 
64143     /* Check to see if we need to simulate an interrupt.  This only happens
64144     ** if we have a special test build.
64145     */
64146 #ifdef SQLITE_TEST
64147     if( sqlite3_interrupt_count>0 ){
64148       sqlite3_interrupt_count--;
64149       if( sqlite3_interrupt_count==0 ){
64150         sqlite3_interrupt(db);
64151       }
64152     }
64153 #endif
64154 
64155 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64156     /* Call the progress callback if it is configured and the required number
64157     ** of VDBE ops have been executed (either since this invocation of
64158     ** sqlite3VdbeExec() or since last time the progress callback was called).
64159     ** If the progress callback returns non-zero, exit the virtual machine with
64160     ** a return code SQLITE_ABORT.
64161     */
64162     if( checkProgress ){
64163       if( db->nProgressOps==nProgressOps ){
64164         int prc;
64165         prc = db->xProgress(db->pProgressArg);
64166         if( prc!=0 ){
64167           rc = SQLITE_INTERRUPT;
64168           goto vdbe_error_halt;
64169         }
64170         nProgressOps = 0;
64171       }
64172       nProgressOps++;
64173     }
64174 #endif
64175 
64176     /* On any opcode with the "out2-prerelase" tag, free any
64177     ** external allocations out of mem[p2] and set mem[p2] to be
64178     ** an undefined integer.  Opcodes will either fill in the integer
64179     ** value or convert mem[p2] to a different type.
64180     */
64181     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
64182     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
64183       assert( pOp->p2>0 );
64184       assert( pOp->p2<=p->nMem );
64185       pOut = &aMem[pOp->p2];
64186       memAboutToChange(p, pOut);
64187       MemReleaseExt(pOut);
64188       pOut->flags = MEM_Int;
64189     }
64190 
64191     /* Sanity checking on other operands */
64192 #ifdef SQLITE_DEBUG
64193     if( (pOp->opflags & OPFLG_IN1)!=0 ){
64194       assert( pOp->p1>0 );
64195       assert( pOp->p1<=p->nMem );
64196       assert( memIsValid(&aMem[pOp->p1]) );
64197       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
64198     }
64199     if( (pOp->opflags & OPFLG_IN2)!=0 ){
64200       assert( pOp->p2>0 );
64201       assert( pOp->p2<=p->nMem );
64202       assert( memIsValid(&aMem[pOp->p2]) );
64203       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
64204     }
64205     if( (pOp->opflags & OPFLG_IN3)!=0 ){
64206       assert( pOp->p3>0 );
64207       assert( pOp->p3<=p->nMem );
64208       assert( memIsValid(&aMem[pOp->p3]) );
64209       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
64210     }
64211     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
64212       assert( pOp->p2>0 );
64213       assert( pOp->p2<=p->nMem );
64214       memAboutToChange(p, &aMem[pOp->p2]);
64215     }
64216     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
64217       assert( pOp->p3>0 );
64218       assert( pOp->p3<=p->nMem );
64219       memAboutToChange(p, &aMem[pOp->p3]);
64220     }
64221 #endif
64222 
64223     switch( pOp->opcode ){
64224 
64225 /*****************************************************************************
64226 ** What follows is a massive switch statement where each case implements a
64227 ** separate instruction in the virtual machine.  If we follow the usual
64228 ** indentation conventions, each case should be indented by 6 spaces.  But
64229 ** that is a lot of wasted space on the left margin.  So the code within
64230 ** the switch statement will break with convention and be flush-left. Another
64231 ** big comment (similar to this one) will mark the point in the code where
64232 ** we transition back to normal indentation.
64233 **
64234 ** The formatting of each case is important.  The makefile for SQLite
64235 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
64236 ** file looking for lines that begin with "case OP_".  The opcodes.h files
64237 ** will be filled with #defines that give unique integer values to each
64238 ** opcode and the opcodes.c file is filled with an array of strings where
64239 ** each string is the symbolic name for the corresponding opcode.  If the
64240 ** case statement is followed by a comment of the form "/# same as ... #/"
64241 ** that comment is used to determine the particular value of the opcode.
64242 **
64243 ** Other keywords in the comment that follows each case are used to
64244 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
64245 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
64246 ** the mkopcodeh.awk script for additional information.
64247 **
64248 ** Documentation about VDBE opcodes is generated by scanning this file
64249 ** for lines of that contain "Opcode:".  That line and all subsequent
64250 ** comment lines are used in the generation of the opcode.html documentation
64251 ** file.
64252 **
64253 ** SUMMARY:
64254 **
64255 **     Formatting is important to scripts that scan this file.
64256 **     Do not deviate from the formatting style currently in use.
64257 **
64258 *****************************************************************************/
64259 
64260 /* Opcode:  Goto * P2 * * *
64261 **
64262 ** An unconditional jump to address P2.
64263 ** The next instruction executed will be
64264 ** the one at index P2 from the beginning of
64265 ** the program.
64266 */
64267 case OP_Goto: {             /* jump */
64268   CHECK_FOR_INTERRUPT;
64269   pc = pOp->p2 - 1;
64270   break;
64271 }
64272 
64273 /* Opcode:  Gosub P1 P2 * * *
64274 **
64275 ** Write the current address onto register P1
64276 ** and then jump to address P2.
64277 */
64278 case OP_Gosub: {            /* jump, in1 */
64279   pIn1 = &aMem[pOp->p1];
64280   assert( (pIn1->flags & MEM_Dyn)==0 );
64281   memAboutToChange(p, pIn1);
64282   pIn1->flags = MEM_Int;
64283   pIn1->u.i = pc;
64284   REGISTER_TRACE(pOp->p1, pIn1);
64285   pc = pOp->p2 - 1;
64286   break;
64287 }
64288 
64289 /* Opcode:  Return P1 * * * *
64290 **
64291 ** Jump to the next instruction after the address in register P1.
64292 */
64293 case OP_Return: {           /* in1 */
64294   pIn1 = &aMem[pOp->p1];
64295   assert( pIn1->flags & MEM_Int );
64296   pc = (int)pIn1->u.i;
64297   break;
64298 }
64299 
64300 /* Opcode:  Yield P1 * * * *
64301 **
64302 ** Swap the program counter with the value in register P1.
64303 */
64304 case OP_Yield: {            /* in1 */
64305 #if 0  /* local variables moved into u.aa */
64306   int pcDest;
64307 #endif /* local variables moved into u.aa */
64308   pIn1 = &aMem[pOp->p1];
64309   assert( (pIn1->flags & MEM_Dyn)==0 );
64310   pIn1->flags = MEM_Int;
64311   u.aa.pcDest = (int)pIn1->u.i;
64312   pIn1->u.i = pc;
64313   REGISTER_TRACE(pOp->p1, pIn1);
64314   pc = u.aa.pcDest;
64315   break;
64316 }
64317 
64318 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
64319 **
64320 ** Check the value in register P3.  If it is NULL then Halt using
64321 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
64322 ** value in register P3 is not NULL, then this routine is a no-op.
64323 */
64324 case OP_HaltIfNull: {      /* in3 */
64325   pIn3 = &aMem[pOp->p3];
64326   if( (pIn3->flags & MEM_Null)==0 ) break;
64327   /* Fall through into OP_Halt */
64328 }
64329 
64330 /* Opcode:  Halt P1 P2 * P4 *
64331 **
64332 ** Exit immediately.  All open cursors, etc are closed
64333 ** automatically.
64334 **
64335 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
64336 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
64337 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
64338 ** whether or not to rollback the current transaction.  Do not rollback
64339 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
64340 ** then back out all changes that have occurred during this execution of the
64341 ** VDBE, but do not rollback the transaction.
64342 **
64343 ** If P4 is not null then it is an error message string.
64344 **
64345 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
64346 ** every program.  So a jump past the last instruction of the program
64347 ** is the same as executing Halt.
64348 */
64349 case OP_Halt: {
64350   if( pOp->p1==SQLITE_OK && p->pFrame ){
64351     /* Halt the sub-program. Return control to the parent frame. */
64352     VdbeFrame *pFrame = p->pFrame;
64353     p->pFrame = pFrame->pParent;
64354     p->nFrame--;
64355     sqlite3VdbeSetChanges(db, p->nChange);
64356     pc = sqlite3VdbeFrameRestore(pFrame);
64357     lastRowid = db->lastRowid;
64358     if( pOp->p2==OE_Ignore ){
64359       /* Instruction pc is the OP_Program that invoked the sub-program
64360       ** currently being halted. If the p2 instruction of this OP_Halt
64361       ** instruction is set to OE_Ignore, then the sub-program is throwing
64362       ** an IGNORE exception. In this case jump to the address specified
64363       ** as the p2 of the calling OP_Program.  */
64364       pc = p->aOp[pc].p2-1;
64365     }
64366     aOp = p->aOp;
64367     aMem = p->aMem;
64368     break;
64369   }
64370 
64371   p->rc = pOp->p1;
64372   p->errorAction = (u8)pOp->p2;
64373   p->pc = pc;
64374   if( pOp->p4.z ){
64375     assert( p->rc!=SQLITE_OK );
64376     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
64377     testcase( sqlite3GlobalConfig.xLog!=0 );
64378     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
64379   }else if( p->rc ){
64380     testcase( sqlite3GlobalConfig.xLog!=0 );
64381     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
64382   }
64383   rc = sqlite3VdbeHalt(p);
64384   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
64385   if( rc==SQLITE_BUSY ){
64386     p->rc = rc = SQLITE_BUSY;
64387   }else{
64388     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
64389     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
64390     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
64391   }
64392   goto vdbe_return;
64393 }
64394 
64395 /* Opcode: Integer P1 P2 * * *
64396 **
64397 ** The 32-bit integer value P1 is written into register P2.
64398 */
64399 case OP_Integer: {         /* out2-prerelease */
64400   pOut->u.i = pOp->p1;
64401   break;
64402 }
64403 
64404 /* Opcode: Int64 * P2 * P4 *
64405 **
64406 ** P4 is a pointer to a 64-bit integer value.
64407 ** Write that value into register P2.
64408 */
64409 case OP_Int64: {           /* out2-prerelease */
64410   assert( pOp->p4.pI64!=0 );
64411   pOut->u.i = *pOp->p4.pI64;
64412   break;
64413 }
64414 
64415 #ifndef SQLITE_OMIT_FLOATING_POINT
64416 /* Opcode: Real * P2 * P4 *
64417 **
64418 ** P4 is a pointer to a 64-bit floating point value.
64419 ** Write that value into register P2.
64420 */
64421 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
64422   pOut->flags = MEM_Real;
64423   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
64424   pOut->r = *pOp->p4.pReal;
64425   break;
64426 }
64427 #endif
64428 
64429 /* Opcode: String8 * P2 * P4 *
64430 **
64431 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
64432 ** into an OP_String before it is executed for the first time.
64433 */
64434 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
64435   assert( pOp->p4.z!=0 );
64436   pOp->opcode = OP_String;
64437   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
64438 
64439 #ifndef SQLITE_OMIT_UTF16
64440   if( encoding!=SQLITE_UTF8 ){
64441     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
64442     if( rc==SQLITE_TOOBIG ) goto too_big;
64443     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
64444     assert( pOut->zMalloc==pOut->z );
64445     assert( pOut->flags & MEM_Dyn );
64446     pOut->zMalloc = 0;
64447     pOut->flags |= MEM_Static;
64448     pOut->flags &= ~MEM_Dyn;
64449     if( pOp->p4type==P4_DYNAMIC ){
64450       sqlite3DbFree(db, pOp->p4.z);
64451     }
64452     pOp->p4type = P4_DYNAMIC;
64453     pOp->p4.z = pOut->z;
64454     pOp->p1 = pOut->n;
64455   }
64456 #endif
64457   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64458     goto too_big;
64459   }
64460   /* Fall through to the next case, OP_String */
64461 }
64462 
64463 /* Opcode: String P1 P2 * P4 *
64464 **
64465 ** The string value P4 of length P1 (bytes) is stored in register P2.
64466 */
64467 case OP_String: {          /* out2-prerelease */
64468   assert( pOp->p4.z!=0 );
64469   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
64470   pOut->z = pOp->p4.z;
64471   pOut->n = pOp->p1;
64472   pOut->enc = encoding;
64473   UPDATE_MAX_BLOBSIZE(pOut);
64474   break;
64475 }
64476 
64477 /* Opcode: Null * P2 * * *
64478 **
64479 ** Write a NULL into register P2.
64480 */
64481 case OP_Null: {           /* out2-prerelease */
64482   pOut->flags = MEM_Null;
64483   break;
64484 }
64485 
64486 
64487 /* Opcode: Blob P1 P2 * P4
64488 **
64489 ** P4 points to a blob of data P1 bytes long.  Store this
64490 ** blob in register P2.
64491 */
64492 case OP_Blob: {                /* out2-prerelease */
64493   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
64494   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
64495   pOut->enc = encoding;
64496   UPDATE_MAX_BLOBSIZE(pOut);
64497   break;
64498 }
64499 
64500 /* Opcode: Variable P1 P2 * P4 *
64501 **
64502 ** Transfer the values of bound parameter P1 into register P2
64503 **
64504 ** If the parameter is named, then its name appears in P4 and P3==1.
64505 ** The P4 value is used by sqlite3_bind_parameter_name().
64506 */
64507 case OP_Variable: {            /* out2-prerelease */
64508 #if 0  /* local variables moved into u.ab */
64509   Mem *pVar;       /* Value being transferred */
64510 #endif /* local variables moved into u.ab */
64511 
64512   assert( pOp->p1>0 && pOp->p1<=p->nVar );
64513   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
64514   u.ab.pVar = &p->aVar[pOp->p1 - 1];
64515   if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
64516     goto too_big;
64517   }
64518   sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
64519   UPDATE_MAX_BLOBSIZE(pOut);
64520   break;
64521 }
64522 
64523 /* Opcode: Move P1 P2 P3 * *
64524 **
64525 ** Move the values in register P1..P1+P3-1 over into
64526 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
64527 ** left holding a NULL.  It is an error for register ranges
64528 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
64529 */
64530 case OP_Move: {
64531 #if 0  /* local variables moved into u.ac */
64532   char *zMalloc;   /* Holding variable for allocated memory */
64533   int n;           /* Number of registers left to copy */
64534   int p1;          /* Register to copy from */
64535   int p2;          /* Register to copy to */
64536 #endif /* local variables moved into u.ac */
64537 
64538   u.ac.n = pOp->p3;
64539   u.ac.p1 = pOp->p1;
64540   u.ac.p2 = pOp->p2;
64541   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
64542   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
64543 
64544   pIn1 = &aMem[u.ac.p1];
64545   pOut = &aMem[u.ac.p2];
64546   while( u.ac.n-- ){
64547     assert( pOut<=&aMem[p->nMem] );
64548     assert( pIn1<=&aMem[p->nMem] );
64549     assert( memIsValid(pIn1) );
64550     memAboutToChange(p, pOut);
64551     u.ac.zMalloc = pOut->zMalloc;
64552     pOut->zMalloc = 0;
64553     sqlite3VdbeMemMove(pOut, pIn1);
64554 #ifdef SQLITE_DEBUG
64555     if( pOut->pScopyFrom>=&aMem[u.ac.p1] && pOut->pScopyFrom<&aMem[u.ac.p1+pOp->p3] ){
64556       pOut->pScopyFrom += u.ac.p1 - pOp->p2;
64557     }
64558 #endif
64559     pIn1->zMalloc = u.ac.zMalloc;
64560     REGISTER_TRACE(u.ac.p2++, pOut);
64561     pIn1++;
64562     pOut++;
64563   }
64564   break;
64565 }
64566 
64567 /* Opcode: Copy P1 P2 * * *
64568 **
64569 ** Make a copy of register P1 into register P2.
64570 **
64571 ** This instruction makes a deep copy of the value.  A duplicate
64572 ** is made of any string or blob constant.  See also OP_SCopy.
64573 */
64574 case OP_Copy: {             /* in1, out2 */
64575   pIn1 = &aMem[pOp->p1];
64576   pOut = &aMem[pOp->p2];
64577   assert( pOut!=pIn1 );
64578   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64579   Deephemeralize(pOut);
64580   REGISTER_TRACE(pOp->p2, pOut);
64581   break;
64582 }
64583 
64584 /* Opcode: SCopy P1 P2 * * *
64585 **
64586 ** Make a shallow copy of register P1 into register P2.
64587 **
64588 ** This instruction makes a shallow copy of the value.  If the value
64589 ** is a string or blob, then the copy is only a pointer to the
64590 ** original and hence if the original changes so will the copy.
64591 ** Worse, if the original is deallocated, the copy becomes invalid.
64592 ** Thus the program must guarantee that the original will not change
64593 ** during the lifetime of the copy.  Use OP_Copy to make a complete
64594 ** copy.
64595 */
64596 case OP_SCopy: {            /* in1, out2 */
64597   pIn1 = &aMem[pOp->p1];
64598   pOut = &aMem[pOp->p2];
64599   assert( pOut!=pIn1 );
64600   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
64601 #ifdef SQLITE_DEBUG
64602   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
64603 #endif
64604   REGISTER_TRACE(pOp->p2, pOut);
64605   break;
64606 }
64607 
64608 /* Opcode: ResultRow P1 P2 * * *
64609 **
64610 ** The registers P1 through P1+P2-1 contain a single row of
64611 ** results. This opcode causes the sqlite3_step() call to terminate
64612 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
64613 ** structure to provide access to the top P1 values as the result
64614 ** row.
64615 */
64616 case OP_ResultRow: {
64617 #if 0  /* local variables moved into u.ad */
64618   Mem *pMem;
64619   int i;
64620 #endif /* local variables moved into u.ad */
64621   assert( p->nResColumn==pOp->p2 );
64622   assert( pOp->p1>0 );
64623   assert( pOp->p1+pOp->p2<=p->nMem+1 );
64624 
64625   /* If this statement has violated immediate foreign key constraints, do
64626   ** not return the number of rows modified. And do not RELEASE the statement
64627   ** transaction. It needs to be rolled back.  */
64628   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
64629     assert( db->flags&SQLITE_CountRows );
64630     assert( p->usesStmtJournal );
64631     break;
64632   }
64633 
64634   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
64635   ** DML statements invoke this opcode to return the number of rows
64636   ** modified to the user. This is the only way that a VM that
64637   ** opens a statement transaction may invoke this opcode.
64638   **
64639   ** In case this is such a statement, close any statement transaction
64640   ** opened by this VM before returning control to the user. This is to
64641   ** ensure that statement-transactions are always nested, not overlapping.
64642   ** If the open statement-transaction is not closed here, then the user
64643   ** may step another VM that opens its own statement transaction. This
64644   ** may lead to overlapping statement transactions.
64645   **
64646   ** The statement transaction is never a top-level transaction.  Hence
64647   ** the RELEASE call below can never fail.
64648   */
64649   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
64650   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
64651   if( NEVER(rc!=SQLITE_OK) ){
64652     break;
64653   }
64654 
64655   /* Invalidate all ephemeral cursor row caches */
64656   p->cacheCtr = (p->cacheCtr + 2)|1;
64657 
64658   /* Make sure the results of the current row are \000 terminated
64659   ** and have an assigned type.  The results are de-ephemeralized as
64660   ** as side effect.
64661   */
64662   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
64663   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
64664     assert( memIsValid(&u.ad.pMem[u.ad.i]) );
64665     Deephemeralize(&u.ad.pMem[u.ad.i]);
64666     assert( (u.ad.pMem[u.ad.i].flags & MEM_Ephem)==0
64667             || (u.ad.pMem[u.ad.i].flags & (MEM_Str|MEM_Blob))==0 );
64668     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
64669     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
64670     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
64671   }
64672   if( db->mallocFailed ) goto no_mem;
64673 
64674   /* Return SQLITE_ROW
64675   */
64676   p->pc = pc + 1;
64677   rc = SQLITE_ROW;
64678   goto vdbe_return;
64679 }
64680 
64681 /* Opcode: Concat P1 P2 P3 * *
64682 **
64683 ** Add the text in register P1 onto the end of the text in
64684 ** register P2 and store the result in register P3.
64685 ** If either the P1 or P2 text are NULL then store NULL in P3.
64686 **
64687 **   P3 = P2 || P1
64688 **
64689 ** It is illegal for P1 and P3 to be the same register. Sometimes,
64690 ** if P3 is the same register as P2, the implementation is able
64691 ** to avoid a memcpy().
64692 */
64693 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
64694 #if 0  /* local variables moved into u.ae */
64695   i64 nByte;
64696 #endif /* local variables moved into u.ae */
64697 
64698   pIn1 = &aMem[pOp->p1];
64699   pIn2 = &aMem[pOp->p2];
64700   pOut = &aMem[pOp->p3];
64701   assert( pIn1!=pOut );
64702   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
64703     sqlite3VdbeMemSetNull(pOut);
64704     break;
64705   }
64706   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
64707   Stringify(pIn1, encoding);
64708   Stringify(pIn2, encoding);
64709   u.ae.nByte = pIn1->n + pIn2->n;
64710   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
64711     goto too_big;
64712   }
64713   MemSetTypeFlag(pOut, MEM_Str);
64714   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
64715     goto no_mem;
64716   }
64717   if( pOut!=pIn2 ){
64718     memcpy(pOut->z, pIn2->z, pIn2->n);
64719   }
64720   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
64721   pOut->z[u.ae.nByte] = 0;
64722   pOut->z[u.ae.nByte+1] = 0;
64723   pOut->flags |= MEM_Term;
64724   pOut->n = (int)u.ae.nByte;
64725   pOut->enc = encoding;
64726   UPDATE_MAX_BLOBSIZE(pOut);
64727   break;
64728 }
64729 
64730 /* Opcode: Add P1 P2 P3 * *
64731 **
64732 ** Add the value in register P1 to the value in register P2
64733 ** and store the result in register P3.
64734 ** If either input is NULL, the result is NULL.
64735 */
64736 /* Opcode: Multiply P1 P2 P3 * *
64737 **
64738 **
64739 ** Multiply the value in register P1 by the value in register P2
64740 ** and store the result in register P3.
64741 ** If either input is NULL, the result is NULL.
64742 */
64743 /* Opcode: Subtract P1 P2 P3 * *
64744 **
64745 ** Subtract the value in register P1 from the value in register P2
64746 ** and store the result in register P3.
64747 ** If either input is NULL, the result is NULL.
64748 */
64749 /* Opcode: Divide P1 P2 P3 * *
64750 **
64751 ** Divide the value in register P1 by the value in register P2
64752 ** and store the result in register P3 (P3=P2/P1). If the value in
64753 ** register P1 is zero, then the result is NULL. If either input is
64754 ** NULL, the result is NULL.
64755 */
64756 /* Opcode: Remainder P1 P2 P3 * *
64757 **
64758 ** Compute the remainder after integer division of the value in
64759 ** register P1 by the value in register P2 and store the result in P3.
64760 ** If the value in register P2 is zero the result is NULL.
64761 ** If either operand is NULL, the result is NULL.
64762 */
64763 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
64764 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
64765 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
64766 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
64767 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
64768 #if 0  /* local variables moved into u.af */
64769   int flags;      /* Combined MEM_* flags from both inputs */
64770   i64 iA;         /* Integer value of left operand */
64771   i64 iB;         /* Integer value of right operand */
64772   double rA;      /* Real value of left operand */
64773   double rB;      /* Real value of right operand */
64774 #endif /* local variables moved into u.af */
64775 
64776   pIn1 = &aMem[pOp->p1];
64777   applyNumericAffinity(pIn1);
64778   pIn2 = &aMem[pOp->p2];
64779   applyNumericAffinity(pIn2);
64780   pOut = &aMem[pOp->p3];
64781   u.af.flags = pIn1->flags | pIn2->flags;
64782   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
64783   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
64784     u.af.iA = pIn1->u.i;
64785     u.af.iB = pIn2->u.i;
64786     switch( pOp->opcode ){
64787       case OP_Add:       if( sqlite3AddInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64788       case OP_Subtract:  if( sqlite3SubInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64789       case OP_Multiply:  if( sqlite3MulInt64(&u.af.iB,u.af.iA) ) goto fp_math;  break;
64790       case OP_Divide: {
64791         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64792         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) goto fp_math;
64793         u.af.iB /= u.af.iA;
64794         break;
64795       }
64796       default: {
64797         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64798         if( u.af.iA==-1 ) u.af.iA = 1;
64799         u.af.iB %= u.af.iA;
64800         break;
64801       }
64802     }
64803     pOut->u.i = u.af.iB;
64804     MemSetTypeFlag(pOut, MEM_Int);
64805   }else{
64806 fp_math:
64807     u.af.rA = sqlite3VdbeRealValue(pIn1);
64808     u.af.rB = sqlite3VdbeRealValue(pIn2);
64809     switch( pOp->opcode ){
64810       case OP_Add:         u.af.rB += u.af.rA;       break;
64811       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
64812       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
64813       case OP_Divide: {
64814         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
64815         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
64816         u.af.rB /= u.af.rA;
64817         break;
64818       }
64819       default: {
64820         u.af.iA = (i64)u.af.rA;
64821         u.af.iB = (i64)u.af.rB;
64822         if( u.af.iA==0 ) goto arithmetic_result_is_null;
64823         if( u.af.iA==-1 ) u.af.iA = 1;
64824         u.af.rB = (double)(u.af.iB % u.af.iA);
64825         break;
64826       }
64827     }
64828 #ifdef SQLITE_OMIT_FLOATING_POINT
64829     pOut->u.i = u.af.rB;
64830     MemSetTypeFlag(pOut, MEM_Int);
64831 #else
64832     if( sqlite3IsNaN(u.af.rB) ){
64833       goto arithmetic_result_is_null;
64834     }
64835     pOut->r = u.af.rB;
64836     MemSetTypeFlag(pOut, MEM_Real);
64837     if( (u.af.flags & MEM_Real)==0 ){
64838       sqlite3VdbeIntegerAffinity(pOut);
64839     }
64840 #endif
64841   }
64842   break;
64843 
64844 arithmetic_result_is_null:
64845   sqlite3VdbeMemSetNull(pOut);
64846   break;
64847 }
64848 
64849 /* Opcode: CollSeq * * P4
64850 **
64851 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
64852 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
64853 ** be returned. This is used by the built-in min(), max() and nullif()
64854 ** functions.
64855 **
64856 ** The interface used by the implementation of the aforementioned functions
64857 ** to retrieve the collation sequence set by this opcode is not available
64858 ** publicly, only to user functions defined in func.c.
64859 */
64860 case OP_CollSeq: {
64861   assert( pOp->p4type==P4_COLLSEQ );
64862   break;
64863 }
64864 
64865 /* Opcode: Function P1 P2 P3 P4 P5
64866 **
64867 ** Invoke a user function (P4 is a pointer to a Function structure that
64868 ** defines the function) with P5 arguments taken from register P2 and
64869 ** successors.  The result of the function is stored in register P3.
64870 ** Register P3 must not be one of the function inputs.
64871 **
64872 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
64873 ** function was determined to be constant at compile time. If the first
64874 ** argument was constant then bit 0 of P1 is set. This is used to determine
64875 ** whether meta data associated with a user function argument using the
64876 ** sqlite3_set_auxdata() API may be safely retained until the next
64877 ** invocation of this opcode.
64878 **
64879 ** See also: AggStep and AggFinal
64880 */
64881 case OP_Function: {
64882 #if 0  /* local variables moved into u.ag */
64883   int i;
64884   Mem *pArg;
64885   sqlite3_context ctx;
64886   sqlite3_value **apVal;
64887   int n;
64888 #endif /* local variables moved into u.ag */
64889 
64890   u.ag.n = pOp->p5;
64891   u.ag.apVal = p->apArg;
64892   assert( u.ag.apVal || u.ag.n==0 );
64893   assert( pOp->p3>0 && pOp->p3<=p->nMem );
64894   pOut = &aMem[pOp->p3];
64895   memAboutToChange(p, pOut);
64896 
64897   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
64898   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
64899   u.ag.pArg = &aMem[pOp->p2];
64900   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
64901     assert( memIsValid(u.ag.pArg) );
64902     u.ag.apVal[u.ag.i] = u.ag.pArg;
64903     Deephemeralize(u.ag.pArg);
64904     sqlite3VdbeMemStoreType(u.ag.pArg);
64905     REGISTER_TRACE(pOp->p2+u.ag.i, u.ag.pArg);
64906   }
64907 
64908   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
64909   if( pOp->p4type==P4_FUNCDEF ){
64910     u.ag.ctx.pFunc = pOp->p4.pFunc;
64911     u.ag.ctx.pVdbeFunc = 0;
64912   }else{
64913     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
64914     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
64915   }
64916 
64917   u.ag.ctx.s.flags = MEM_Null;
64918   u.ag.ctx.s.db = db;
64919   u.ag.ctx.s.xDel = 0;
64920   u.ag.ctx.s.zMalloc = 0;
64921 
64922   /* The output cell may already have a buffer allocated. Move
64923   ** the pointer to u.ag.ctx.s so in case the user-function can use
64924   ** the already allocated buffer instead of allocating a new one.
64925   */
64926   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
64927   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
64928 
64929   u.ag.ctx.isError = 0;
64930   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
64931     assert( pOp>aOp );
64932     assert( pOp[-1].p4type==P4_COLLSEQ );
64933     assert( pOp[-1].opcode==OP_CollSeq );
64934     u.ag.ctx.pColl = pOp[-1].p4.pColl;
64935   }
64936   db->lastRowid = lastRowid;
64937   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal); /* IMP: R-24505-23230 */
64938   lastRowid = db->lastRowid;
64939 
64940   /* If any auxiliary data functions have been called by this user function,
64941   ** immediately call the destructor for any non-static values.
64942   */
64943   if( u.ag.ctx.pVdbeFunc ){
64944     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
64945     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
64946     pOp->p4type = P4_VDBEFUNC;
64947   }
64948 
64949   if( db->mallocFailed ){
64950     /* Even though a malloc() has failed, the implementation of the
64951     ** user function may have called an sqlite3_result_XXX() function
64952     ** to return a value. The following call releases any resources
64953     ** associated with such a value.
64954     */
64955     sqlite3VdbeMemRelease(&u.ag.ctx.s);
64956     goto no_mem;
64957   }
64958 
64959   /* If the function returned an error, throw an exception */
64960   if( u.ag.ctx.isError ){
64961     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
64962     rc = u.ag.ctx.isError;
64963   }
64964 
64965   /* Copy the result of the function into register P3 */
64966   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
64967   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
64968   if( sqlite3VdbeMemTooBig(pOut) ){
64969     goto too_big;
64970   }
64971 
64972 #if 0
64973   /* The app-defined function has done something that as caused this
64974   ** statement to expire.  (Perhaps the function called sqlite3_exec()
64975   ** with a CREATE TABLE statement.)
64976   */
64977   if( p->expired ) rc = SQLITE_ABORT;
64978 #endif
64979 
64980   REGISTER_TRACE(pOp->p3, pOut);
64981   UPDATE_MAX_BLOBSIZE(pOut);
64982   break;
64983 }
64984 
64985 /* Opcode: BitAnd P1 P2 P3 * *
64986 **
64987 ** Take the bit-wise AND of the values in register P1 and P2 and
64988 ** store the result in register P3.
64989 ** If either input is NULL, the result is NULL.
64990 */
64991 /* Opcode: BitOr P1 P2 P3 * *
64992 **
64993 ** Take the bit-wise OR of the values in register P1 and P2 and
64994 ** store the result in register P3.
64995 ** If either input is NULL, the result is NULL.
64996 */
64997 /* Opcode: ShiftLeft P1 P2 P3 * *
64998 **
64999 ** Shift the integer value in register P2 to the left by the
65000 ** number of bits specified by the integer in register P1.
65001 ** Store the result in register P3.
65002 ** If either input is NULL, the result is NULL.
65003 */
65004 /* Opcode: ShiftRight P1 P2 P3 * *
65005 **
65006 ** Shift the integer value in register P2 to the right by the
65007 ** number of bits specified by the integer in register P1.
65008 ** Store the result in register P3.
65009 ** If either input is NULL, the result is NULL.
65010 */
65011 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
65012 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
65013 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
65014 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
65015 #if 0  /* local variables moved into u.ah */
65016   i64 iA;
65017   u64 uA;
65018   i64 iB;
65019   u8 op;
65020 #endif /* local variables moved into u.ah */
65021 
65022   pIn1 = &aMem[pOp->p1];
65023   pIn2 = &aMem[pOp->p2];
65024   pOut = &aMem[pOp->p3];
65025   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
65026     sqlite3VdbeMemSetNull(pOut);
65027     break;
65028   }
65029   u.ah.iA = sqlite3VdbeIntValue(pIn2);
65030   u.ah.iB = sqlite3VdbeIntValue(pIn1);
65031   u.ah.op = pOp->opcode;
65032   if( u.ah.op==OP_BitAnd ){
65033     u.ah.iA &= u.ah.iB;
65034   }else if( u.ah.op==OP_BitOr ){
65035     u.ah.iA |= u.ah.iB;
65036   }else if( u.ah.iB!=0 ){
65037     assert( u.ah.op==OP_ShiftRight || u.ah.op==OP_ShiftLeft );
65038 
65039     /* If shifting by a negative amount, shift in the other direction */
65040     if( u.ah.iB<0 ){
65041       assert( OP_ShiftRight==OP_ShiftLeft+1 );
65042       u.ah.op = 2*OP_ShiftLeft + 1 - u.ah.op;
65043       u.ah.iB = u.ah.iB>(-64) ? -u.ah.iB : 64;
65044     }
65045 
65046     if( u.ah.iB>=64 ){
65047       u.ah.iA = (u.ah.iA>=0 || u.ah.op==OP_ShiftLeft) ? 0 : -1;
65048     }else{
65049       memcpy(&u.ah.uA, &u.ah.iA, sizeof(u.ah.uA));
65050       if( u.ah.op==OP_ShiftLeft ){
65051         u.ah.uA <<= u.ah.iB;
65052       }else{
65053         u.ah.uA >>= u.ah.iB;
65054         /* Sign-extend on a right shift of a negative number */
65055         if( u.ah.iA<0 ) u.ah.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ah.iB);
65056       }
65057       memcpy(&u.ah.iA, &u.ah.uA, sizeof(u.ah.iA));
65058     }
65059   }
65060   pOut->u.i = u.ah.iA;
65061   MemSetTypeFlag(pOut, MEM_Int);
65062   break;
65063 }
65064 
65065 /* Opcode: AddImm  P1 P2 * * *
65066 **
65067 ** Add the constant P2 to the value in register P1.
65068 ** The result is always an integer.
65069 **
65070 ** To force any register to be an integer, just add 0.
65071 */
65072 case OP_AddImm: {            /* in1 */
65073   pIn1 = &aMem[pOp->p1];
65074   memAboutToChange(p, pIn1);
65075   sqlite3VdbeMemIntegerify(pIn1);
65076   pIn1->u.i += pOp->p2;
65077   break;
65078 }
65079 
65080 /* Opcode: MustBeInt P1 P2 * * *
65081 **
65082 ** Force the value in register P1 to be an integer.  If the value
65083 ** in P1 is not an integer and cannot be converted into an integer
65084 ** without data loss, then jump immediately to P2, or if P2==0
65085 ** raise an SQLITE_MISMATCH exception.
65086 */
65087 case OP_MustBeInt: {            /* jump, in1 */
65088   pIn1 = &aMem[pOp->p1];
65089   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
65090   if( (pIn1->flags & MEM_Int)==0 ){
65091     if( pOp->p2==0 ){
65092       rc = SQLITE_MISMATCH;
65093       goto abort_due_to_error;
65094     }else{
65095       pc = pOp->p2 - 1;
65096     }
65097   }else{
65098     MemSetTypeFlag(pIn1, MEM_Int);
65099   }
65100   break;
65101 }
65102 
65103 #ifndef SQLITE_OMIT_FLOATING_POINT
65104 /* Opcode: RealAffinity P1 * * * *
65105 **
65106 ** If register P1 holds an integer convert it to a real value.
65107 **
65108 ** This opcode is used when extracting information from a column that
65109 ** has REAL affinity.  Such column values may still be stored as
65110 ** integers, for space efficiency, but after extraction we want them
65111 ** to have only a real value.
65112 */
65113 case OP_RealAffinity: {                  /* in1 */
65114   pIn1 = &aMem[pOp->p1];
65115   if( pIn1->flags & MEM_Int ){
65116     sqlite3VdbeMemRealify(pIn1);
65117   }
65118   break;
65119 }
65120 #endif
65121 
65122 #ifndef SQLITE_OMIT_CAST
65123 /* Opcode: ToText P1 * * * *
65124 **
65125 ** Force the value in register P1 to be text.
65126 ** If the value is numeric, convert it to a string using the
65127 ** equivalent of printf().  Blob values are unchanged and
65128 ** are afterwards simply interpreted as text.
65129 **
65130 ** A NULL value is not changed by this routine.  It remains NULL.
65131 */
65132 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
65133   pIn1 = &aMem[pOp->p1];
65134   memAboutToChange(p, pIn1);
65135   if( pIn1->flags & MEM_Null ) break;
65136   assert( MEM_Str==(MEM_Blob>>3) );
65137   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
65138   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65139   rc = ExpandBlob(pIn1);
65140   assert( pIn1->flags & MEM_Str || db->mallocFailed );
65141   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
65142   UPDATE_MAX_BLOBSIZE(pIn1);
65143   break;
65144 }
65145 
65146 /* Opcode: ToBlob P1 * * * *
65147 **
65148 ** Force the value in register P1 to be a BLOB.
65149 ** If the value is numeric, convert it to a string first.
65150 ** Strings are simply reinterpreted as blobs with no change
65151 ** to the underlying data.
65152 **
65153 ** A NULL value is not changed by this routine.  It remains NULL.
65154 */
65155 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
65156   pIn1 = &aMem[pOp->p1];
65157   if( pIn1->flags & MEM_Null ) break;
65158   if( (pIn1->flags & MEM_Blob)==0 ){
65159     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
65160     assert( pIn1->flags & MEM_Str || db->mallocFailed );
65161     MemSetTypeFlag(pIn1, MEM_Blob);
65162   }else{
65163     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
65164   }
65165   UPDATE_MAX_BLOBSIZE(pIn1);
65166   break;
65167 }
65168 
65169 /* Opcode: ToNumeric P1 * * * *
65170 **
65171 ** Force the value in register P1 to be numeric (either an
65172 ** integer or a floating-point number.)
65173 ** If the value is text or blob, try to convert it to an using the
65174 ** equivalent of atoi() or atof() and store 0 if no such conversion
65175 ** is possible.
65176 **
65177 ** A NULL value is not changed by this routine.  It remains NULL.
65178 */
65179 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
65180   pIn1 = &aMem[pOp->p1];
65181   sqlite3VdbeMemNumerify(pIn1);
65182   break;
65183 }
65184 #endif /* SQLITE_OMIT_CAST */
65185 
65186 /* Opcode: ToInt P1 * * * *
65187 **
65188 ** Force the value in register P1 to be an integer.  If
65189 ** The value is currently a real number, drop its fractional part.
65190 ** If the value is text or blob, try to convert it to an integer using the
65191 ** equivalent of atoi() and store 0 if no such conversion is possible.
65192 **
65193 ** A NULL value is not changed by this routine.  It remains NULL.
65194 */
65195 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
65196   pIn1 = &aMem[pOp->p1];
65197   if( (pIn1->flags & MEM_Null)==0 ){
65198     sqlite3VdbeMemIntegerify(pIn1);
65199   }
65200   break;
65201 }
65202 
65203 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
65204 /* Opcode: ToReal P1 * * * *
65205 **
65206 ** Force the value in register P1 to be a floating point number.
65207 ** If The value is currently an integer, convert it.
65208 ** If the value is text or blob, try to convert it to an integer using the
65209 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
65210 **
65211 ** A NULL value is not changed by this routine.  It remains NULL.
65212 */
65213 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
65214   pIn1 = &aMem[pOp->p1];
65215   memAboutToChange(p, pIn1);
65216   if( (pIn1->flags & MEM_Null)==0 ){
65217     sqlite3VdbeMemRealify(pIn1);
65218   }
65219   break;
65220 }
65221 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
65222 
65223 /* Opcode: Lt P1 P2 P3 P4 P5
65224 **
65225 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
65226 ** jump to address P2.
65227 **
65228 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
65229 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
65230 ** bit is clear then fall through if either operand is NULL.
65231 **
65232 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
65233 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
65234 ** to coerce both inputs according to this affinity before the
65235 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
65236 ** affinity is used. Note that the affinity conversions are stored
65237 ** back into the input registers P1 and P3.  So this opcode can cause
65238 ** persistent changes to registers P1 and P3.
65239 **
65240 ** Once any conversions have taken place, and neither value is NULL,
65241 ** the values are compared. If both values are blobs then memcmp() is
65242 ** used to determine the results of the comparison.  If both values
65243 ** are text, then the appropriate collating function specified in
65244 ** P4 is  used to do the comparison.  If P4 is not specified then
65245 ** memcmp() is used to compare text string.  If both values are
65246 ** numeric, then a numeric comparison is used. If the two values
65247 ** are of different types, then numbers are considered less than
65248 ** strings and strings are considered less than blobs.
65249 **
65250 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
65251 ** store a boolean result (either 0, or 1, or NULL) in register P2.
65252 */
65253 /* Opcode: Ne P1 P2 P3 P4 P5
65254 **
65255 ** This works just like the Lt opcode except that the jump is taken if
65256 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
65257 ** additional information.
65258 **
65259 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65260 ** true or false and is never NULL.  If both operands are NULL then the result
65261 ** of comparison is false.  If either operand is NULL then the result is true.
65262 ** If neither operand is NULL the result is the same as it would be if
65263 ** the SQLITE_NULLEQ flag were omitted from P5.
65264 */
65265 /* Opcode: Eq P1 P2 P3 P4 P5
65266 **
65267 ** This works just like the Lt opcode except that the jump is taken if
65268 ** the operands in registers P1 and P3 are equal.
65269 ** See the Lt opcode for additional information.
65270 **
65271 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
65272 ** true or false and is never NULL.  If both operands are NULL then the result
65273 ** of comparison is true.  If either operand is NULL then the result is false.
65274 ** If neither operand is NULL the result is the same as it would be if
65275 ** the SQLITE_NULLEQ flag were omitted from P5.
65276 */
65277 /* Opcode: Le P1 P2 P3 P4 P5
65278 **
65279 ** This works just like the Lt opcode except that the jump is taken if
65280 ** the content of register P3 is less than or equal to the content of
65281 ** register P1.  See the Lt opcode for additional information.
65282 */
65283 /* Opcode: Gt P1 P2 P3 P4 P5
65284 **
65285 ** This works just like the Lt opcode except that the jump is taken if
65286 ** the content of register P3 is greater than the content of
65287 ** register P1.  See the Lt opcode for additional information.
65288 */
65289 /* Opcode: Ge P1 P2 P3 P4 P5
65290 **
65291 ** This works just like the Lt opcode except that the jump is taken if
65292 ** the content of register P3 is greater than or equal to the content of
65293 ** register P1.  See the Lt opcode for additional information.
65294 */
65295 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
65296 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
65297 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
65298 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
65299 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
65300 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
65301 #if 0  /* local variables moved into u.ai */
65302   int res;            /* Result of the comparison of pIn1 against pIn3 */
65303   char affinity;      /* Affinity to use for comparison */
65304   u16 flags1;         /* Copy of initial value of pIn1->flags */
65305   u16 flags3;         /* Copy of initial value of pIn3->flags */
65306 #endif /* local variables moved into u.ai */
65307 
65308   pIn1 = &aMem[pOp->p1];
65309   pIn3 = &aMem[pOp->p3];
65310   u.ai.flags1 = pIn1->flags;
65311   u.ai.flags3 = pIn3->flags;
65312   if( (u.ai.flags1 | u.ai.flags3)&MEM_Null ){
65313     /* One or both operands are NULL */
65314     if( pOp->p5 & SQLITE_NULLEQ ){
65315       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
65316       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
65317       ** or not both operands are null.
65318       */
65319       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
65320       u.ai.res = (u.ai.flags1 & u.ai.flags3 & MEM_Null)==0;
65321     }else{
65322       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
65323       ** then the result is always NULL.
65324       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
65325       */
65326       if( pOp->p5 & SQLITE_STOREP2 ){
65327         pOut = &aMem[pOp->p2];
65328         MemSetTypeFlag(pOut, MEM_Null);
65329         REGISTER_TRACE(pOp->p2, pOut);
65330       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
65331         pc = pOp->p2-1;
65332       }
65333       break;
65334     }
65335   }else{
65336     /* Neither operand is NULL.  Do a comparison. */
65337     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
65338     if( u.ai.affinity ){
65339       applyAffinity(pIn1, u.ai.affinity, encoding);
65340       applyAffinity(pIn3, u.ai.affinity, encoding);
65341       if( db->mallocFailed ) goto no_mem;
65342     }
65343 
65344     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
65345     ExpandBlob(pIn1);
65346     ExpandBlob(pIn3);
65347     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
65348   }
65349   switch( pOp->opcode ){
65350     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
65351     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
65352     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
65353     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
65354     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
65355     default:       u.ai.res = u.ai.res>=0;     break;
65356   }
65357 
65358   if( pOp->p5 & SQLITE_STOREP2 ){
65359     pOut = &aMem[pOp->p2];
65360     memAboutToChange(p, pOut);
65361     MemSetTypeFlag(pOut, MEM_Int);
65362     pOut->u.i = u.ai.res;
65363     REGISTER_TRACE(pOp->p2, pOut);
65364   }else if( u.ai.res ){
65365     pc = pOp->p2-1;
65366   }
65367 
65368   /* Undo any changes made by applyAffinity() to the input registers. */
65369   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
65370   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
65371   break;
65372 }
65373 
65374 /* Opcode: Permutation * * * P4 *
65375 **
65376 ** Set the permutation used by the OP_Compare operator to be the array
65377 ** of integers in P4.
65378 **
65379 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
65380 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
65381 ** immediately prior to the OP_Compare.
65382 */
65383 case OP_Permutation: {
65384   assert( pOp->p4type==P4_INTARRAY );
65385   assert( pOp->p4.ai );
65386   aPermute = pOp->p4.ai;
65387   break;
65388 }
65389 
65390 /* Opcode: Compare P1 P2 P3 P4 *
65391 **
65392 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
65393 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
65394 ** the comparison for use by the next OP_Jump instruct.
65395 **
65396 ** P4 is a KeyInfo structure that defines collating sequences and sort
65397 ** orders for the comparison.  The permutation applies to registers
65398 ** only.  The KeyInfo elements are used sequentially.
65399 **
65400 ** The comparison is a sort comparison, so NULLs compare equal,
65401 ** NULLs are less than numbers, numbers are less than strings,
65402 ** and strings are less than blobs.
65403 */
65404 case OP_Compare: {
65405 #if 0  /* local variables moved into u.aj */
65406   int n;
65407   int i;
65408   int p1;
65409   int p2;
65410   const KeyInfo *pKeyInfo;
65411   int idx;
65412   CollSeq *pColl;    /* Collating sequence to use on this term */
65413   int bRev;          /* True for DESCENDING sort order */
65414 #endif /* local variables moved into u.aj */
65415 
65416   u.aj.n = pOp->p3;
65417   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
65418   assert( u.aj.n>0 );
65419   assert( u.aj.pKeyInfo!=0 );
65420   u.aj.p1 = pOp->p1;
65421   u.aj.p2 = pOp->p2;
65422 #if SQLITE_DEBUG
65423   if( aPermute ){
65424     int k, mx = 0;
65425     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
65426     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
65427     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
65428   }else{
65429     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
65430     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
65431   }
65432 #endif /* SQLITE_DEBUG */
65433   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
65434     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
65435     assert( memIsValid(&aMem[u.aj.p1+u.aj.idx]) );
65436     assert( memIsValid(&aMem[u.aj.p2+u.aj.idx]) );
65437     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
65438     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
65439     assert( u.aj.i<u.aj.pKeyInfo->nField );
65440     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
65441     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
65442     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
65443     if( iCompare ){
65444       if( u.aj.bRev ) iCompare = -iCompare;
65445       break;
65446     }
65447   }
65448   aPermute = 0;
65449   break;
65450 }
65451 
65452 /* Opcode: Jump P1 P2 P3 * *
65453 **
65454 ** Jump to the instruction at address P1, P2, or P3 depending on whether
65455 ** in the most recent OP_Compare instruction the P1 vector was less than
65456 ** equal to, or greater than the P2 vector, respectively.
65457 */
65458 case OP_Jump: {             /* jump */
65459   if( iCompare<0 ){
65460     pc = pOp->p1 - 1;
65461   }else if( iCompare==0 ){
65462     pc = pOp->p2 - 1;
65463   }else{
65464     pc = pOp->p3 - 1;
65465   }
65466   break;
65467 }
65468 
65469 /* Opcode: And P1 P2 P3 * *
65470 **
65471 ** Take the logical AND of the values in registers P1 and P2 and
65472 ** write the result into register P3.
65473 **
65474 ** If either P1 or P2 is 0 (false) then the result is 0 even if
65475 ** the other input is NULL.  A NULL and true or two NULLs give
65476 ** a NULL output.
65477 */
65478 /* Opcode: Or P1 P2 P3 * *
65479 **
65480 ** Take the logical OR of the values in register P1 and P2 and
65481 ** store the answer in register P3.
65482 **
65483 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
65484 ** even if the other input is NULL.  A NULL and false or two NULLs
65485 ** give a NULL output.
65486 */
65487 case OP_And:              /* same as TK_AND, in1, in2, out3 */
65488 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
65489 #if 0  /* local variables moved into u.ak */
65490   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65491   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65492 #endif /* local variables moved into u.ak */
65493 
65494   pIn1 = &aMem[pOp->p1];
65495   if( pIn1->flags & MEM_Null ){
65496     u.ak.v1 = 2;
65497   }else{
65498     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
65499   }
65500   pIn2 = &aMem[pOp->p2];
65501   if( pIn2->flags & MEM_Null ){
65502     u.ak.v2 = 2;
65503   }else{
65504     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
65505   }
65506   if( pOp->opcode==OP_And ){
65507     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
65508     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
65509   }else{
65510     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
65511     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
65512   }
65513   pOut = &aMem[pOp->p3];
65514   if( u.ak.v1==2 ){
65515     MemSetTypeFlag(pOut, MEM_Null);
65516   }else{
65517     pOut->u.i = u.ak.v1;
65518     MemSetTypeFlag(pOut, MEM_Int);
65519   }
65520   break;
65521 }
65522 
65523 /* Opcode: Not P1 P2 * * *
65524 **
65525 ** Interpret the value in register P1 as a boolean value.  Store the
65526 ** boolean complement in register P2.  If the value in register P1 is
65527 ** NULL, then a NULL is stored in P2.
65528 */
65529 case OP_Not: {                /* same as TK_NOT, in1, out2 */
65530   pIn1 = &aMem[pOp->p1];
65531   pOut = &aMem[pOp->p2];
65532   if( pIn1->flags & MEM_Null ){
65533     sqlite3VdbeMemSetNull(pOut);
65534   }else{
65535     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
65536   }
65537   break;
65538 }
65539 
65540 /* Opcode: BitNot P1 P2 * * *
65541 **
65542 ** Interpret the content of register P1 as an integer.  Store the
65543 ** ones-complement of the P1 value into register P2.  If P1 holds
65544 ** a NULL then store a NULL in P2.
65545 */
65546 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
65547   pIn1 = &aMem[pOp->p1];
65548   pOut = &aMem[pOp->p2];
65549   if( pIn1->flags & MEM_Null ){
65550     sqlite3VdbeMemSetNull(pOut);
65551   }else{
65552     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
65553   }
65554   break;
65555 }
65556 
65557 /* Opcode: Once P1 P2 * * *
65558 **
65559 ** Jump to P2 if the value in register P1 is a not null or zero.  If
65560 ** the value is NULL or zero, fall through and change the P1 register
65561 ** to an integer 1.
65562 **
65563 ** When P1 is not used otherwise in a program, this opcode falls through
65564 ** once and jumps on all subsequent invocations.  It is the equivalent
65565 ** of "OP_If P1 P2", followed by "OP_Integer 1 P1".
65566 */
65567 /* Opcode: If P1 P2 P3 * *
65568 **
65569 ** Jump to P2 if the value in register P1 is true.  The value
65570 ** is considered true if it is numeric and non-zero.  If the value
65571 ** in P1 is NULL then take the jump if P3 is true.
65572 */
65573 /* Opcode: IfNot P1 P2 P3 * *
65574 **
65575 ** Jump to P2 if the value in register P1 is False.  The value
65576 ** is considered true if it has a numeric value of zero.  If the value
65577 ** in P1 is NULL then take the jump if P3 is true.
65578 */
65579 case OP_Once:               /* jump, in1 */
65580 case OP_If:                 /* jump, in1 */
65581 case OP_IfNot: {            /* jump, in1 */
65582 #if 0  /* local variables moved into u.al */
65583   int c;
65584 #endif /* local variables moved into u.al */
65585   pIn1 = &aMem[pOp->p1];
65586   if( pIn1->flags & MEM_Null ){
65587     u.al.c = pOp->p3;
65588   }else{
65589 #ifdef SQLITE_OMIT_FLOATING_POINT
65590     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
65591 #else
65592     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
65593 #endif
65594     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
65595   }
65596   if( u.al.c ){
65597     pc = pOp->p2-1;
65598   }else if( pOp->opcode==OP_Once ){
65599     assert( (pIn1->flags & (MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))==0 );
65600     memAboutToChange(p, pIn1);
65601     pIn1->flags = MEM_Int;
65602     pIn1->u.i = 1;
65603     REGISTER_TRACE(pOp->p1, pIn1);
65604   }
65605   break;
65606 }
65607 
65608 /* Opcode: IsNull P1 P2 * * *
65609 **
65610 ** Jump to P2 if the value in register P1 is NULL.
65611 */
65612 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
65613   pIn1 = &aMem[pOp->p1];
65614   if( (pIn1->flags & MEM_Null)!=0 ){
65615     pc = pOp->p2 - 1;
65616   }
65617   break;
65618 }
65619 
65620 /* Opcode: NotNull P1 P2 * * *
65621 **
65622 ** Jump to P2 if the value in register P1 is not NULL.
65623 */
65624 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
65625   pIn1 = &aMem[pOp->p1];
65626   if( (pIn1->flags & MEM_Null)==0 ){
65627     pc = pOp->p2 - 1;
65628   }
65629   break;
65630 }
65631 
65632 /* Opcode: Column P1 P2 P3 P4 P5
65633 **
65634 ** Interpret the data that cursor P1 points to as a structure built using
65635 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
65636 ** information about the format of the data.)  Extract the P2-th column
65637 ** from this record.  If there are less that (P2+1)
65638 ** values in the record, extract a NULL.
65639 **
65640 ** The value extracted is stored in register P3.
65641 **
65642 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
65643 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
65644 ** the result.
65645 **
65646 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
65647 ** then the cache of the cursor is reset prior to extracting the column.
65648 ** The first OP_Column against a pseudo-table after the value of the content
65649 ** register has changed should have this bit set.
65650 */
65651 case OP_Column: {
65652 #if 0  /* local variables moved into u.am */
65653   u32 payloadSize;   /* Number of bytes in the record */
65654   i64 payloadSize64; /* Number of bytes in the record */
65655   int p1;            /* P1 value of the opcode */
65656   int p2;            /* column number to retrieve */
65657   VdbeCursor *pC;    /* The VDBE cursor */
65658   char *zRec;        /* Pointer to complete record-data */
65659   BtCursor *pCrsr;   /* The BTree cursor */
65660   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65661   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65662   int nField;        /* number of fields in the record */
65663   int len;           /* The length of the serialized data for the column */
65664   int i;             /* Loop counter */
65665   char *zData;       /* Part of the record being decoded */
65666   Mem *pDest;        /* Where to write the extracted value */
65667   Mem sMem;          /* For storing the record being decoded */
65668   u8 *zIdx;          /* Index into header */
65669   u8 *zEndHdr;       /* Pointer to first byte after the header */
65670   u32 offset;        /* Offset into the data */
65671   u32 szField;       /* Number of bytes in the content of a field */
65672   int szHdr;         /* Size of the header size field at start of record */
65673   int avail;         /* Number of bytes of available data */
65674   u32 t;             /* A type code from the record header */
65675   Mem *pReg;         /* PseudoTable input register */
65676 #endif /* local variables moved into u.am */
65677 
65678 
65679   u.am.p1 = pOp->p1;
65680   u.am.p2 = pOp->p2;
65681   u.am.pC = 0;
65682   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
65683   assert( u.am.p1<p->nCursor );
65684   assert( pOp->p3>0 && pOp->p3<=p->nMem );
65685   u.am.pDest = &aMem[pOp->p3];
65686   memAboutToChange(p, u.am.pDest);
65687   u.am.zRec = 0;
65688 
65689   /* This block sets the variable u.am.payloadSize to be the total number of
65690   ** bytes in the record.
65691   **
65692   ** u.am.zRec is set to be the complete text of the record if it is available.
65693   ** The complete record text is always available for pseudo-tables
65694   ** If the record is stored in a cursor, the complete record text
65695   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
65696   ** If the data is unavailable,  u.am.zRec is set to NULL.
65697   **
65698   ** We also compute the number of columns in the record.  For cursors,
65699   ** the number of columns is stored in the VdbeCursor.nField element.
65700   */
65701   u.am.pC = p->apCsr[u.am.p1];
65702   assert( u.am.pC!=0 );
65703 #ifndef SQLITE_OMIT_VIRTUALTABLE
65704   assert( u.am.pC->pVtabCursor==0 );
65705 #endif
65706   u.am.pCrsr = u.am.pC->pCursor;
65707   if( u.am.pCrsr!=0 ){
65708     /* The record is stored in a B-Tree */
65709     rc = sqlite3VdbeCursorMoveto(u.am.pC);
65710     if( rc ) goto abort_due_to_error;
65711     if( u.am.pC->nullRow ){
65712       u.am.payloadSize = 0;
65713     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
65714       u.am.payloadSize = u.am.pC->payloadSize;
65715       u.am.zRec = (char*)u.am.pC->aRow;
65716     }else if( u.am.pC->isIndex ){
65717       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
65718       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
65719       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
65720       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
65721       ** payload size, so it is impossible for u.am.payloadSize64 to be
65722       ** larger than 32 bits. */
65723       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
65724       u.am.payloadSize = (u32)u.am.payloadSize64;
65725     }else{
65726       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
65727       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
65728       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
65729     }
65730   }else if( ALWAYS(u.am.pC->pseudoTableReg>0) ){
65731     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
65732     assert( u.am.pReg->flags & MEM_Blob );
65733     assert( memIsValid(u.am.pReg) );
65734     u.am.payloadSize = u.am.pReg->n;
65735     u.am.zRec = u.am.pReg->z;
65736     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
65737     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
65738   }else{
65739     /* Consider the row to be NULL */
65740     u.am.payloadSize = 0;
65741   }
65742 
65743   /* If u.am.payloadSize is 0, then just store a NULL.  This can happen because of
65744   ** nullRow or because of a corrupt database. */
65745   if( u.am.payloadSize==0 ){
65746     MemSetTypeFlag(u.am.pDest, MEM_Null);
65747     goto op_column_out;
65748   }
65749   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
65750   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
65751     goto too_big;
65752   }
65753 
65754   u.am.nField = u.am.pC->nField;
65755   assert( u.am.p2<u.am.nField );
65756 
65757   /* Read and parse the table header.  Store the results of the parse
65758   ** into the record header cache fields of the cursor.
65759   */
65760   u.am.aType = u.am.pC->aType;
65761   if( u.am.pC->cacheStatus==p->cacheCtr ){
65762     u.am.aOffset = u.am.pC->aOffset;
65763   }else{
65764     assert(u.am.aType);
65765     u.am.avail = 0;
65766     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
65767     u.am.pC->payloadSize = u.am.payloadSize;
65768     u.am.pC->cacheStatus = p->cacheCtr;
65769 
65770     /* Figure out how many bytes are in the header */
65771     if( u.am.zRec ){
65772       u.am.zData = u.am.zRec;
65773     }else{
65774       if( u.am.pC->isIndex ){
65775         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
65776       }else{
65777         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
65778       }
65779       /* If KeyFetch()/DataFetch() managed to get the entire payload,
65780       ** save the payload in the u.am.pC->aRow cache.  That will save us from
65781       ** having to make additional calls to fetch the content portion of
65782       ** the record.
65783       */
65784       assert( u.am.avail>=0 );
65785       if( u.am.payloadSize <= (u32)u.am.avail ){
65786         u.am.zRec = u.am.zData;
65787         u.am.pC->aRow = (u8*)u.am.zData;
65788       }else{
65789         u.am.pC->aRow = 0;
65790       }
65791     }
65792     /* The following assert is true in all cases accept when
65793     ** the database file has been corrupted externally.
65794     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
65795     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
65796 
65797     /* Make sure a corrupt database has not given us an oversize header.
65798     ** Do this now to avoid an oversize memory allocation.
65799     **
65800     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
65801     ** types use so much data space that there can only be 4096 and 32 of
65802     ** them, respectively.  So the maximum header length results from a
65803     ** 3-byte type for each of the maximum of 32768 columns plus three
65804     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
65805     */
65806     if( u.am.offset > 98307 ){
65807       rc = SQLITE_CORRUPT_BKPT;
65808       goto op_column_out;
65809     }
65810 
65811     /* Compute in u.am.len the number of bytes of data we need to read in order
65812     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
65813     ** u.am.nField might be significantly less than the true number of columns
65814     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
65815     ** We want to minimize u.am.len in order to limit the size of the memory
65816     ** allocation, especially if a corrupt database file has caused u.am.offset
65817     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
65818     ** still exceed Robson memory allocation limits on some configurations.
65819     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
65820     ** will likely be much smaller since u.am.nField will likely be less than
65821     ** 20 or so.  This insures that Robson memory allocation limits are
65822     ** not exceeded even for corrupt database files.
65823     */
65824     u.am.len = u.am.nField*5 + 3;
65825     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
65826 
65827     /* The KeyFetch() or DataFetch() above are fast and will get the entire
65828     ** record header in most cases.  But they will fail to get the complete
65829     ** record header if the record header does not fit on a single page
65830     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
65831     ** acquire the complete header text.
65832     */
65833     if( !u.am.zRec && u.am.avail<u.am.len ){
65834       u.am.sMem.flags = 0;
65835       u.am.sMem.db = 0;
65836       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
65837       if( rc!=SQLITE_OK ){
65838         goto op_column_out;
65839       }
65840       u.am.zData = u.am.sMem.z;
65841     }
65842     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
65843     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
65844 
65845     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
65846     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
65847     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
65848     ** of the record to the start of the data for the u.am.i-th column
65849     */
65850     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
65851       if( u.am.zIdx<u.am.zEndHdr ){
65852         u.am.aOffset[u.am.i] = u.am.offset;
65853         if( u.am.zIdx[0]<0x80 ){
65854           u.am.t = u.am.zIdx[0];
65855           u.am.zIdx++;
65856         }else{
65857           u.am.zIdx += sqlite3GetVarint32(u.am.zIdx, &u.am.t);
65858         }
65859         u.am.aType[u.am.i] = u.am.t;
65860         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.t);
65861         u.am.offset += u.am.szField;
65862         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
65863           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
65864           break;
65865         }
65866       }else{
65867         /* If u.am.i is less that u.am.nField, then there are less fields in this
65868         ** record than SetNumColumns indicated there are columns in the
65869         ** table. Set the u.am.offset for any extra columns not present in
65870         ** the record to 0. This tells code below to store a NULL
65871         ** instead of deserializing a value from the record.
65872         */
65873         u.am.aOffset[u.am.i] = 0;
65874       }
65875     }
65876     sqlite3VdbeMemRelease(&u.am.sMem);
65877     u.am.sMem.flags = MEM_Null;
65878 
65879     /* If we have read more header data than was contained in the header,
65880     ** or if the end of the last field appears to be past the end of the
65881     ** record, or if the end of the last field appears to be before the end
65882     ** of the record (when all fields present), then we must be dealing
65883     ** with a corrupt database.
65884     */
65885     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
65886          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
65887       rc = SQLITE_CORRUPT_BKPT;
65888       goto op_column_out;
65889     }
65890   }
65891 
65892   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
65893   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
65894   ** then there are not enough fields in the record to satisfy the
65895   ** request.  In this case, set the value NULL or to P4 if P4 is
65896   ** a pointer to a Mem object.
65897   */
65898   if( u.am.aOffset[u.am.p2] ){
65899     assert( rc==SQLITE_OK );
65900     if( u.am.zRec ){
65901       MemReleaseExt(u.am.pDest);
65902       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
65903     }else{
65904       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
65905       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
65906       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
65907       if( rc!=SQLITE_OK ){
65908         goto op_column_out;
65909       }
65910       u.am.zData = u.am.sMem.z;
65911       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
65912     }
65913     u.am.pDest->enc = encoding;
65914   }else{
65915     if( pOp->p4type==P4_MEM ){
65916       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
65917     }else{
65918       MemSetTypeFlag(u.am.pDest, MEM_Null);
65919     }
65920   }
65921 
65922   /* If we dynamically allocated space to hold the data (in the
65923   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
65924   ** dynamically allocated space over to the u.am.pDest structure.
65925   ** This prevents a memory copy.
65926   */
65927   if( u.am.sMem.zMalloc ){
65928     assert( u.am.sMem.z==u.am.sMem.zMalloc );
65929     assert( !(u.am.pDest->flags & MEM_Dyn) );
65930     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
65931     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
65932     u.am.pDest->flags |= MEM_Term;
65933     u.am.pDest->z = u.am.sMem.z;
65934     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
65935   }
65936 
65937   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
65938 
65939 op_column_out:
65940   UPDATE_MAX_BLOBSIZE(u.am.pDest);
65941   REGISTER_TRACE(pOp->p3, u.am.pDest);
65942   break;
65943 }
65944 
65945 /* Opcode: Affinity P1 P2 * P4 *
65946 **
65947 ** Apply affinities to a range of P2 registers starting with P1.
65948 **
65949 ** P4 is a string that is P2 characters long. The nth character of the
65950 ** string indicates the column affinity that should be used for the nth
65951 ** memory cell in the range.
65952 */
65953 case OP_Affinity: {
65954 #if 0  /* local variables moved into u.an */
65955   const char *zAffinity;   /* The affinity to be applied */
65956   char cAff;               /* A single character of affinity */
65957 #endif /* local variables moved into u.an */
65958 
65959   u.an.zAffinity = pOp->p4.z;
65960   assert( u.an.zAffinity!=0 );
65961   assert( u.an.zAffinity[pOp->p2]==0 );
65962   pIn1 = &aMem[pOp->p1];
65963   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
65964     assert( pIn1 <= &p->aMem[p->nMem] );
65965     assert( memIsValid(pIn1) );
65966     ExpandBlob(pIn1);
65967     applyAffinity(pIn1, u.an.cAff, encoding);
65968     pIn1++;
65969   }
65970   break;
65971 }
65972 
65973 /* Opcode: MakeRecord P1 P2 P3 P4 *
65974 **
65975 ** Convert P2 registers beginning with P1 into the [record format]
65976 ** use as a data record in a database table or as a key
65977 ** in an index.  The OP_Column opcode can decode the record later.
65978 **
65979 ** P4 may be a string that is P2 characters long.  The nth character of the
65980 ** string indicates the column affinity that should be used for the nth
65981 ** field of the index key.
65982 **
65983 ** The mapping from character to affinity is given by the SQLITE_AFF_
65984 ** macros defined in sqliteInt.h.
65985 **
65986 ** If P4 is NULL then all index fields have the affinity NONE.
65987 */
65988 case OP_MakeRecord: {
65989 #if 0  /* local variables moved into u.ao */
65990   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65991   Mem *pRec;             /* The new record */
65992   u64 nData;             /* Number of bytes of data space */
65993   int nHdr;              /* Number of bytes of header space */
65994   i64 nByte;             /* Data space required for this record */
65995   int nZero;             /* Number of zero bytes at the end of the record */
65996   int nVarint;           /* Number of bytes in a varint */
65997   u32 serial_type;       /* Type field */
65998   Mem *pData0;           /* First field to be combined into the record */
65999   Mem *pLast;            /* Last field of the record */
66000   int nField;            /* Number of fields in the record */
66001   char *zAffinity;       /* The affinity string for the record */
66002   int file_format;       /* File format to use for encoding */
66003   int i;                 /* Space used in zNewRecord[] */
66004   int len;               /* Length of a field */
66005 #endif /* local variables moved into u.ao */
66006 
66007   /* Assuming the record contains N fields, the record format looks
66008   ** like this:
66009   **
66010   ** ------------------------------------------------------------------------
66011   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
66012   ** ------------------------------------------------------------------------
66013   **
66014   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
66015   ** and so froth.
66016   **
66017   ** Each type field is a varint representing the serial type of the
66018   ** corresponding data element (see sqlite3VdbeSerialType()). The
66019   ** hdr-size field is also a varint which is the offset from the beginning
66020   ** of the record to data0.
66021   */
66022   u.ao.nData = 0;         /* Number of bytes of data space */
66023   u.ao.nHdr = 0;          /* Number of bytes of header space */
66024   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
66025   u.ao.nField = pOp->p1;
66026   u.ao.zAffinity = pOp->p4.z;
66027   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
66028   u.ao.pData0 = &aMem[u.ao.nField];
66029   u.ao.nField = pOp->p2;
66030   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
66031   u.ao.file_format = p->minWriteFileFormat;
66032 
66033   /* Identify the output register */
66034   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
66035   pOut = &aMem[pOp->p3];
66036   memAboutToChange(p, pOut);
66037 
66038   /* Loop through the elements that will make up the record to figure
66039   ** out how much space is required for the new record.
66040   */
66041   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
66042     assert( memIsValid(u.ao.pRec) );
66043     if( u.ao.zAffinity ){
66044       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
66045     }
66046     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
66047       sqlite3VdbeMemExpandBlob(u.ao.pRec);
66048     }
66049     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
66050     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
66051     u.ao.nData += u.ao.len;
66052     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
66053     if( u.ao.pRec->flags & MEM_Zero ){
66054       /* Only pure zero-filled BLOBs can be input to this Opcode.
66055       ** We do not allow blobs with a prefix and a zero-filled tail. */
66056       u.ao.nZero += u.ao.pRec->u.nZero;
66057     }else if( u.ao.len ){
66058       u.ao.nZero = 0;
66059     }
66060   }
66061 
66062   /* Add the initial header varint and total the size */
66063   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
66064   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
66065     u.ao.nHdr++;
66066   }
66067   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
66068   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66069     goto too_big;
66070   }
66071 
66072   /* Make sure the output register has a buffer large enough to store
66073   ** the new record. The output register (pOp->p3) is not allowed to
66074   ** be one of the input registers (because the following call to
66075   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
66076   */
66077   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
66078     goto no_mem;
66079   }
66080   u.ao.zNewRecord = (u8 *)pOut->z;
66081 
66082   /* Write the record */
66083   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
66084   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
66085     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
66086     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
66087   }
66088   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
66089     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
66090   }
66091   assert( u.ao.i==u.ao.nByte );
66092 
66093   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66094   pOut->n = (int)u.ao.nByte;
66095   pOut->flags = MEM_Blob | MEM_Dyn;
66096   pOut->xDel = 0;
66097   if( u.ao.nZero ){
66098     pOut->u.nZero = u.ao.nZero;
66099     pOut->flags |= MEM_Zero;
66100   }
66101   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
66102   REGISTER_TRACE(pOp->p3, pOut);
66103   UPDATE_MAX_BLOBSIZE(pOut);
66104   break;
66105 }
66106 
66107 /* Opcode: Count P1 P2 * * *
66108 **
66109 ** Store the number of entries (an integer value) in the table or index
66110 ** opened by cursor P1 in register P2
66111 */
66112 #ifndef SQLITE_OMIT_BTREECOUNT
66113 case OP_Count: {         /* out2-prerelease */
66114 #if 0  /* local variables moved into u.ap */
66115   i64 nEntry;
66116   BtCursor *pCrsr;
66117 #endif /* local variables moved into u.ap */
66118 
66119   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
66120   if( ALWAYS(u.ap.pCrsr) ){
66121     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
66122   }else{
66123     u.ap.nEntry = 0;
66124   }
66125   pOut->u.i = u.ap.nEntry;
66126   break;
66127 }
66128 #endif
66129 
66130 /* Opcode: Savepoint P1 * * P4 *
66131 **
66132 ** Open, release or rollback the savepoint named by parameter P4, depending
66133 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
66134 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
66135 */
66136 case OP_Savepoint: {
66137 #if 0  /* local variables moved into u.aq */
66138   int p1;                         /* Value of P1 operand */
66139   char *zName;                    /* Name of savepoint */
66140   int nName;
66141   Savepoint *pNew;
66142   Savepoint *pSavepoint;
66143   Savepoint *pTmp;
66144   int iSavepoint;
66145   int ii;
66146 #endif /* local variables moved into u.aq */
66147 
66148   u.aq.p1 = pOp->p1;
66149   u.aq.zName = pOp->p4.z;
66150 
66151   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
66152   ** transaction, then there cannot be any savepoints.
66153   */
66154   assert( db->pSavepoint==0 || db->autoCommit==0 );
66155   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
66156   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
66157   assert( checkSavepointCount(db) );
66158 
66159   if( u.aq.p1==SAVEPOINT_BEGIN ){
66160     if( db->writeVdbeCnt>0 ){
66161       /* A new savepoint cannot be created if there are active write
66162       ** statements (i.e. open read/write incremental blob handles).
66163       */
66164       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
66165         "SQL statements in progress");
66166       rc = SQLITE_BUSY;
66167     }else{
66168       u.aq.nName = sqlite3Strlen30(u.aq.zName);
66169 
66170 #ifndef SQLITE_OMIT_VIRTUALTABLE
66171       /* This call is Ok even if this savepoint is actually a transaction
66172       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
66173       ** If this is a transaction savepoint being opened, it is guaranteed
66174       ** that the db->aVTrans[] array is empty.  */
66175       assert( db->autoCommit==0 || db->nVTrans==0 );
66176       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
66177                                 db->nStatement+db->nSavepoint);
66178       if( rc!=SQLITE_OK ) goto abort_due_to_error;
66179 #endif
66180 
66181       /* Create a new savepoint structure. */
66182       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
66183       if( u.aq.pNew ){
66184         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
66185         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
66186 
66187         /* If there is no open transaction, then mark this as a special
66188         ** "transaction savepoint". */
66189         if( db->autoCommit ){
66190           db->autoCommit = 0;
66191           db->isTransactionSavepoint = 1;
66192         }else{
66193           db->nSavepoint++;
66194         }
66195 
66196         /* Link the new savepoint into the database handle's list. */
66197         u.aq.pNew->pNext = db->pSavepoint;
66198         db->pSavepoint = u.aq.pNew;
66199         u.aq.pNew->nDeferredCons = db->nDeferredCons;
66200       }
66201     }
66202   }else{
66203     u.aq.iSavepoint = 0;
66204 
66205     /* Find the named savepoint. If there is no such savepoint, then an
66206     ** an error is returned to the user.  */
66207     for(
66208       u.aq.pSavepoint = db->pSavepoint;
66209       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
66210       u.aq.pSavepoint = u.aq.pSavepoint->pNext
66211     ){
66212       u.aq.iSavepoint++;
66213     }
66214     if( !u.aq.pSavepoint ){
66215       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
66216       rc = SQLITE_ERROR;
66217     }else if(
66218         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
66219     ){
66220       /* It is not possible to release (commit) a savepoint if there are
66221       ** active write statements. It is not possible to rollback a savepoint
66222       ** if there are any active statements at all.
66223       */
66224       sqlite3SetString(&p->zErrMsg, db,
66225         "cannot %s savepoint - SQL statements in progress",
66226         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
66227       );
66228       rc = SQLITE_BUSY;
66229     }else{
66230 
66231       /* Determine whether or not this is a transaction savepoint. If so,
66232       ** and this is a RELEASE command, then the current transaction
66233       ** is committed.
66234       */
66235       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
66236       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
66237         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66238           goto vdbe_return;
66239         }
66240         db->autoCommit = 1;
66241         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66242           p->pc = pc;
66243           db->autoCommit = 0;
66244           p->rc = rc = SQLITE_BUSY;
66245           goto vdbe_return;
66246         }
66247         db->isTransactionSavepoint = 0;
66248         rc = p->rc;
66249       }else{
66250         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
66251         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
66252           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
66253           if( rc!=SQLITE_OK ){
66254             goto abort_due_to_error;
66255           }
66256         }
66257         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
66258           sqlite3ExpirePreparedStatements(db);
66259           sqlite3ResetInternalSchema(db, -1);
66260           db->flags = (db->flags | SQLITE_InternChanges);
66261         }
66262       }
66263 
66264       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
66265       ** savepoints nested inside of the savepoint being operated on. */
66266       while( db->pSavepoint!=u.aq.pSavepoint ){
66267         u.aq.pTmp = db->pSavepoint;
66268         db->pSavepoint = u.aq.pTmp->pNext;
66269         sqlite3DbFree(db, u.aq.pTmp);
66270         db->nSavepoint--;
66271       }
66272 
66273       /* If it is a RELEASE, then destroy the savepoint being operated on
66274       ** too. If it is a ROLLBACK TO, then set the number of deferred
66275       ** constraint violations present in the database to the value stored
66276       ** when the savepoint was created.  */
66277       if( u.aq.p1==SAVEPOINT_RELEASE ){
66278         assert( u.aq.pSavepoint==db->pSavepoint );
66279         db->pSavepoint = u.aq.pSavepoint->pNext;
66280         sqlite3DbFree(db, u.aq.pSavepoint);
66281         if( !isTransaction ){
66282           db->nSavepoint--;
66283         }
66284       }else{
66285         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
66286       }
66287 
66288       if( !isTransaction ){
66289         rc = sqlite3VtabSavepoint(db, u.aq.p1, u.aq.iSavepoint);
66290         if( rc!=SQLITE_OK ) goto abort_due_to_error;
66291       }
66292     }
66293   }
66294 
66295   break;
66296 }
66297 
66298 /* Opcode: AutoCommit P1 P2 * * *
66299 **
66300 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
66301 ** back any currently active btree transactions. If there are any active
66302 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
66303 ** there are active writing VMs or active VMs that use shared cache.
66304 **
66305 ** This instruction causes the VM to halt.
66306 */
66307 case OP_AutoCommit: {
66308 #if 0  /* local variables moved into u.ar */
66309   int desiredAutoCommit;
66310   int iRollback;
66311   int turnOnAC;
66312 #endif /* local variables moved into u.ar */
66313 
66314   u.ar.desiredAutoCommit = pOp->p1;
66315   u.ar.iRollback = pOp->p2;
66316   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
66317   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
66318   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
66319   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
66320 
66321   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
66322     /* If this instruction implements a ROLLBACK and other VMs are
66323     ** still running, and a transaction is active, return an error indicating
66324     ** that the other VMs must complete first.
66325     */
66326     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
66327         "SQL statements in progress");
66328     rc = SQLITE_BUSY;
66329   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
66330     /* If this instruction implements a COMMIT and other VMs are writing
66331     ** return an error indicating that the other VMs must complete first.
66332     */
66333     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
66334         "SQL statements in progress");
66335     rc = SQLITE_BUSY;
66336   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
66337     if( u.ar.iRollback ){
66338       assert( u.ar.desiredAutoCommit==1 );
66339       sqlite3RollbackAll(db);
66340       db->autoCommit = 1;
66341     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
66342       goto vdbe_return;
66343     }else{
66344       db->autoCommit = (u8)u.ar.desiredAutoCommit;
66345       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
66346         p->pc = pc;
66347         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
66348         p->rc = rc = SQLITE_BUSY;
66349         goto vdbe_return;
66350       }
66351     }
66352     assert( db->nStatement==0 );
66353     sqlite3CloseSavepoints(db);
66354     if( p->rc==SQLITE_OK ){
66355       rc = SQLITE_DONE;
66356     }else{
66357       rc = SQLITE_ERROR;
66358     }
66359     goto vdbe_return;
66360   }else{
66361     sqlite3SetString(&p->zErrMsg, db,
66362         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
66363         (u.ar.iRollback)?"cannot rollback - no transaction is active":
66364                    "cannot commit - no transaction is active"));
66365 
66366     rc = SQLITE_ERROR;
66367   }
66368   break;
66369 }
66370 
66371 /* Opcode: Transaction P1 P2 * * *
66372 **
66373 ** Begin a transaction.  The transaction ends when a Commit or Rollback
66374 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
66375 ** transaction might also be rolled back if an error is encountered.
66376 **
66377 ** P1 is the index of the database file on which the transaction is
66378 ** started.  Index 0 is the main database file and index 1 is the
66379 ** file used for temporary tables.  Indices of 2 or more are used for
66380 ** attached databases.
66381 **
66382 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
66383 ** obtained on the database file when a write-transaction is started.  No
66384 ** other process can start another write transaction while this transaction is
66385 ** underway.  Starting a write transaction also creates a rollback journal. A
66386 ** write transaction must be started before any changes can be made to the
66387 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
66388 ** on the file.
66389 **
66390 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
66391 ** true (this flag is set if the Vdbe may modify more than one row and may
66392 ** throw an ABORT exception), a statement transaction may also be opened.
66393 ** More specifically, a statement transaction is opened iff the database
66394 ** connection is currently not in autocommit mode, or if there are other
66395 ** active statements. A statement transaction allows the affects of this
66396 ** VDBE to be rolled back after an error without having to roll back the
66397 ** entire transaction. If no error is encountered, the statement transaction
66398 ** will automatically commit when the VDBE halts.
66399 **
66400 ** If P2 is zero, then a read-lock is obtained on the database file.
66401 */
66402 case OP_Transaction: {
66403 #if 0  /* local variables moved into u.as */
66404   Btree *pBt;
66405 #endif /* local variables moved into u.as */
66406 
66407   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66408   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66409   u.as.pBt = db->aDb[pOp->p1].pBt;
66410 
66411   if( u.as.pBt ){
66412     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
66413     if( rc==SQLITE_BUSY ){
66414       p->pc = pc;
66415       p->rc = rc = SQLITE_BUSY;
66416       goto vdbe_return;
66417     }
66418     if( rc!=SQLITE_OK ){
66419       goto abort_due_to_error;
66420     }
66421 
66422     if( pOp->p2 && p->usesStmtJournal
66423      && (db->autoCommit==0 || db->activeVdbeCnt>1)
66424     ){
66425       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
66426       if( p->iStatement==0 ){
66427         assert( db->nStatement>=0 && db->nSavepoint>=0 );
66428         db->nStatement++;
66429         p->iStatement = db->nSavepoint + db->nStatement;
66430       }
66431 
66432       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
66433       if( rc==SQLITE_OK ){
66434         rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
66435       }
66436 
66437       /* Store the current value of the database handles deferred constraint
66438       ** counter. If the statement transaction needs to be rolled back,
66439       ** the value of this counter needs to be restored too.  */
66440       p->nStmtDefCons = db->nDeferredCons;
66441     }
66442   }
66443   break;
66444 }
66445 
66446 /* Opcode: ReadCookie P1 P2 P3 * *
66447 **
66448 ** Read cookie number P3 from database P1 and write it into register P2.
66449 ** P3==1 is the schema version.  P3==2 is the database format.
66450 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
66451 ** the main database file and P1==1 is the database file used to store
66452 ** temporary tables.
66453 **
66454 ** There must be a read-lock on the database (either a transaction
66455 ** must be started or there must be an open cursor) before
66456 ** executing this instruction.
66457 */
66458 case OP_ReadCookie: {               /* out2-prerelease */
66459 #if 0  /* local variables moved into u.at */
66460   int iMeta;
66461   int iDb;
66462   int iCookie;
66463 #endif /* local variables moved into u.at */
66464 
66465   u.at.iDb = pOp->p1;
66466   u.at.iCookie = pOp->p3;
66467   assert( pOp->p3<SQLITE_N_BTREE_META );
66468   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
66469   assert( db->aDb[u.at.iDb].pBt!=0 );
66470   assert( (p->btreeMask & (((yDbMask)1)<<u.at.iDb))!=0 );
66471 
66472   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
66473   pOut->u.i = u.at.iMeta;
66474   break;
66475 }
66476 
66477 /* Opcode: SetCookie P1 P2 P3 * *
66478 **
66479 ** Write the content of register P3 (interpreted as an integer)
66480 ** into cookie number P2 of database P1.  P2==1 is the schema version.
66481 ** P2==2 is the database format. P2==3 is the recommended pager cache
66482 ** size, and so forth.  P1==0 is the main database file and P1==1 is the
66483 ** database file used to store temporary tables.
66484 **
66485 ** A transaction must be started before executing this opcode.
66486 */
66487 case OP_SetCookie: {       /* in3 */
66488 #if 0  /* local variables moved into u.au */
66489   Db *pDb;
66490 #endif /* local variables moved into u.au */
66491   assert( pOp->p2<SQLITE_N_BTREE_META );
66492   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66493   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66494   u.au.pDb = &db->aDb[pOp->p1];
66495   assert( u.au.pDb->pBt!=0 );
66496   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66497   pIn3 = &aMem[pOp->p3];
66498   sqlite3VdbeMemIntegerify(pIn3);
66499   /* See note about index shifting on OP_ReadCookie */
66500   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
66501   if( pOp->p2==BTREE_SCHEMA_VERSION ){
66502     /* When the schema cookie changes, record the new cookie internally */
66503     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
66504     db->flags |= SQLITE_InternChanges;
66505   }else if( pOp->p2==BTREE_FILE_FORMAT ){
66506     /* Record changes in the file format */
66507     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
66508   }
66509   if( pOp->p1==1 ){
66510     /* Invalidate all prepared statements whenever the TEMP database
66511     ** schema is changed.  Ticket #1644 */
66512     sqlite3ExpirePreparedStatements(db);
66513     p->expired = 0;
66514   }
66515   break;
66516 }
66517 
66518 /* Opcode: VerifyCookie P1 P2 P3 * *
66519 **
66520 ** Check the value of global database parameter number 0 (the
66521 ** schema version) and make sure it is equal to P2 and that the
66522 ** generation counter on the local schema parse equals P3.
66523 **
66524 ** P1 is the database number which is 0 for the main database file
66525 ** and 1 for the file holding temporary tables and some higher number
66526 ** for auxiliary databases.
66527 **
66528 ** The cookie changes its value whenever the database schema changes.
66529 ** This operation is used to detect when that the cookie has changed
66530 ** and that the current process needs to reread the schema.
66531 **
66532 ** Either a transaction needs to have been started or an OP_Open needs
66533 ** to be executed (to establish a read lock) before this opcode is
66534 ** invoked.
66535 */
66536 case OP_VerifyCookie: {
66537 #if 0  /* local variables moved into u.av */
66538   int iMeta;
66539   int iGen;
66540   Btree *pBt;
66541 #endif /* local variables moved into u.av */
66542 
66543   assert( pOp->p1>=0 && pOp->p1<db->nDb );
66544   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
66545   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
66546   u.av.pBt = db->aDb[pOp->p1].pBt;
66547   if( u.av.pBt ){
66548     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
66549     u.av.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
66550   }else{
66551     u.av.iGen = u.av.iMeta = 0;
66552   }
66553   if( u.av.iMeta!=pOp->p2 || u.av.iGen!=pOp->p3 ){
66554     sqlite3DbFree(db, p->zErrMsg);
66555     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
66556     /* If the schema-cookie from the database file matches the cookie
66557     ** stored with the in-memory representation of the schema, do
66558     ** not reload the schema from the database file.
66559     **
66560     ** If virtual-tables are in use, this is not just an optimization.
66561     ** Often, v-tables store their data in other SQLite tables, which
66562     ** are queried from within xNext() and other v-table methods using
66563     ** prepared queries. If such a query is out-of-date, we do not want to
66564     ** discard the database schema, as the user code implementing the
66565     ** v-table would have to be ready for the sqlite3_vtab structure itself
66566     ** to be invalidated whenever sqlite3_step() is called from within
66567     ** a v-table method.
66568     */
66569     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
66570       sqlite3ResetInternalSchema(db, pOp->p1);
66571     }
66572 
66573     p->expired = 1;
66574     rc = SQLITE_SCHEMA;
66575   }
66576   break;
66577 }
66578 
66579 /* Opcode: OpenRead P1 P2 P3 P4 P5
66580 **
66581 ** Open a read-only cursor for the database table whose root page is
66582 ** P2 in a database file.  The database file is determined by P3.
66583 ** P3==0 means the main database, P3==1 means the database used for
66584 ** temporary tables, and P3>1 means used the corresponding attached
66585 ** database.  Give the new cursor an identifier of P1.  The P1
66586 ** values need not be contiguous but all P1 values should be small integers.
66587 ** It is an error for P1 to be negative.
66588 **
66589 ** If P5!=0 then use the content of register P2 as the root page, not
66590 ** the value of P2 itself.
66591 **
66592 ** There will be a read lock on the database whenever there is an
66593 ** open cursor.  If the database was unlocked prior to this instruction
66594 ** then a read lock is acquired as part of this instruction.  A read
66595 ** lock allows other processes to read the database but prohibits
66596 ** any other process from modifying the database.  The read lock is
66597 ** released when all cursors are closed.  If this instruction attempts
66598 ** to get a read lock but fails, the script terminates with an
66599 ** SQLITE_BUSY error code.
66600 **
66601 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66602 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
66603 ** structure, then said structure defines the content and collating
66604 ** sequence of the index being opened. Otherwise, if P4 is an integer
66605 ** value, it is set to the number of columns in the table.
66606 **
66607 ** See also OpenWrite.
66608 */
66609 /* Opcode: OpenWrite P1 P2 P3 P4 P5
66610 **
66611 ** Open a read/write cursor named P1 on the table or index whose root
66612 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
66613 ** root page.
66614 **
66615 ** The P4 value may be either an integer (P4_INT32) or a pointer to
66616 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
66617 ** structure, then said structure defines the content and collating
66618 ** sequence of the index being opened. Otherwise, if P4 is an integer
66619 ** value, it is set to the number of columns in the table, or to the
66620 ** largest index of any column of the table that is actually used.
66621 **
66622 ** This instruction works just like OpenRead except that it opens the cursor
66623 ** in read/write mode.  For a given table, there can be one or more read-only
66624 ** cursors or a single read/write cursor but not both.
66625 **
66626 ** See also OpenRead.
66627 */
66628 case OP_OpenRead:
66629 case OP_OpenWrite: {
66630 #if 0  /* local variables moved into u.aw */
66631   int nField;
66632   KeyInfo *pKeyInfo;
66633   int p2;
66634   int iDb;
66635   int wrFlag;
66636   Btree *pX;
66637   VdbeCursor *pCur;
66638   Db *pDb;
66639 #endif /* local variables moved into u.aw */
66640 
66641   if( p->expired ){
66642     rc = SQLITE_ABORT;
66643     break;
66644   }
66645 
66646   u.aw.nField = 0;
66647   u.aw.pKeyInfo = 0;
66648   u.aw.p2 = pOp->p2;
66649   u.aw.iDb = pOp->p3;
66650   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
66651   assert( (p->btreeMask & (((yDbMask)1)<<u.aw.iDb))!=0 );
66652   u.aw.pDb = &db->aDb[u.aw.iDb];
66653   u.aw.pX = u.aw.pDb->pBt;
66654   assert( u.aw.pX!=0 );
66655   if( pOp->opcode==OP_OpenWrite ){
66656     u.aw.wrFlag = 1;
66657     assert( sqlite3SchemaMutexHeld(db, u.aw.iDb, 0) );
66658     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
66659       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
66660     }
66661   }else{
66662     u.aw.wrFlag = 0;
66663   }
66664   if( pOp->p5 ){
66665     assert( u.aw.p2>0 );
66666     assert( u.aw.p2<=p->nMem );
66667     pIn2 = &aMem[u.aw.p2];
66668     assert( memIsValid(pIn2) );
66669     assert( (pIn2->flags & MEM_Int)!=0 );
66670     sqlite3VdbeMemIntegerify(pIn2);
66671     u.aw.p2 = (int)pIn2->u.i;
66672     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
66673     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
66674     ** If there were a failure, the prepared statement would have halted
66675     ** before reaching this instruction. */
66676     if( NEVER(u.aw.p2<2) ) {
66677       rc = SQLITE_CORRUPT_BKPT;
66678       goto abort_due_to_error;
66679     }
66680   }
66681   if( pOp->p4type==P4_KEYINFO ){
66682     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
66683     u.aw.pKeyInfo->enc = ENC(p->db);
66684     u.aw.nField = u.aw.pKeyInfo->nField+1;
66685   }else if( pOp->p4type==P4_INT32 ){
66686     u.aw.nField = pOp->p4.i;
66687   }
66688   assert( pOp->p1>=0 );
66689   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
66690   if( u.aw.pCur==0 ) goto no_mem;
66691   u.aw.pCur->nullRow = 1;
66692   u.aw.pCur->isOrdered = 1;
66693   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
66694   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
66695 
66696   /* Since it performs no memory allocation or IO, the only value that
66697   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
66698   assert( rc==SQLITE_OK );
66699 
66700   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
66701   ** SQLite used to check if the root-page flags were sane at this point
66702   ** and report database corruption if they were not, but this check has
66703   ** since moved into the btree layer.  */
66704   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
66705   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
66706   break;
66707 }
66708 
66709 /* Opcode: OpenEphemeral P1 P2 * P4 P5
66710 **
66711 ** Open a new cursor P1 to a transient table.
66712 ** The cursor is always opened read/write even if
66713 ** the main database is read-only.  The ephemeral
66714 ** table is deleted automatically when the cursor is closed.
66715 **
66716 ** P2 is the number of columns in the ephemeral table.
66717 ** The cursor points to a BTree table if P4==0 and to a BTree index
66718 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
66719 ** that defines the format of keys in the index.
66720 **
66721 ** This opcode was once called OpenTemp.  But that created
66722 ** confusion because the term "temp table", might refer either
66723 ** to a TEMP table at the SQL level, or to a table opened by
66724 ** this opcode.  Then this opcode was call OpenVirtual.  But
66725 ** that created confusion with the whole virtual-table idea.
66726 **
66727 ** The P5 parameter can be a mask of the BTREE_* flags defined
66728 ** in btree.h.  These flags control aspects of the operation of
66729 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
66730 ** added automatically.
66731 */
66732 /* Opcode: OpenAutoindex P1 P2 * P4 *
66733 **
66734 ** This opcode works the same as OP_OpenEphemeral.  It has a
66735 ** different name to distinguish its use.  Tables created using
66736 ** by this opcode will be used for automatically created transient
66737 ** indices in joins.
66738 */
66739 case OP_OpenAutoindex:
66740 case OP_OpenEphemeral: {
66741 #if 0  /* local variables moved into u.ax */
66742   VdbeCursor *pCx;
66743 #endif /* local variables moved into u.ax */
66744   static const int vfsFlags =
66745       SQLITE_OPEN_READWRITE |
66746       SQLITE_OPEN_CREATE |
66747       SQLITE_OPEN_EXCLUSIVE |
66748       SQLITE_OPEN_DELETEONCLOSE |
66749       SQLITE_OPEN_TRANSIENT_DB;
66750 
66751   assert( pOp->p1>=0 );
66752   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66753   if( u.ax.pCx==0 ) goto no_mem;
66754   u.ax.pCx->nullRow = 1;
66755   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ax.pCx->pBt,
66756                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
66757   if( rc==SQLITE_OK ){
66758     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
66759   }
66760   if( rc==SQLITE_OK ){
66761     /* If a transient index is required, create it by calling
66762     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
66763     ** opening it. If a transient table is required, just use the
66764     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
66765     */
66766     if( pOp->p4.pKeyInfo ){
66767       int pgno;
66768       assert( pOp->p4type==P4_KEYINFO );
66769       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
66770       if( rc==SQLITE_OK ){
66771         assert( pgno==MASTER_ROOT+1 );
66772         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
66773                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
66774         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66775         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
66776       }
66777       u.ax.pCx->isTable = 0;
66778     }else{
66779       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
66780       u.ax.pCx->isTable = 1;
66781     }
66782   }
66783   u.ax.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
66784   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
66785   break;
66786 }
66787 
66788 /* Opcode: OpenSorter P1 P2 * P4 *
66789 **
66790 ** This opcode works like OP_OpenEphemeral except that it opens
66791 ** a transient index that is specifically designed to sort large
66792 ** tables using an external merge-sort algorithm.
66793 */
66794 case OP_SorterOpen: {
66795 #if 0  /* local variables moved into u.ay */
66796   VdbeCursor *pCx;
66797 #endif /* local variables moved into u.ay */
66798 #ifndef SQLITE_OMIT_MERGE_SORT
66799   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
66800   if( u.ay.pCx==0 ) goto no_mem;
66801   u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
66802   u.ay.pCx->pKeyInfo->enc = ENC(p->db);
66803   u.ay.pCx->isSorter = 1;
66804   rc = sqlite3VdbeSorterInit(db, u.ay.pCx);
66805 #else
66806   pOp->opcode = OP_OpenEphemeral;
66807   pc--;
66808 #endif
66809   break;
66810 }
66811 
66812 /* Opcode: OpenPseudo P1 P2 P3 * *
66813 **
66814 ** Open a new cursor that points to a fake table that contains a single
66815 ** row of data.  The content of that one row in the content of memory
66816 ** register P2.  In other words, cursor P1 becomes an alias for the
66817 ** MEM_Blob content contained in register P2.
66818 **
66819 ** A pseudo-table created by this opcode is used to hold a single
66820 ** row output from the sorter so that the row can be decomposed into
66821 ** individual columns using the OP_Column opcode.  The OP_Column opcode
66822 ** is the only cursor opcode that works with a pseudo-table.
66823 **
66824 ** P3 is the number of fields in the records that will be stored by
66825 ** the pseudo-table.
66826 */
66827 case OP_OpenPseudo: {
66828 #if 0  /* local variables moved into u.az */
66829   VdbeCursor *pCx;
66830 #endif /* local variables moved into u.az */
66831 
66832   assert( pOp->p1>=0 );
66833   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
66834   if( u.az.pCx==0 ) goto no_mem;
66835   u.az.pCx->nullRow = 1;
66836   u.az.pCx->pseudoTableReg = pOp->p2;
66837   u.az.pCx->isTable = 1;
66838   u.az.pCx->isIndex = 0;
66839   break;
66840 }
66841 
66842 /* Opcode: Close P1 * * * *
66843 **
66844 ** Close a cursor previously opened as P1.  If P1 is not
66845 ** currently open, this instruction is a no-op.
66846 */
66847 case OP_Close: {
66848   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66849   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
66850   p->apCsr[pOp->p1] = 0;
66851   break;
66852 }
66853 
66854 /* Opcode: SeekGe P1 P2 P3 P4 *
66855 **
66856 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66857 ** use the value in register P3 as the key.  If cursor P1 refers
66858 ** to an SQL index, then P3 is the first in an array of P4 registers
66859 ** that are used as an unpacked index key.
66860 **
66861 ** Reposition cursor P1 so that  it points to the smallest entry that
66862 ** is greater than or equal to the key value. If there are no records
66863 ** greater than or equal to the key and P2 is not zero, then jump to P2.
66864 **
66865 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
66866 */
66867 /* Opcode: SeekGt P1 P2 P3 P4 *
66868 **
66869 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66870 ** use the value in register P3 as a key. If cursor P1 refers
66871 ** to an SQL index, then P3 is the first in an array of P4 registers
66872 ** that are used as an unpacked index key.
66873 **
66874 ** Reposition cursor P1 so that  it points to the smallest entry that
66875 ** is greater than the key value. If there are no records greater than
66876 ** the key and P2 is not zero, then jump to P2.
66877 **
66878 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
66879 */
66880 /* Opcode: SeekLt P1 P2 P3 P4 *
66881 **
66882 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66883 ** use the value in register P3 as a key. If cursor P1 refers
66884 ** to an SQL index, then P3 is the first in an array of P4 registers
66885 ** that are used as an unpacked index key.
66886 **
66887 ** Reposition cursor P1 so that  it points to the largest entry that
66888 ** is less than the key value. If there are no records less than
66889 ** the key and P2 is not zero, then jump to P2.
66890 **
66891 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
66892 */
66893 /* Opcode: SeekLe P1 P2 P3 P4 *
66894 **
66895 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
66896 ** use the value in register P3 as a key. If cursor P1 refers
66897 ** to an SQL index, then P3 is the first in an array of P4 registers
66898 ** that are used as an unpacked index key.
66899 **
66900 ** Reposition cursor P1 so that it points to the largest entry that
66901 ** is less than or equal to the key value. If there are no records
66902 ** less than or equal to the key and P2 is not zero, then jump to P2.
66903 **
66904 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
66905 */
66906 case OP_SeekLt:         /* jump, in3 */
66907 case OP_SeekLe:         /* jump, in3 */
66908 case OP_SeekGe:         /* jump, in3 */
66909 case OP_SeekGt: {       /* jump, in3 */
66910 #if 0  /* local variables moved into u.ba */
66911   int res;
66912   int oc;
66913   VdbeCursor *pC;
66914   UnpackedRecord r;
66915   int nField;
66916   i64 iKey;      /* The rowid we are to seek to */
66917 #endif /* local variables moved into u.ba */
66918 
66919   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
66920   assert( pOp->p2!=0 );
66921   u.ba.pC = p->apCsr[pOp->p1];
66922   assert( u.ba.pC!=0 );
66923   assert( u.ba.pC->pseudoTableReg==0 );
66924   assert( OP_SeekLe == OP_SeekLt+1 );
66925   assert( OP_SeekGe == OP_SeekLt+2 );
66926   assert( OP_SeekGt == OP_SeekLt+3 );
66927   assert( u.ba.pC->isOrdered );
66928   if( ALWAYS(u.ba.pC->pCursor!=0) ){
66929     u.ba.oc = pOp->opcode;
66930     u.ba.pC->nullRow = 0;
66931     if( u.ba.pC->isTable ){
66932       /* The input value in P3 might be of any type: integer, real, string,
66933       ** blob, or NULL.  But it needs to be an integer before we can do
66934       ** the seek, so covert it. */
66935       pIn3 = &aMem[pOp->p3];
66936       applyNumericAffinity(pIn3);
66937       u.ba.iKey = sqlite3VdbeIntValue(pIn3);
66938       u.ba.pC->rowidIsValid = 0;
66939 
66940       /* If the P3 value could not be converted into an integer without
66941       ** loss of information, then special processing is required... */
66942       if( (pIn3->flags & MEM_Int)==0 ){
66943         if( (pIn3->flags & MEM_Real)==0 ){
66944           /* If the P3 value cannot be converted into any kind of a number,
66945           ** then the seek is not possible, so jump to P2 */
66946           pc = pOp->p2 - 1;
66947           break;
66948         }
66949         /* If we reach this point, then the P3 value must be a floating
66950         ** point number. */
66951         assert( (pIn3->flags & MEM_Real)!=0 );
66952 
66953         if( u.ba.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.ba.iKey || pIn3->r>0) ){
66954           /* The P3 value is too large in magnitude to be expressed as an
66955           ** integer. */
66956           u.ba.res = 1;
66957           if( pIn3->r<0 ){
66958             if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
66959               rc = sqlite3BtreeFirst(u.ba.pC->pCursor, &u.ba.res);
66960               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66961             }
66962           }else{
66963             if( u.ba.oc<=OP_SeekLe ){  assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
66964               rc = sqlite3BtreeLast(u.ba.pC->pCursor, &u.ba.res);
66965               if( rc!=SQLITE_OK ) goto abort_due_to_error;
66966             }
66967           }
66968           if( u.ba.res ){
66969             pc = pOp->p2 - 1;
66970           }
66971           break;
66972         }else if( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekGe ){
66973           /* Use the ceiling() function to convert real->int */
66974           if( pIn3->r > (double)u.ba.iKey ) u.ba.iKey++;
66975         }else{
66976           /* Use the floor() function to convert real->int */
66977           assert( u.ba.oc==OP_SeekLe || u.ba.oc==OP_SeekGt );
66978           if( pIn3->r < (double)u.ba.iKey ) u.ba.iKey--;
66979         }
66980       }
66981       rc = sqlite3BtreeMovetoUnpacked(u.ba.pC->pCursor, 0, (u64)u.ba.iKey, 0, &u.ba.res);
66982       if( rc!=SQLITE_OK ){
66983         goto abort_due_to_error;
66984       }
66985       if( u.ba.res==0 ){
66986         u.ba.pC->rowidIsValid = 1;
66987         u.ba.pC->lastRowid = u.ba.iKey;
66988       }
66989     }else{
66990       u.ba.nField = pOp->p4.i;
66991       assert( pOp->p4type==P4_INT32 );
66992       assert( u.ba.nField>0 );
66993       u.ba.r.pKeyInfo = u.ba.pC->pKeyInfo;
66994       u.ba.r.nField = (u16)u.ba.nField;
66995 
66996       /* The next line of code computes as follows, only faster:
66997       **   if( u.ba.oc==OP_SeekGt || u.ba.oc==OP_SeekLe ){
66998       **     u.ba.r.flags = UNPACKED_INCRKEY;
66999       **   }else{
67000       **     u.ba.r.flags = 0;
67001       **   }
67002       */
67003       u.ba.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.ba.oc - OP_SeekLt)));
67004       assert( u.ba.oc!=OP_SeekGt || u.ba.r.flags==UNPACKED_INCRKEY );
67005       assert( u.ba.oc!=OP_SeekLe || u.ba.r.flags==UNPACKED_INCRKEY );
67006       assert( u.ba.oc!=OP_SeekGe || u.ba.r.flags==0 );
67007       assert( u.ba.oc!=OP_SeekLt || u.ba.r.flags==0 );
67008 
67009       u.ba.r.aMem = &aMem[pOp->p3];
67010 #ifdef SQLITE_DEBUG
67011       { int i; for(i=0; i<u.ba.r.nField; i++) assert( memIsValid(&u.ba.r.aMem[i]) ); }
67012 #endif
67013       ExpandBlob(u.ba.r.aMem);
67014       rc = sqlite3BtreeMovetoUnpacked(u.ba.pC->pCursor, &u.ba.r, 0, 0, &u.ba.res);
67015       if( rc!=SQLITE_OK ){
67016         goto abort_due_to_error;
67017       }
67018       u.ba.pC->rowidIsValid = 0;
67019     }
67020     u.ba.pC->deferredMoveto = 0;
67021     u.ba.pC->cacheStatus = CACHE_STALE;
67022 #ifdef SQLITE_TEST
67023     sqlite3_search_count++;
67024 #endif
67025     if( u.ba.oc>=OP_SeekGe ){  assert( u.ba.oc==OP_SeekGe || u.ba.oc==OP_SeekGt );
67026       if( u.ba.res<0 || (u.ba.res==0 && u.ba.oc==OP_SeekGt) ){
67027         rc = sqlite3BtreeNext(u.ba.pC->pCursor, &u.ba.res);
67028         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67029         u.ba.pC->rowidIsValid = 0;
67030       }else{
67031         u.ba.res = 0;
67032       }
67033     }else{
67034       assert( u.ba.oc==OP_SeekLt || u.ba.oc==OP_SeekLe );
67035       if( u.ba.res>0 || (u.ba.res==0 && u.ba.oc==OP_SeekLt) ){
67036         rc = sqlite3BtreePrevious(u.ba.pC->pCursor, &u.ba.res);
67037         if( rc!=SQLITE_OK ) goto abort_due_to_error;
67038         u.ba.pC->rowidIsValid = 0;
67039       }else{
67040         /* u.ba.res might be negative because the table is empty.  Check to
67041         ** see if this is the case.
67042         */
67043         u.ba.res = sqlite3BtreeEof(u.ba.pC->pCursor);
67044       }
67045     }
67046     assert( pOp->p2>0 );
67047     if( u.ba.res ){
67048       pc = pOp->p2 - 1;
67049     }
67050   }else{
67051     /* This happens when attempting to open the sqlite3_master table
67052     ** for read access returns SQLITE_EMPTY. In this case always
67053     ** take the jump (since there are no records in the table).
67054     */
67055     pc = pOp->p2 - 1;
67056   }
67057   break;
67058 }
67059 
67060 /* Opcode: Seek P1 P2 * * *
67061 **
67062 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
67063 ** for P1 to move so that it points to the rowid given by P2.
67064 **
67065 ** This is actually a deferred seek.  Nothing actually happens until
67066 ** the cursor is used to read a record.  That way, if no reads
67067 ** occur, no unnecessary I/O happens.
67068 */
67069 case OP_Seek: {    /* in2 */
67070 #if 0  /* local variables moved into u.bb */
67071   VdbeCursor *pC;
67072 #endif /* local variables moved into u.bb */
67073 
67074   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67075   u.bb.pC = p->apCsr[pOp->p1];
67076   assert( u.bb.pC!=0 );
67077   if( ALWAYS(u.bb.pC->pCursor!=0) ){
67078     assert( u.bb.pC->isTable );
67079     u.bb.pC->nullRow = 0;
67080     pIn2 = &aMem[pOp->p2];
67081     u.bb.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
67082     u.bb.pC->rowidIsValid = 0;
67083     u.bb.pC->deferredMoveto = 1;
67084   }
67085   break;
67086 }
67087 
67088 
67089 /* Opcode: Found P1 P2 P3 P4 *
67090 **
67091 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67092 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67093 ** record.
67094 **
67095 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67096 ** is a prefix of any entry in P1 then a jump is made to P2 and
67097 ** P1 is left pointing at the matching entry.
67098 */
67099 /* Opcode: NotFound P1 P2 P3 P4 *
67100 **
67101 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
67102 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
67103 ** record.
67104 **
67105 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
67106 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
67107 ** does contain an entry whose prefix matches the P3/P4 record then control
67108 ** falls through to the next instruction and P1 is left pointing at the
67109 ** matching entry.
67110 **
67111 ** See also: Found, NotExists, IsUnique
67112 */
67113 case OP_NotFound:       /* jump, in3 */
67114 case OP_Found: {        /* jump, in3 */
67115 #if 0  /* local variables moved into u.bc */
67116   int alreadyExists;
67117   VdbeCursor *pC;
67118   int res;
67119   char *pFree;
67120   UnpackedRecord *pIdxKey;
67121   UnpackedRecord r;
67122   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
67123 #endif /* local variables moved into u.bc */
67124 
67125 #ifdef SQLITE_TEST
67126   sqlite3_found_count++;
67127 #endif
67128 
67129   u.bc.alreadyExists = 0;
67130   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67131   assert( pOp->p4type==P4_INT32 );
67132   u.bc.pC = p->apCsr[pOp->p1];
67133   assert( u.bc.pC!=0 );
67134   pIn3 = &aMem[pOp->p3];
67135   if( ALWAYS(u.bc.pC->pCursor!=0) ){
67136 
67137     assert( u.bc.pC->isTable==0 );
67138     if( pOp->p4.i>0 ){
67139       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
67140       u.bc.r.nField = (u16)pOp->p4.i;
67141       u.bc.r.aMem = pIn3;
67142 #ifdef SQLITE_DEBUG
67143       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
67144 #endif
67145       u.bc.r.flags = UNPACKED_PREFIX_MATCH;
67146       u.bc.pIdxKey = &u.bc.r;
67147     }else{
67148       u.bc.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
67149           u.bc.pC->pKeyInfo, u.bc.aTempRec, sizeof(u.bc.aTempRec), &u.bc.pFree
67150       );
67151       if( u.bc.pIdxKey==0 ) goto no_mem;
67152       assert( pIn3->flags & MEM_Blob );
67153       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
67154       sqlite3VdbeRecordUnpack(u.bc.pC->pKeyInfo, pIn3->n, pIn3->z, u.bc.pIdxKey);
67155       u.bc.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
67156     }
67157     rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, u.bc.pIdxKey, 0, 0, &u.bc.res);
67158     if( pOp->p4.i==0 ){
67159       sqlite3DbFree(db, u.bc.pFree);
67160     }
67161     if( rc!=SQLITE_OK ){
67162       break;
67163     }
67164     u.bc.alreadyExists = (u.bc.res==0);
67165     u.bc.pC->deferredMoveto = 0;
67166     u.bc.pC->cacheStatus = CACHE_STALE;
67167   }
67168   if( pOp->opcode==OP_Found ){
67169     if( u.bc.alreadyExists ) pc = pOp->p2 - 1;
67170   }else{
67171     if( !u.bc.alreadyExists ) pc = pOp->p2 - 1;
67172   }
67173   break;
67174 }
67175 
67176 /* Opcode: IsUnique P1 P2 P3 P4 *
67177 **
67178 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
67179 ** no data and where the key are records generated by OP_MakeRecord with
67180 ** the list field being the integer ROWID of the entry that the index
67181 ** entry refers to.
67182 **
67183 ** The P3 register contains an integer record number. Call this record
67184 ** number R. Register P4 is the first in a set of N contiguous registers
67185 ** that make up an unpacked index key that can be used with cursor P1.
67186 ** The value of N can be inferred from the cursor. N includes the rowid
67187 ** value appended to the end of the index record. This rowid value may
67188 ** or may not be the same as R.
67189 **
67190 ** If any of the N registers beginning with register P4 contains a NULL
67191 ** value, jump immediately to P2.
67192 **
67193 ** Otherwise, this instruction checks if cursor P1 contains an entry
67194 ** where the first (N-1) fields match but the rowid value at the end
67195 ** of the index entry is not R. If there is no such entry, control jumps
67196 ** to instruction P2. Otherwise, the rowid of the conflicting index
67197 ** entry is copied to register P3 and control falls through to the next
67198 ** instruction.
67199 **
67200 ** See also: NotFound, NotExists, Found
67201 */
67202 case OP_IsUnique: {        /* jump, in3 */
67203 #if 0  /* local variables moved into u.bd */
67204   u16 ii;
67205   VdbeCursor *pCx;
67206   BtCursor *pCrsr;
67207   u16 nField;
67208   Mem *aMx;
67209   UnpackedRecord r;                  /* B-Tree index search key */
67210   i64 R;                             /* Rowid stored in register P3 */
67211 #endif /* local variables moved into u.bd */
67212 
67213   pIn3 = &aMem[pOp->p3];
67214   u.bd.aMx = &aMem[pOp->p4.i];
67215   /* Assert that the values of parameters P1 and P4 are in range. */
67216   assert( pOp->p4type==P4_INT32 );
67217   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
67218   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67219 
67220   /* Find the index cursor. */
67221   u.bd.pCx = p->apCsr[pOp->p1];
67222   assert( u.bd.pCx->deferredMoveto==0 );
67223   u.bd.pCx->seekResult = 0;
67224   u.bd.pCx->cacheStatus = CACHE_STALE;
67225   u.bd.pCrsr = u.bd.pCx->pCursor;
67226 
67227   /* If any of the values are NULL, take the jump. */
67228   u.bd.nField = u.bd.pCx->pKeyInfo->nField;
67229   for(u.bd.ii=0; u.bd.ii<u.bd.nField; u.bd.ii++){
67230     if( u.bd.aMx[u.bd.ii].flags & MEM_Null ){
67231       pc = pOp->p2 - 1;
67232       u.bd.pCrsr = 0;
67233       break;
67234     }
67235   }
67236   assert( (u.bd.aMx[u.bd.nField].flags & MEM_Null)==0 );
67237 
67238   if( u.bd.pCrsr!=0 ){
67239     /* Populate the index search key. */
67240     u.bd.r.pKeyInfo = u.bd.pCx->pKeyInfo;
67241     u.bd.r.nField = u.bd.nField + 1;
67242     u.bd.r.flags = UNPACKED_PREFIX_SEARCH;
67243     u.bd.r.aMem = u.bd.aMx;
67244 #ifdef SQLITE_DEBUG
67245     { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
67246 #endif
67247 
67248     /* Extract the value of u.bd.R from register P3. */
67249     sqlite3VdbeMemIntegerify(pIn3);
67250     u.bd.R = pIn3->u.i;
67251 
67252     /* Search the B-Tree index. If no conflicting record is found, jump
67253     ** to P2. Otherwise, copy the rowid of the conflicting record to
67254     ** register P3 and fall through to the next instruction.  */
67255     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, &u.bd.r, 0, 0, &u.bd.pCx->seekResult);
67256     if( (u.bd.r.flags & UNPACKED_PREFIX_SEARCH) || u.bd.r.rowid==u.bd.R ){
67257       pc = pOp->p2 - 1;
67258     }else{
67259       pIn3->u.i = u.bd.r.rowid;
67260     }
67261   }
67262   break;
67263 }
67264 
67265 /* Opcode: NotExists P1 P2 P3 * *
67266 **
67267 ** Use the content of register P3 as an integer key.  If a record
67268 ** with that key does not exist in table of P1, then jump to P2.
67269 ** If the record does exist, then fall through.  The cursor is left
67270 ** pointing to the record if it exists.
67271 **
67272 ** The difference between this operation and NotFound is that this
67273 ** operation assumes the key is an integer and that P1 is a table whereas
67274 ** NotFound assumes key is a blob constructed from MakeRecord and
67275 ** P1 is an index.
67276 **
67277 ** See also: Found, NotFound, IsUnique
67278 */
67279 case OP_NotExists: {        /* jump, in3 */
67280 #if 0  /* local variables moved into u.be */
67281   VdbeCursor *pC;
67282   BtCursor *pCrsr;
67283   int res;
67284   u64 iKey;
67285 #endif /* local variables moved into u.be */
67286 
67287   pIn3 = &aMem[pOp->p3];
67288   assert( pIn3->flags & MEM_Int );
67289   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67290   u.be.pC = p->apCsr[pOp->p1];
67291   assert( u.be.pC!=0 );
67292   assert( u.be.pC->isTable );
67293   assert( u.be.pC->pseudoTableReg==0 );
67294   u.be.pCrsr = u.be.pC->pCursor;
67295   if( ALWAYS(u.be.pCrsr!=0) ){
67296     u.be.res = 0;
67297     u.be.iKey = pIn3->u.i;
67298     rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, 0, u.be.iKey, 0, &u.be.res);
67299     u.be.pC->lastRowid = pIn3->u.i;
67300     u.be.pC->rowidIsValid = u.be.res==0 ?1:0;
67301     u.be.pC->nullRow = 0;
67302     u.be.pC->cacheStatus = CACHE_STALE;
67303     u.be.pC->deferredMoveto = 0;
67304     if( u.be.res!=0 ){
67305       pc = pOp->p2 - 1;
67306       assert( u.be.pC->rowidIsValid==0 );
67307     }
67308     u.be.pC->seekResult = u.be.res;
67309   }else{
67310     /* This happens when an attempt to open a read cursor on the
67311     ** sqlite_master table returns SQLITE_EMPTY.
67312     */
67313     pc = pOp->p2 - 1;
67314     assert( u.be.pC->rowidIsValid==0 );
67315     u.be.pC->seekResult = 0;
67316   }
67317   break;
67318 }
67319 
67320 /* Opcode: Sequence P1 P2 * * *
67321 **
67322 ** Find the next available sequence number for cursor P1.
67323 ** Write the sequence number into register P2.
67324 ** The sequence number on the cursor is incremented after this
67325 ** instruction.
67326 */
67327 case OP_Sequence: {           /* out2-prerelease */
67328   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67329   assert( p->apCsr[pOp->p1]!=0 );
67330   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
67331   break;
67332 }
67333 
67334 
67335 /* Opcode: NewRowid P1 P2 P3 * *
67336 **
67337 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
67338 ** The record number is not previously used as a key in the database
67339 ** table that cursor P1 points to.  The new record number is written
67340 ** written to register P2.
67341 **
67342 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
67343 ** the largest previously generated record number. No new record numbers are
67344 ** allowed to be less than this value. When this value reaches its maximum,
67345 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
67346 ** generated record number. This P3 mechanism is used to help implement the
67347 ** AUTOINCREMENT feature.
67348 */
67349 case OP_NewRowid: {           /* out2-prerelease */
67350 #if 0  /* local variables moved into u.bf */
67351   i64 v;                 /* The new rowid */
67352   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
67353   int res;               /* Result of an sqlite3BtreeLast() */
67354   int cnt;               /* Counter to limit the number of searches */
67355   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
67356   VdbeFrame *pFrame;     /* Root frame of VDBE */
67357 #endif /* local variables moved into u.bf */
67358 
67359   u.bf.v = 0;
67360   u.bf.res = 0;
67361   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67362   u.bf.pC = p->apCsr[pOp->p1];
67363   assert( u.bf.pC!=0 );
67364   if( NEVER(u.bf.pC->pCursor==0) ){
67365     /* The zero initialization above is all that is needed */
67366   }else{
67367     /* The next rowid or record number (different terms for the same
67368     ** thing) is obtained in a two-step algorithm.
67369     **
67370     ** First we attempt to find the largest existing rowid and add one
67371     ** to that.  But if the largest existing rowid is already the maximum
67372     ** positive integer, we have to fall through to the second
67373     ** probabilistic algorithm
67374     **
67375     ** The second algorithm is to select a rowid at random and see if
67376     ** it already exists in the table.  If it does not exist, we have
67377     ** succeeded.  If the random rowid does exist, we select a new one
67378     ** and try again, up to 100 times.
67379     */
67380     assert( u.bf.pC->isTable );
67381 
67382 #ifdef SQLITE_32BIT_ROWID
67383 #   define MAX_ROWID 0x7fffffff
67384 #else
67385     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
67386     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
67387     ** to provide the constant while making all compilers happy.
67388     */
67389 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
67390 #endif
67391 
67392     if( !u.bf.pC->useRandomRowid ){
67393       u.bf.v = sqlite3BtreeGetCachedRowid(u.bf.pC->pCursor);
67394       if( u.bf.v==0 ){
67395         rc = sqlite3BtreeLast(u.bf.pC->pCursor, &u.bf.res);
67396         if( rc!=SQLITE_OK ){
67397           goto abort_due_to_error;
67398         }
67399         if( u.bf.res ){
67400           u.bf.v = 1;   /* IMP: R-61914-48074 */
67401         }else{
67402           assert( sqlite3BtreeCursorIsValid(u.bf.pC->pCursor) );
67403           rc = sqlite3BtreeKeySize(u.bf.pC->pCursor, &u.bf.v);
67404           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
67405           if( u.bf.v==MAX_ROWID ){
67406             u.bf.pC->useRandomRowid = 1;
67407           }else{
67408             u.bf.v++;   /* IMP: R-29538-34987 */
67409           }
67410         }
67411       }
67412 
67413 #ifndef SQLITE_OMIT_AUTOINCREMENT
67414       if( pOp->p3 ){
67415         /* Assert that P3 is a valid memory cell. */
67416         assert( pOp->p3>0 );
67417         if( p->pFrame ){
67418           for(u.bf.pFrame=p->pFrame; u.bf.pFrame->pParent; u.bf.pFrame=u.bf.pFrame->pParent);
67419           /* Assert that P3 is a valid memory cell. */
67420           assert( pOp->p3<=u.bf.pFrame->nMem );
67421           u.bf.pMem = &u.bf.pFrame->aMem[pOp->p3];
67422         }else{
67423           /* Assert that P3 is a valid memory cell. */
67424           assert( pOp->p3<=p->nMem );
67425           u.bf.pMem = &aMem[pOp->p3];
67426           memAboutToChange(p, u.bf.pMem);
67427         }
67428         assert( memIsValid(u.bf.pMem) );
67429 
67430         REGISTER_TRACE(pOp->p3, u.bf.pMem);
67431         sqlite3VdbeMemIntegerify(u.bf.pMem);
67432         assert( (u.bf.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
67433         if( u.bf.pMem->u.i==MAX_ROWID || u.bf.pC->useRandomRowid ){
67434           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
67435           goto abort_due_to_error;
67436         }
67437         if( u.bf.v<u.bf.pMem->u.i+1 ){
67438           u.bf.v = u.bf.pMem->u.i + 1;
67439         }
67440         u.bf.pMem->u.i = u.bf.v;
67441       }
67442 #endif
67443 
67444       sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, u.bf.v<MAX_ROWID ? u.bf.v+1 : 0);
67445     }
67446     if( u.bf.pC->useRandomRowid ){
67447       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
67448       ** largest possible integer (9223372036854775807) then the database
67449       ** engine starts picking positive candidate ROWIDs at random until
67450       ** it finds one that is not previously used. */
67451       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
67452                              ** an AUTOINCREMENT table. */
67453       /* on the first attempt, simply do one more than previous */
67454       u.bf.v = lastRowid;
67455       u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67456       u.bf.v++; /* ensure non-zero */
67457       u.bf.cnt = 0;
67458       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bf.pC->pCursor, 0, (u64)u.bf.v,
67459                                                  0, &u.bf.res))==SQLITE_OK)
67460             && (u.bf.res==0)
67461             && (++u.bf.cnt<100)){
67462         /* collision - try another random rowid */
67463         sqlite3_randomness(sizeof(u.bf.v), &u.bf.v);
67464         if( u.bf.cnt<5 ){
67465           /* try "small" random rowids for the initial attempts */
67466           u.bf.v &= 0xffffff;
67467         }else{
67468           u.bf.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
67469         }
67470         u.bf.v++; /* ensure non-zero */
67471       }
67472       if( rc==SQLITE_OK && u.bf.res==0 ){
67473         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
67474         goto abort_due_to_error;
67475       }
67476       assert( u.bf.v>0 );  /* EV: R-40812-03570 */
67477     }
67478     u.bf.pC->rowidIsValid = 0;
67479     u.bf.pC->deferredMoveto = 0;
67480     u.bf.pC->cacheStatus = CACHE_STALE;
67481   }
67482   pOut->u.i = u.bf.v;
67483   break;
67484 }
67485 
67486 /* Opcode: Insert P1 P2 P3 P4 P5
67487 **
67488 ** Write an entry into the table of cursor P1.  A new entry is
67489 ** created if it doesn't already exist or the data for an existing
67490 ** entry is overwritten.  The data is the value MEM_Blob stored in register
67491 ** number P2. The key is stored in register P3. The key must
67492 ** be a MEM_Int.
67493 **
67494 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
67495 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
67496 ** then rowid is stored for subsequent return by the
67497 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
67498 **
67499 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
67500 ** the last seek operation (OP_NotExists) was a success, then this
67501 ** operation will not attempt to find the appropriate row before doing
67502 ** the insert but will instead overwrite the row that the cursor is
67503 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
67504 ** has already positioned the cursor correctly.  This is an optimization
67505 ** that boosts performance by avoiding redundant seeks.
67506 **
67507 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
67508 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
67509 ** is part of an INSERT operation.  The difference is only important to
67510 ** the update hook.
67511 **
67512 ** Parameter P4 may point to a string containing the table-name, or
67513 ** may be NULL. If it is not NULL, then the update-hook
67514 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
67515 **
67516 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
67517 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
67518 ** and register P2 becomes ephemeral.  If the cursor is changed, the
67519 ** value of register P2 will then change.  Make sure this does not
67520 ** cause any problems.)
67521 **
67522 ** This instruction only works on tables.  The equivalent instruction
67523 ** for indices is OP_IdxInsert.
67524 */
67525 /* Opcode: InsertInt P1 P2 P3 P4 P5
67526 **
67527 ** This works exactly like OP_Insert except that the key is the
67528 ** integer value P3, not the value of the integer stored in register P3.
67529 */
67530 case OP_Insert:
67531 case OP_InsertInt: {
67532 #if 0  /* local variables moved into u.bg */
67533   Mem *pData;       /* MEM cell holding data for the record to be inserted */
67534   Mem *pKey;        /* MEM cell holding key  for the record */
67535   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
67536   VdbeCursor *pC;   /* Cursor to table into which insert is written */
67537   int nZero;        /* Number of zero-bytes to append */
67538   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
67539   const char *zDb;  /* database name - used by the update hook */
67540   const char *zTbl; /* Table name - used by the opdate hook */
67541   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
67542 #endif /* local variables moved into u.bg */
67543 
67544   u.bg.pData = &aMem[pOp->p2];
67545   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67546   assert( memIsValid(u.bg.pData) );
67547   u.bg.pC = p->apCsr[pOp->p1];
67548   assert( u.bg.pC!=0 );
67549   assert( u.bg.pC->pCursor!=0 );
67550   assert( u.bg.pC->pseudoTableReg==0 );
67551   assert( u.bg.pC->isTable );
67552   REGISTER_TRACE(pOp->p2, u.bg.pData);
67553 
67554   if( pOp->opcode==OP_Insert ){
67555     u.bg.pKey = &aMem[pOp->p3];
67556     assert( u.bg.pKey->flags & MEM_Int );
67557     assert( memIsValid(u.bg.pKey) );
67558     REGISTER_TRACE(pOp->p3, u.bg.pKey);
67559     u.bg.iKey = u.bg.pKey->u.i;
67560   }else{
67561     assert( pOp->opcode==OP_InsertInt );
67562     u.bg.iKey = pOp->p3;
67563   }
67564 
67565   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
67566   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bg.iKey;
67567   if( u.bg.pData->flags & MEM_Null ){
67568     u.bg.pData->z = 0;
67569     u.bg.pData->n = 0;
67570   }else{
67571     assert( u.bg.pData->flags & (MEM_Blob|MEM_Str) );
67572   }
67573   u.bg.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bg.pC->seekResult : 0);
67574   if( u.bg.pData->flags & MEM_Zero ){
67575     u.bg.nZero = u.bg.pData->u.nZero;
67576   }else{
67577     u.bg.nZero = 0;
67578   }
67579   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
67580   rc = sqlite3BtreeInsert(u.bg.pC->pCursor, 0, u.bg.iKey,
67581                           u.bg.pData->z, u.bg.pData->n, u.bg.nZero,
67582                           pOp->p5 & OPFLAG_APPEND, u.bg.seekResult
67583   );
67584   u.bg.pC->rowidIsValid = 0;
67585   u.bg.pC->deferredMoveto = 0;
67586   u.bg.pC->cacheStatus = CACHE_STALE;
67587 
67588   /* Invoke the update-hook if required. */
67589   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67590     u.bg.zDb = db->aDb[u.bg.pC->iDb].zName;
67591     u.bg.zTbl = pOp->p4.z;
67592     u.bg.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
67593     assert( u.bg.pC->isTable );
67594     db->xUpdateCallback(db->pUpdateArg, u.bg.op, u.bg.zDb, u.bg.zTbl, u.bg.iKey);
67595     assert( u.bg.pC->iDb>=0 );
67596   }
67597   break;
67598 }
67599 
67600 /* Opcode: Delete P1 P2 * P4 *
67601 **
67602 ** Delete the record at which the P1 cursor is currently pointing.
67603 **
67604 ** The cursor will be left pointing at either the next or the previous
67605 ** record in the table. If it is left pointing at the next record, then
67606 ** the next Next instruction will be a no-op.  Hence it is OK to delete
67607 ** a record from within an Next loop.
67608 **
67609 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
67610 ** incremented (otherwise not).
67611 **
67612 ** P1 must not be pseudo-table.  It has to be a real table with
67613 ** multiple rows.
67614 **
67615 ** If P4 is not NULL, then it is the name of the table that P1 is
67616 ** pointing to.  The update hook will be invoked, if it exists.
67617 ** If P4 is not NULL then the P1 cursor must have been positioned
67618 ** using OP_NotFound prior to invoking this opcode.
67619 */
67620 case OP_Delete: {
67621 #if 0  /* local variables moved into u.bh */
67622   i64 iKey;
67623   VdbeCursor *pC;
67624 #endif /* local variables moved into u.bh */
67625 
67626   u.bh.iKey = 0;
67627   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67628   u.bh.pC = p->apCsr[pOp->p1];
67629   assert( u.bh.pC!=0 );
67630   assert( u.bh.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
67631 
67632   /* If the update-hook will be invoked, set u.bh.iKey to the rowid of the
67633   ** row being deleted.
67634   */
67635   if( db->xUpdateCallback && pOp->p4.z ){
67636     assert( u.bh.pC->isTable );
67637     assert( u.bh.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
67638     u.bh.iKey = u.bh.pC->lastRowid;
67639   }
67640 
67641   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
67642   ** OP_Column on the same table without any intervening operations that
67643   ** might move or invalidate the cursor.  Hence cursor u.bh.pC is always pointing
67644   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
67645   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
67646   ** to guard against future changes to the code generator.
67647   **/
67648   assert( u.bh.pC->deferredMoveto==0 );
67649   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
67650   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67651 
67652   sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
67653   rc = sqlite3BtreeDelete(u.bh.pC->pCursor);
67654   u.bh.pC->cacheStatus = CACHE_STALE;
67655 
67656   /* Invoke the update-hook if required. */
67657   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
67658     const char *zDb = db->aDb[u.bh.pC->iDb].zName;
67659     const char *zTbl = pOp->p4.z;
67660     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bh.iKey);
67661     assert( u.bh.pC->iDb>=0 );
67662   }
67663   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
67664   break;
67665 }
67666 /* Opcode: ResetCount * * * * *
67667 **
67668 ** The value of the change counter is copied to the database handle
67669 ** change counter (returned by subsequent calls to sqlite3_changes()).
67670 ** Then the VMs internal change counter resets to 0.
67671 ** This is used by trigger programs.
67672 */
67673 case OP_ResetCount: {
67674   sqlite3VdbeSetChanges(db, p->nChange);
67675   p->nChange = 0;
67676   break;
67677 }
67678 
67679 /* Opcode: SorterCompare P1 P2 P3
67680 **
67681 ** P1 is a sorter cursor. This instruction compares the record blob in
67682 ** register P3 with the entry that the sorter cursor currently points to.
67683 ** If, excluding the rowid fields at the end, the two records are a match,
67684 ** fall through to the next instruction. Otherwise, jump to instruction P2.
67685 */
67686 case OP_SorterCompare: {
67687 #if 0  /* local variables moved into u.bi */
67688   VdbeCursor *pC;
67689   int res;
67690 #endif /* local variables moved into u.bi */
67691 
67692   u.bi.pC = p->apCsr[pOp->p1];
67693   assert( isSorter(u.bi.pC) );
67694   pIn3 = &aMem[pOp->p3];
67695   rc = sqlite3VdbeSorterCompare(u.bi.pC, pIn3, &u.bi.res);
67696   if( u.bi.res ){
67697     pc = pOp->p2-1;
67698   }
67699   break;
67700 };
67701 
67702 /* Opcode: SorterData P1 P2 * * *
67703 **
67704 ** Write into register P2 the current sorter data for sorter cursor P1.
67705 */
67706 case OP_SorterData: {
67707 #if 0  /* local variables moved into u.bj */
67708   VdbeCursor *pC;
67709 #endif /* local variables moved into u.bj */
67710 #ifndef SQLITE_OMIT_MERGE_SORT
67711   pOut = &aMem[pOp->p2];
67712   u.bj.pC = p->apCsr[pOp->p1];
67713   assert( u.bj.pC->isSorter );
67714   rc = sqlite3VdbeSorterRowkey(u.bj.pC, pOut);
67715 #else
67716   pOp->opcode = OP_RowKey;
67717   pc--;
67718 #endif
67719   break;
67720 }
67721 
67722 /* Opcode: RowData P1 P2 * * *
67723 **
67724 ** Write into register P2 the complete row data for cursor P1.
67725 ** There is no interpretation of the data.
67726 ** It is just copied onto the P2 register exactly as
67727 ** it is found in the database file.
67728 **
67729 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67730 ** of a real table, not a pseudo-table.
67731 */
67732 /* Opcode: RowKey P1 P2 * * *
67733 **
67734 ** Write into register P2 the complete row key for cursor P1.
67735 ** There is no interpretation of the data.
67736 ** The key is copied onto the P3 register exactly as
67737 ** it is found in the database file.
67738 **
67739 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
67740 ** of a real table, not a pseudo-table.
67741 */
67742 case OP_RowKey:
67743 case OP_RowData: {
67744 #if 0  /* local variables moved into u.bk */
67745   VdbeCursor *pC;
67746   BtCursor *pCrsr;
67747   u32 n;
67748   i64 n64;
67749 #endif /* local variables moved into u.bk */
67750 
67751   pOut = &aMem[pOp->p2];
67752   memAboutToChange(p, pOut);
67753 
67754   /* Note that RowKey and RowData are really exactly the same instruction */
67755   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67756   u.bk.pC = p->apCsr[pOp->p1];
67757   assert( u.bk.pC->isSorter==0 );
67758   assert( u.bk.pC->isTable || pOp->opcode!=OP_RowData );
67759   assert( u.bk.pC->isIndex || pOp->opcode==OP_RowData );
67760   assert( u.bk.pC!=0 );
67761   assert( u.bk.pC->nullRow==0 );
67762   assert( u.bk.pC->pseudoTableReg==0 );
67763   assert( !u.bk.pC->isSorter );
67764   assert( u.bk.pC->pCursor!=0 );
67765   u.bk.pCrsr = u.bk.pC->pCursor;
67766   assert( sqlite3BtreeCursorIsValid(u.bk.pCrsr) );
67767 
67768   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
67769   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
67770   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
67771   ** a no-op and can never fail.  But we leave it in place as a safety.
67772   */
67773   assert( u.bk.pC->deferredMoveto==0 );
67774   rc = sqlite3VdbeCursorMoveto(u.bk.pC);
67775   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
67776 
67777   if( u.bk.pC->isIndex ){
67778     assert( !u.bk.pC->isTable );
67779     rc = sqlite3BtreeKeySize(u.bk.pCrsr, &u.bk.n64);
67780     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
67781     if( u.bk.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67782       goto too_big;
67783     }
67784     u.bk.n = (u32)u.bk.n64;
67785   }else{
67786     rc = sqlite3BtreeDataSize(u.bk.pCrsr, &u.bk.n);
67787     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
67788     if( u.bk.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67789       goto too_big;
67790     }
67791   }
67792   if( sqlite3VdbeMemGrow(pOut, u.bk.n, 0) ){
67793     goto no_mem;
67794   }
67795   pOut->n = u.bk.n;
67796   MemSetTypeFlag(pOut, MEM_Blob);
67797   if( u.bk.pC->isIndex ){
67798     rc = sqlite3BtreeKey(u.bk.pCrsr, 0, u.bk.n, pOut->z);
67799   }else{
67800     rc = sqlite3BtreeData(u.bk.pCrsr, 0, u.bk.n, pOut->z);
67801   }
67802   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
67803   UPDATE_MAX_BLOBSIZE(pOut);
67804   break;
67805 }
67806 
67807 /* Opcode: Rowid P1 P2 * * *
67808 **
67809 ** Store in register P2 an integer which is the key of the table entry that
67810 ** P1 is currently point to.
67811 **
67812 ** P1 can be either an ordinary table or a virtual table.  There used to
67813 ** be a separate OP_VRowid opcode for use with virtual tables, but this
67814 ** one opcode now works for both table types.
67815 */
67816 case OP_Rowid: {                 /* out2-prerelease */
67817 #if 0  /* local variables moved into u.bl */
67818   VdbeCursor *pC;
67819   i64 v;
67820   sqlite3_vtab *pVtab;
67821   const sqlite3_module *pModule;
67822 #endif /* local variables moved into u.bl */
67823 
67824   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67825   u.bl.pC = p->apCsr[pOp->p1];
67826   assert( u.bl.pC!=0 );
67827   assert( u.bl.pC->pseudoTableReg==0 );
67828   if( u.bl.pC->nullRow ){
67829     pOut->flags = MEM_Null;
67830     break;
67831   }else if( u.bl.pC->deferredMoveto ){
67832     u.bl.v = u.bl.pC->movetoTarget;
67833 #ifndef SQLITE_OMIT_VIRTUALTABLE
67834   }else if( u.bl.pC->pVtabCursor ){
67835     u.bl.pVtab = u.bl.pC->pVtabCursor->pVtab;
67836     u.bl.pModule = u.bl.pVtab->pModule;
67837     assert( u.bl.pModule->xRowid );
67838     rc = u.bl.pModule->xRowid(u.bl.pC->pVtabCursor, &u.bl.v);
67839     importVtabErrMsg(p, u.bl.pVtab);
67840 #endif /* SQLITE_OMIT_VIRTUALTABLE */
67841   }else{
67842     assert( u.bl.pC->pCursor!=0 );
67843     rc = sqlite3VdbeCursorMoveto(u.bl.pC);
67844     if( rc ) goto abort_due_to_error;
67845     if( u.bl.pC->rowidIsValid ){
67846       u.bl.v = u.bl.pC->lastRowid;
67847     }else{
67848       rc = sqlite3BtreeKeySize(u.bl.pC->pCursor, &u.bl.v);
67849       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
67850     }
67851   }
67852   pOut->u.i = u.bl.v;
67853   break;
67854 }
67855 
67856 /* Opcode: NullRow P1 * * * *
67857 **
67858 ** Move the cursor P1 to a null row.  Any OP_Column operations
67859 ** that occur while the cursor is on the null row will always
67860 ** write a NULL.
67861 */
67862 case OP_NullRow: {
67863 #if 0  /* local variables moved into u.bm */
67864   VdbeCursor *pC;
67865 #endif /* local variables moved into u.bm */
67866 
67867   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67868   u.bm.pC = p->apCsr[pOp->p1];
67869   assert( u.bm.pC!=0 );
67870   u.bm.pC->nullRow = 1;
67871   u.bm.pC->rowidIsValid = 0;
67872   assert( u.bm.pC->pCursor || u.bm.pC->pVtabCursor );
67873   if( u.bm.pC->pCursor ){
67874     sqlite3BtreeClearCursor(u.bm.pC->pCursor);
67875   }
67876   break;
67877 }
67878 
67879 /* Opcode: Last P1 P2 * * *
67880 **
67881 ** The next use of the Rowid or Column or Next instruction for P1
67882 ** will refer to the last entry in the database table or index.
67883 ** If the table or index is empty and P2>0, then jump immediately to P2.
67884 ** If P2 is 0 or if the table or index is not empty, fall through
67885 ** to the following instruction.
67886 */
67887 case OP_Last: {        /* jump */
67888 #if 0  /* local variables moved into u.bn */
67889   VdbeCursor *pC;
67890   BtCursor *pCrsr;
67891   int res;
67892 #endif /* local variables moved into u.bn */
67893 
67894   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67895   u.bn.pC = p->apCsr[pOp->p1];
67896   assert( u.bn.pC!=0 );
67897   u.bn.pCrsr = u.bn.pC->pCursor;
67898   if( NEVER(u.bn.pCrsr==0) ){
67899     u.bn.res = 1;
67900   }else{
67901     rc = sqlite3BtreeLast(u.bn.pCrsr, &u.bn.res);
67902   }
67903   u.bn.pC->nullRow = (u8)u.bn.res;
67904   u.bn.pC->deferredMoveto = 0;
67905   u.bn.pC->rowidIsValid = 0;
67906   u.bn.pC->cacheStatus = CACHE_STALE;
67907   if( pOp->p2>0 && u.bn.res ){
67908     pc = pOp->p2 - 1;
67909   }
67910   break;
67911 }
67912 
67913 
67914 /* Opcode: Sort P1 P2 * * *
67915 **
67916 ** This opcode does exactly the same thing as OP_Rewind except that
67917 ** it increments an undocumented global variable used for testing.
67918 **
67919 ** Sorting is accomplished by writing records into a sorting index,
67920 ** then rewinding that index and playing it back from beginning to
67921 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
67922 ** rewinding so that the global variable will be incremented and
67923 ** regression tests can determine whether or not the optimizer is
67924 ** correctly optimizing out sorts.
67925 */
67926 case OP_SorterSort:    /* jump */
67927 #ifdef SQLITE_OMIT_MERGE_SORT
67928   pOp->opcode = OP_Sort;
67929 #endif
67930 case OP_Sort: {        /* jump */
67931 #ifdef SQLITE_TEST
67932   sqlite3_sort_count++;
67933   sqlite3_search_count--;
67934 #endif
67935   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
67936   /* Fall through into OP_Rewind */
67937 }
67938 /* Opcode: Rewind P1 P2 * * *
67939 **
67940 ** The next use of the Rowid or Column or Next instruction for P1
67941 ** will refer to the first entry in the database table or index.
67942 ** If the table or index is empty and P2>0, then jump immediately to P2.
67943 ** If P2 is 0 or if the table or index is not empty, fall through
67944 ** to the following instruction.
67945 */
67946 case OP_Rewind: {        /* jump */
67947 #if 0  /* local variables moved into u.bo */
67948   VdbeCursor *pC;
67949   BtCursor *pCrsr;
67950   int res;
67951 #endif /* local variables moved into u.bo */
67952 
67953   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
67954   u.bo.pC = p->apCsr[pOp->p1];
67955   assert( u.bo.pC!=0 );
67956   assert( u.bo.pC->isSorter==(pOp->opcode==OP_SorterSort) );
67957   u.bo.res = 1;
67958   if( isSorter(u.bo.pC) ){
67959     rc = sqlite3VdbeSorterRewind(db, u.bo.pC, &u.bo.res);
67960   }else{
67961     u.bo.pCrsr = u.bo.pC->pCursor;
67962     assert( u.bo.pCrsr );
67963     rc = sqlite3BtreeFirst(u.bo.pCrsr, &u.bo.res);
67964     u.bo.pC->atFirst = u.bo.res==0 ?1:0;
67965     u.bo.pC->deferredMoveto = 0;
67966     u.bo.pC->cacheStatus = CACHE_STALE;
67967     u.bo.pC->rowidIsValid = 0;
67968   }
67969   u.bo.pC->nullRow = (u8)u.bo.res;
67970   assert( pOp->p2>0 && pOp->p2<p->nOp );
67971   if( u.bo.res ){
67972     pc = pOp->p2 - 1;
67973   }
67974   break;
67975 }
67976 
67977 /* Opcode: Next P1 P2 * P4 P5
67978 **
67979 ** Advance cursor P1 so that it points to the next key/data pair in its
67980 ** table or index.  If there are no more key/value pairs then fall through
67981 ** to the following instruction.  But if the cursor advance was successful,
67982 ** jump immediately to P2.
67983 **
67984 ** The P1 cursor must be for a real table, not a pseudo-table.
67985 **
67986 ** P4 is always of type P4_ADVANCE. The function pointer points to
67987 ** sqlite3BtreeNext().
67988 **
67989 ** If P5 is positive and the jump is taken, then event counter
67990 ** number P5-1 in the prepared statement is incremented.
67991 **
67992 ** See also: Prev
67993 */
67994 /* Opcode: Prev P1 P2 * * P5
67995 **
67996 ** Back up cursor P1 so that it points to the previous key/data pair in its
67997 ** table or index.  If there is no previous key/value pairs then fall through
67998 ** to the following instruction.  But if the cursor backup was successful,
67999 ** jump immediately to P2.
68000 **
68001 ** The P1 cursor must be for a real table, not a pseudo-table.
68002 **
68003 ** P4 is always of type P4_ADVANCE. The function pointer points to
68004 ** sqlite3BtreePrevious().
68005 **
68006 ** If P5 is positive and the jump is taken, then event counter
68007 ** number P5-1 in the prepared statement is incremented.
68008 */
68009 case OP_SorterNext:    /* jump */
68010 #ifdef SQLITE_OMIT_MERGE_SORT
68011   pOp->opcode = OP_Next;
68012 #endif
68013 case OP_Prev:          /* jump */
68014 case OP_Next: {        /* jump */
68015 #if 0  /* local variables moved into u.bp */
68016   VdbeCursor *pC;
68017   int res;
68018 #endif /* local variables moved into u.bp */
68019 
68020   CHECK_FOR_INTERRUPT;
68021   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68022   assert( pOp->p5<=ArraySize(p->aCounter) );
68023   u.bp.pC = p->apCsr[pOp->p1];
68024   if( u.bp.pC==0 ){
68025     break;  /* See ticket #2273 */
68026   }
68027   assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterNext) );
68028   if( isSorter(u.bp.pC) ){
68029     assert( pOp->opcode==OP_SorterNext );
68030     rc = sqlite3VdbeSorterNext(db, u.bp.pC, &u.bp.res);
68031   }else{
68032     u.bp.res = 1;
68033     assert( u.bp.pC->deferredMoveto==0 );
68034     assert( u.bp.pC->pCursor );
68035     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
68036     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
68037     rc = pOp->p4.xAdvance(u.bp.pC->pCursor, &u.bp.res);
68038   }
68039   u.bp.pC->nullRow = (u8)u.bp.res;
68040   u.bp.pC->cacheStatus = CACHE_STALE;
68041   if( u.bp.res==0 ){
68042     pc = pOp->p2 - 1;
68043     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
68044 #ifdef SQLITE_TEST
68045     sqlite3_search_count++;
68046 #endif
68047   }
68048   u.bp.pC->rowidIsValid = 0;
68049   break;
68050 }
68051 
68052 /* Opcode: IdxInsert P1 P2 P3 * P5
68053 **
68054 ** Register P2 holds an SQL index key made using the
68055 ** MakeRecord instructions.  This opcode writes that key
68056 ** into the index P1.  Data for the entry is nil.
68057 **
68058 ** P3 is a flag that provides a hint to the b-tree layer that this
68059 ** insert is likely to be an append.
68060 **
68061 ** This instruction only works for indices.  The equivalent instruction
68062 ** for tables is OP_Insert.
68063 */
68064 case OP_SorterInsert:       /* in2 */
68065 #ifdef SQLITE_OMIT_MERGE_SORT
68066   pOp->opcode = OP_IdxInsert;
68067 #endif
68068 case OP_IdxInsert: {        /* in2 */
68069 #if 0  /* local variables moved into u.bq */
68070   VdbeCursor *pC;
68071   BtCursor *pCrsr;
68072   int nKey;
68073   const char *zKey;
68074 #endif /* local variables moved into u.bq */
68075 
68076   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68077   u.bq.pC = p->apCsr[pOp->p1];
68078   assert( u.bq.pC!=0 );
68079   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
68080   pIn2 = &aMem[pOp->p2];
68081   assert( pIn2->flags & MEM_Blob );
68082   u.bq.pCrsr = u.bq.pC->pCursor;
68083   if( ALWAYS(u.bq.pCrsr!=0) ){
68084     assert( u.bq.pC->isTable==0 );
68085     rc = ExpandBlob(pIn2);
68086     if( rc==SQLITE_OK ){
68087       if( isSorter(u.bq.pC) ){
68088         rc = sqlite3VdbeSorterWrite(db, u.bq.pC, pIn2);
68089       }else{
68090         u.bq.nKey = pIn2->n;
68091         u.bq.zKey = pIn2->z;
68092         rc = sqlite3BtreeInsert(u.bq.pCrsr, u.bq.zKey, u.bq.nKey, "", 0, 0, pOp->p3,
68093             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bq.pC->seekResult : 0)
68094             );
68095         assert( u.bq.pC->deferredMoveto==0 );
68096         u.bq.pC->cacheStatus = CACHE_STALE;
68097       }
68098     }
68099   }
68100   break;
68101 }
68102 
68103 /* Opcode: IdxDelete P1 P2 P3 * *
68104 **
68105 ** The content of P3 registers starting at register P2 form
68106 ** an unpacked index key. This opcode removes that entry from the
68107 ** index opened by cursor P1.
68108 */
68109 case OP_IdxDelete: {
68110 #if 0  /* local variables moved into u.br */
68111   VdbeCursor *pC;
68112   BtCursor *pCrsr;
68113   int res;
68114   UnpackedRecord r;
68115 #endif /* local variables moved into u.br */
68116 
68117   assert( pOp->p3>0 );
68118   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
68119   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68120   u.br.pC = p->apCsr[pOp->p1];
68121   assert( u.br.pC!=0 );
68122   u.br.pCrsr = u.br.pC->pCursor;
68123   if( ALWAYS(u.br.pCrsr!=0) ){
68124     u.br.r.pKeyInfo = u.br.pC->pKeyInfo;
68125     u.br.r.nField = (u16)pOp->p3;
68126     u.br.r.flags = 0;
68127     u.br.r.aMem = &aMem[pOp->p2];
68128 #ifdef SQLITE_DEBUG
68129     { int i; for(i=0; i<u.br.r.nField; i++) assert( memIsValid(&u.br.r.aMem[i]) ); }
68130 #endif
68131     rc = sqlite3BtreeMovetoUnpacked(u.br.pCrsr, &u.br.r, 0, 0, &u.br.res);
68132     if( rc==SQLITE_OK && u.br.res==0 ){
68133       rc = sqlite3BtreeDelete(u.br.pCrsr);
68134     }
68135     assert( u.br.pC->deferredMoveto==0 );
68136     u.br.pC->cacheStatus = CACHE_STALE;
68137   }
68138   break;
68139 }
68140 
68141 /* Opcode: IdxRowid P1 P2 * * *
68142 **
68143 ** Write into register P2 an integer which is the last entry in the record at
68144 ** the end of the index key pointed to by cursor P1.  This integer should be
68145 ** the rowid of the table entry to which this index entry points.
68146 **
68147 ** See also: Rowid, MakeRecord.
68148 */
68149 case OP_IdxRowid: {              /* out2-prerelease */
68150 #if 0  /* local variables moved into u.bs */
68151   BtCursor *pCrsr;
68152   VdbeCursor *pC;
68153   i64 rowid;
68154 #endif /* local variables moved into u.bs */
68155 
68156   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68157   u.bs.pC = p->apCsr[pOp->p1];
68158   assert( u.bs.pC!=0 );
68159   u.bs.pCrsr = u.bs.pC->pCursor;
68160   pOut->flags = MEM_Null;
68161   if( ALWAYS(u.bs.pCrsr!=0) ){
68162     rc = sqlite3VdbeCursorMoveto(u.bs.pC);
68163     if( NEVER(rc) ) goto abort_due_to_error;
68164     assert( u.bs.pC->deferredMoveto==0 );
68165     assert( u.bs.pC->isTable==0 );
68166     if( !u.bs.pC->nullRow ){
68167       rc = sqlite3VdbeIdxRowid(db, u.bs.pCrsr, &u.bs.rowid);
68168       if( rc!=SQLITE_OK ){
68169         goto abort_due_to_error;
68170       }
68171       pOut->u.i = u.bs.rowid;
68172       pOut->flags = MEM_Int;
68173     }
68174   }
68175   break;
68176 }
68177 
68178 /* Opcode: IdxGE P1 P2 P3 P4 P5
68179 **
68180 ** The P4 register values beginning with P3 form an unpacked index
68181 ** key that omits the ROWID.  Compare this key value against the index
68182 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68183 **
68184 ** If the P1 index entry is greater than or equal to the key value
68185 ** then jump to P2.  Otherwise fall through to the next instruction.
68186 **
68187 ** If P5 is non-zero then the key value is increased by an epsilon
68188 ** prior to the comparison.  This make the opcode work like IdxGT except
68189 ** that if the key from register P3 is a prefix of the key in the cursor,
68190 ** the result is false whereas it would be true with IdxGT.
68191 */
68192 /* Opcode: IdxLT P1 P2 P3 P4 P5
68193 **
68194 ** The P4 register values beginning with P3 form an unpacked index
68195 ** key that omits the ROWID.  Compare this key value against the index
68196 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
68197 **
68198 ** If the P1 index entry is less than the key value then jump to P2.
68199 ** Otherwise fall through to the next instruction.
68200 **
68201 ** If P5 is non-zero then the key value is increased by an epsilon prior
68202 ** to the comparison.  This makes the opcode work like IdxLE.
68203 */
68204 case OP_IdxLT:          /* jump */
68205 case OP_IdxGE: {        /* jump */
68206 #if 0  /* local variables moved into u.bt */
68207   VdbeCursor *pC;
68208   int res;
68209   UnpackedRecord r;
68210 #endif /* local variables moved into u.bt */
68211 
68212   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68213   u.bt.pC = p->apCsr[pOp->p1];
68214   assert( u.bt.pC!=0 );
68215   assert( u.bt.pC->isOrdered );
68216   if( ALWAYS(u.bt.pC->pCursor!=0) ){
68217     assert( u.bt.pC->deferredMoveto==0 );
68218     assert( pOp->p5==0 || pOp->p5==1 );
68219     assert( pOp->p4type==P4_INT32 );
68220     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
68221     u.bt.r.nField = (u16)pOp->p4.i;
68222     if( pOp->p5 ){
68223       u.bt.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
68224     }else{
68225       u.bt.r.flags = UNPACKED_IGNORE_ROWID;
68226     }
68227     u.bt.r.aMem = &aMem[pOp->p3];
68228 #ifdef SQLITE_DEBUG
68229     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
68230 #endif
68231     rc = sqlite3VdbeIdxKeyCompare(u.bt.pC, &u.bt.r, &u.bt.res);
68232     if( pOp->opcode==OP_IdxLT ){
68233       u.bt.res = -u.bt.res;
68234     }else{
68235       assert( pOp->opcode==OP_IdxGE );
68236       u.bt.res++;
68237     }
68238     if( u.bt.res>0 ){
68239       pc = pOp->p2 - 1 ;
68240     }
68241   }
68242   break;
68243 }
68244 
68245 /* Opcode: Destroy P1 P2 P3 * *
68246 **
68247 ** Delete an entire database table or index whose root page in the database
68248 ** file is given by P1.
68249 **
68250 ** The table being destroyed is in the main database file if P3==0.  If
68251 ** P3==1 then the table to be clear is in the auxiliary database file
68252 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68253 **
68254 ** If AUTOVACUUM is enabled then it is possible that another root page
68255 ** might be moved into the newly deleted root page in order to keep all
68256 ** root pages contiguous at the beginning of the database.  The former
68257 ** value of the root page that moved - its value before the move occurred -
68258 ** is stored in register P2.  If no page
68259 ** movement was required (because the table being dropped was already
68260 ** the last one in the database) then a zero is stored in register P2.
68261 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
68262 **
68263 ** See also: Clear
68264 */
68265 case OP_Destroy: {     /* out2-prerelease */
68266 #if 0  /* local variables moved into u.bu */
68267   int iMoved;
68268   int iCnt;
68269   Vdbe *pVdbe;
68270   int iDb;
68271 #endif /* local variables moved into u.bu */
68272 #ifndef SQLITE_OMIT_VIRTUALTABLE
68273   u.bu.iCnt = 0;
68274   for(u.bu.pVdbe=db->pVdbe; u.bu.pVdbe; u.bu.pVdbe = u.bu.pVdbe->pNext){
68275     if( u.bu.pVdbe->magic==VDBE_MAGIC_RUN && u.bu.pVdbe->inVtabMethod<2 && u.bu.pVdbe->pc>=0 ){
68276       u.bu.iCnt++;
68277     }
68278   }
68279 #else
68280   u.bu.iCnt = db->activeVdbeCnt;
68281 #endif
68282   pOut->flags = MEM_Null;
68283   if( u.bu.iCnt>1 ){
68284     rc = SQLITE_LOCKED;
68285     p->errorAction = OE_Abort;
68286   }else{
68287     u.bu.iDb = pOp->p3;
68288     assert( u.bu.iCnt==1 );
68289     assert( (p->btreeMask & (((yDbMask)1)<<u.bu.iDb))!=0 );
68290     rc = sqlite3BtreeDropTable(db->aDb[u.bu.iDb].pBt, pOp->p1, &u.bu.iMoved);
68291     pOut->flags = MEM_Int;
68292     pOut->u.i = u.bu.iMoved;
68293 #ifndef SQLITE_OMIT_AUTOVACUUM
68294     if( rc==SQLITE_OK && u.bu.iMoved!=0 ){
68295       sqlite3RootPageMoved(db, u.bu.iDb, u.bu.iMoved, pOp->p1);
68296       /* All OP_Destroy operations occur on the same btree */
68297       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bu.iDb+1 );
68298       resetSchemaOnFault = u.bu.iDb+1;
68299     }
68300 #endif
68301   }
68302   break;
68303 }
68304 
68305 /* Opcode: Clear P1 P2 P3
68306 **
68307 ** Delete all contents of the database table or index whose root page
68308 ** in the database file is given by P1.  But, unlike Destroy, do not
68309 ** remove the table or index from the database file.
68310 **
68311 ** The table being clear is in the main database file if P2==0.  If
68312 ** P2==1 then the table to be clear is in the auxiliary database file
68313 ** that is used to store tables create using CREATE TEMPORARY TABLE.
68314 **
68315 ** If the P3 value is non-zero, then the table referred to must be an
68316 ** intkey table (an SQL table, not an index). In this case the row change
68317 ** count is incremented by the number of rows in the table being cleared.
68318 ** If P3 is greater than zero, then the value stored in register P3 is
68319 ** also incremented by the number of rows in the table being cleared.
68320 **
68321 ** See also: Destroy
68322 */
68323 case OP_Clear: {
68324 #if 0  /* local variables moved into u.bv */
68325   int nChange;
68326 #endif /* local variables moved into u.bv */
68327 
68328   u.bv.nChange = 0;
68329   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
68330   rc = sqlite3BtreeClearTable(
68331       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bv.nChange : 0)
68332   );
68333   if( pOp->p3 ){
68334     p->nChange += u.bv.nChange;
68335     if( pOp->p3>0 ){
68336       assert( memIsValid(&aMem[pOp->p3]) );
68337       memAboutToChange(p, &aMem[pOp->p3]);
68338       aMem[pOp->p3].u.i += u.bv.nChange;
68339     }
68340   }
68341   break;
68342 }
68343 
68344 /* Opcode: CreateTable P1 P2 * * *
68345 **
68346 ** Allocate a new table in the main database file if P1==0 or in the
68347 ** auxiliary database file if P1==1 or in an attached database if
68348 ** P1>1.  Write the root page number of the new table into
68349 ** register P2
68350 **
68351 ** The difference between a table and an index is this:  A table must
68352 ** have a 4-byte integer key and can have arbitrary data.  An index
68353 ** has an arbitrary key but no data.
68354 **
68355 ** See also: CreateIndex
68356 */
68357 /* Opcode: CreateIndex P1 P2 * * *
68358 **
68359 ** Allocate a new index in the main database file if P1==0 or in the
68360 ** auxiliary database file if P1==1 or in an attached database if
68361 ** P1>1.  Write the root page number of the new table into
68362 ** register P2.
68363 **
68364 ** See documentation on OP_CreateTable for additional information.
68365 */
68366 case OP_CreateIndex:            /* out2-prerelease */
68367 case OP_CreateTable: {          /* out2-prerelease */
68368 #if 0  /* local variables moved into u.bw */
68369   int pgno;
68370   int flags;
68371   Db *pDb;
68372 #endif /* local variables moved into u.bw */
68373 
68374   u.bw.pgno = 0;
68375   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68376   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68377   u.bw.pDb = &db->aDb[pOp->p1];
68378   assert( u.bw.pDb->pBt!=0 );
68379   if( pOp->opcode==OP_CreateTable ){
68380     /* u.bw.flags = BTREE_INTKEY; */
68381     u.bw.flags = BTREE_INTKEY;
68382   }else{
68383     u.bw.flags = BTREE_BLOBKEY;
68384   }
68385   rc = sqlite3BtreeCreateTable(u.bw.pDb->pBt, &u.bw.pgno, u.bw.flags);
68386   pOut->u.i = u.bw.pgno;
68387   break;
68388 }
68389 
68390 /* Opcode: ParseSchema P1 * * P4 *
68391 **
68392 ** Read and parse all entries from the SQLITE_MASTER table of database P1
68393 ** that match the WHERE clause P4.
68394 **
68395 ** This opcode invokes the parser to create a new virtual machine,
68396 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
68397 */
68398 case OP_ParseSchema: {
68399 #if 0  /* local variables moved into u.bx */
68400   int iDb;
68401   const char *zMaster;
68402   char *zSql;
68403   InitData initData;
68404 #endif /* local variables moved into u.bx */
68405 
68406   /* Any prepared statement that invokes this opcode will hold mutexes
68407   ** on every btree.  This is a prerequisite for invoking
68408   ** sqlite3InitCallback().
68409   */
68410 #ifdef SQLITE_DEBUG
68411   for(u.bx.iDb=0; u.bx.iDb<db->nDb; u.bx.iDb++){
68412     assert( u.bx.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bx.iDb].pBt) );
68413   }
68414 #endif
68415 
68416   u.bx.iDb = pOp->p1;
68417   assert( u.bx.iDb>=0 && u.bx.iDb<db->nDb );
68418   assert( DbHasProperty(db, u.bx.iDb, DB_SchemaLoaded) );
68419   /* Used to be a conditional */ {
68420     u.bx.zMaster = SCHEMA_TABLE(u.bx.iDb);
68421     u.bx.initData.db = db;
68422     u.bx.initData.iDb = pOp->p1;
68423     u.bx.initData.pzErrMsg = &p->zErrMsg;
68424     u.bx.zSql = sqlite3MPrintf(db,
68425        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
68426        db->aDb[u.bx.iDb].zName, u.bx.zMaster, pOp->p4.z);
68427     if( u.bx.zSql==0 ){
68428       rc = SQLITE_NOMEM;
68429     }else{
68430       assert( db->init.busy==0 );
68431       db->init.busy = 1;
68432       u.bx.initData.rc = SQLITE_OK;
68433       assert( !db->mallocFailed );
68434       rc = sqlite3_exec(db, u.bx.zSql, sqlite3InitCallback, &u.bx.initData, 0);
68435       if( rc==SQLITE_OK ) rc = u.bx.initData.rc;
68436       sqlite3DbFree(db, u.bx.zSql);
68437       db->init.busy = 0;
68438     }
68439   }
68440   if( rc==SQLITE_NOMEM ){
68441     goto no_mem;
68442   }
68443   break;
68444 }
68445 
68446 #if !defined(SQLITE_OMIT_ANALYZE)
68447 /* Opcode: LoadAnalysis P1 * * * *
68448 **
68449 ** Read the sqlite_stat1 table for database P1 and load the content
68450 ** of that table into the internal index hash table.  This will cause
68451 ** the analysis to be used when preparing all subsequent queries.
68452 */
68453 case OP_LoadAnalysis: {
68454   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68455   rc = sqlite3AnalysisLoad(db, pOp->p1);
68456   break;
68457 }
68458 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
68459 
68460 /* Opcode: DropTable P1 * * P4 *
68461 **
68462 ** Remove the internal (in-memory) data structures that describe
68463 ** the table named P4 in database P1.  This is called after a table
68464 ** is dropped in order to keep the internal representation of the
68465 ** schema consistent with what is on disk.
68466 */
68467 case OP_DropTable: {
68468   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
68469   break;
68470 }
68471 
68472 /* Opcode: DropIndex P1 * * P4 *
68473 **
68474 ** Remove the internal (in-memory) data structures that describe
68475 ** the index named P4 in database P1.  This is called after an index
68476 ** is dropped in order to keep the internal representation of the
68477 ** schema consistent with what is on disk.
68478 */
68479 case OP_DropIndex: {
68480   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
68481   break;
68482 }
68483 
68484 /* Opcode: DropTrigger P1 * * P4 *
68485 **
68486 ** Remove the internal (in-memory) data structures that describe
68487 ** the trigger named P4 in database P1.  This is called after a trigger
68488 ** is dropped in order to keep the internal representation of the
68489 ** schema consistent with what is on disk.
68490 */
68491 case OP_DropTrigger: {
68492   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
68493   break;
68494 }
68495 
68496 
68497 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
68498 /* Opcode: IntegrityCk P1 P2 P3 * P5
68499 **
68500 ** Do an analysis of the currently open database.  Store in
68501 ** register P1 the text of an error message describing any problems.
68502 ** If no problems are found, store a NULL in register P1.
68503 **
68504 ** The register P3 contains the maximum number of allowed errors.
68505 ** At most reg(P3) errors will be reported.
68506 ** In other words, the analysis stops as soon as reg(P1) errors are
68507 ** seen.  Reg(P1) is updated with the number of errors remaining.
68508 **
68509 ** The root page numbers of all tables in the database are integer
68510 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
68511 ** total.
68512 **
68513 ** If P5 is not zero, the check is done on the auxiliary database
68514 ** file, not the main database file.
68515 **
68516 ** This opcode is used to implement the integrity_check pragma.
68517 */
68518 case OP_IntegrityCk: {
68519 #if 0  /* local variables moved into u.by */
68520   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
68521   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
68522   int j;          /* Loop counter */
68523   int nErr;       /* Number of errors reported */
68524   char *z;        /* Text of the error report */
68525   Mem *pnErr;     /* Register keeping track of errors remaining */
68526 #endif /* local variables moved into u.by */
68527 
68528   u.by.nRoot = pOp->p2;
68529   assert( u.by.nRoot>0 );
68530   u.by.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.by.nRoot+1) );
68531   if( u.by.aRoot==0 ) goto no_mem;
68532   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68533   u.by.pnErr = &aMem[pOp->p3];
68534   assert( (u.by.pnErr->flags & MEM_Int)!=0 );
68535   assert( (u.by.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
68536   pIn1 = &aMem[pOp->p1];
68537   for(u.by.j=0; u.by.j<u.by.nRoot; u.by.j++){
68538     u.by.aRoot[u.by.j] = (int)sqlite3VdbeIntValue(&pIn1[u.by.j]);
68539   }
68540   u.by.aRoot[u.by.j] = 0;
68541   assert( pOp->p5<db->nDb );
68542   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
68543   u.by.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.by.aRoot, u.by.nRoot,
68544                                  (int)u.by.pnErr->u.i, &u.by.nErr);
68545   sqlite3DbFree(db, u.by.aRoot);
68546   u.by.pnErr->u.i -= u.by.nErr;
68547   sqlite3VdbeMemSetNull(pIn1);
68548   if( u.by.nErr==0 ){
68549     assert( u.by.z==0 );
68550   }else if( u.by.z==0 ){
68551     goto no_mem;
68552   }else{
68553     sqlite3VdbeMemSetStr(pIn1, u.by.z, -1, SQLITE_UTF8, sqlite3_free);
68554   }
68555   UPDATE_MAX_BLOBSIZE(pIn1);
68556   sqlite3VdbeChangeEncoding(pIn1, encoding);
68557   break;
68558 }
68559 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
68560 
68561 /* Opcode: RowSetAdd P1 P2 * * *
68562 **
68563 ** Insert the integer value held by register P2 into a boolean index
68564 ** held in register P1.
68565 **
68566 ** An assertion fails if P2 is not an integer.
68567 */
68568 case OP_RowSetAdd: {       /* in1, in2 */
68569   pIn1 = &aMem[pOp->p1];
68570   pIn2 = &aMem[pOp->p2];
68571   assert( (pIn2->flags & MEM_Int)!=0 );
68572   if( (pIn1->flags & MEM_RowSet)==0 ){
68573     sqlite3VdbeMemSetRowSet(pIn1);
68574     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68575   }
68576   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
68577   break;
68578 }
68579 
68580 /* Opcode: RowSetRead P1 P2 P3 * *
68581 **
68582 ** Extract the smallest value from boolean index P1 and put that value into
68583 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
68584 ** unchanged and jump to instruction P2.
68585 */
68586 case OP_RowSetRead: {       /* jump, in1, out3 */
68587 #if 0  /* local variables moved into u.bz */
68588   i64 val;
68589 #endif /* local variables moved into u.bz */
68590   CHECK_FOR_INTERRUPT;
68591   pIn1 = &aMem[pOp->p1];
68592   if( (pIn1->flags & MEM_RowSet)==0
68593    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bz.val)==0
68594   ){
68595     /* The boolean index is empty */
68596     sqlite3VdbeMemSetNull(pIn1);
68597     pc = pOp->p2 - 1;
68598   }else{
68599     /* A value was pulled from the index */
68600     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bz.val);
68601   }
68602   break;
68603 }
68604 
68605 /* Opcode: RowSetTest P1 P2 P3 P4
68606 **
68607 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
68608 ** contains a RowSet object and that RowSet object contains
68609 ** the value held in P3, jump to register P2. Otherwise, insert the
68610 ** integer in P3 into the RowSet and continue on to the
68611 ** next opcode.
68612 **
68613 ** The RowSet object is optimized for the case where successive sets
68614 ** of integers, where each set contains no duplicates. Each set
68615 ** of values is identified by a unique P4 value. The first set
68616 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
68617 ** non-negative.  For non-negative values of P4 only the lower 4
68618 ** bits are significant.
68619 **
68620 ** This allows optimizations: (a) when P4==0 there is no need to test
68621 ** the rowset object for P3, as it is guaranteed not to contain it,
68622 ** (b) when P4==-1 there is no need to insert the value, as it will
68623 ** never be tested for, and (c) when a value that is part of set X is
68624 ** inserted, there is no need to search to see if the same value was
68625 ** previously inserted as part of set X (only if it was previously
68626 ** inserted as part of some other set).
68627 */
68628 case OP_RowSetTest: {                     /* jump, in1, in3 */
68629 #if 0  /* local variables moved into u.ca */
68630   int iSet;
68631   int exists;
68632 #endif /* local variables moved into u.ca */
68633 
68634   pIn1 = &aMem[pOp->p1];
68635   pIn3 = &aMem[pOp->p3];
68636   u.ca.iSet = pOp->p4.i;
68637   assert( pIn3->flags&MEM_Int );
68638 
68639   /* If there is anything other than a rowset object in memory cell P1,
68640   ** delete it now and initialize P1 with an empty rowset
68641   */
68642   if( (pIn1->flags & MEM_RowSet)==0 ){
68643     sqlite3VdbeMemSetRowSet(pIn1);
68644     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
68645   }
68646 
68647   assert( pOp->p4type==P4_INT32 );
68648   assert( u.ca.iSet==-1 || u.ca.iSet>=0 );
68649   if( u.ca.iSet ){
68650     u.ca.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
68651                                (u8)(u.ca.iSet>=0 ? u.ca.iSet & 0xf : 0xff),
68652                                pIn3->u.i);
68653     if( u.ca.exists ){
68654       pc = pOp->p2 - 1;
68655       break;
68656     }
68657   }
68658   if( u.ca.iSet>=0 ){
68659     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
68660   }
68661   break;
68662 }
68663 
68664 
68665 #ifndef SQLITE_OMIT_TRIGGER
68666 
68667 /* Opcode: Program P1 P2 P3 P4 *
68668 **
68669 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
68670 **
68671 ** P1 contains the address of the memory cell that contains the first memory
68672 ** cell in an array of values used as arguments to the sub-program. P2
68673 ** contains the address to jump to if the sub-program throws an IGNORE
68674 ** exception using the RAISE() function. Register P3 contains the address
68675 ** of a memory cell in this (the parent) VM that is used to allocate the
68676 ** memory required by the sub-vdbe at runtime.
68677 **
68678 ** P4 is a pointer to the VM containing the trigger program.
68679 */
68680 case OP_Program: {        /* jump */
68681 #if 0  /* local variables moved into u.cb */
68682   int nMem;               /* Number of memory registers for sub-program */
68683   int nByte;              /* Bytes of runtime space required for sub-program */
68684   Mem *pRt;               /* Register to allocate runtime space */
68685   Mem *pMem;              /* Used to iterate through memory cells */
68686   Mem *pEnd;              /* Last memory cell in new array */
68687   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
68688   SubProgram *pProgram;   /* Sub-program to execute */
68689   void *t;                /* Token identifying trigger */
68690 #endif /* local variables moved into u.cb */
68691 
68692   u.cb.pProgram = pOp->p4.pProgram;
68693   u.cb.pRt = &aMem[pOp->p3];
68694   assert( memIsValid(u.cb.pRt) );
68695   assert( u.cb.pProgram->nOp>0 );
68696 
68697   /* If the p5 flag is clear, then recursive invocation of triggers is
68698   ** disabled for backwards compatibility (p5 is set if this sub-program
68699   ** is really a trigger, not a foreign key action, and the flag set
68700   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
68701   **
68702   ** It is recursive invocation of triggers, at the SQL level, that is
68703   ** disabled. In some cases a single trigger may generate more than one
68704   ** SubProgram (if the trigger may be executed with more than one different
68705   ** ON CONFLICT algorithm). SubProgram structures associated with a
68706   ** single trigger all have the same value for the SubProgram.token
68707   ** variable.  */
68708   if( pOp->p5 ){
68709     u.cb.t = u.cb.pProgram->token;
68710     for(u.cb.pFrame=p->pFrame; u.cb.pFrame && u.cb.pFrame->token!=u.cb.t; u.cb.pFrame=u.cb.pFrame->pParent);
68711     if( u.cb.pFrame ) break;
68712   }
68713 
68714   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
68715     rc = SQLITE_ERROR;
68716     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
68717     break;
68718   }
68719 
68720   /* Register u.cb.pRt is used to store the memory required to save the state
68721   ** of the current program, and the memory required at runtime to execute
68722   ** the trigger program. If this trigger has been fired before, then u.cb.pRt
68723   ** is already allocated. Otherwise, it must be initialized.  */
68724   if( (u.cb.pRt->flags&MEM_Frame)==0 ){
68725     /* SubProgram.nMem is set to the number of memory cells used by the
68726     ** program stored in SubProgram.aOp. As well as these, one memory
68727     ** cell is required for each cursor used by the program. Set local
68728     ** variable u.cb.nMem (and later, VdbeFrame.nChildMem) to this value.
68729     */
68730     u.cb.nMem = u.cb.pProgram->nMem + u.cb.pProgram->nCsr;
68731     u.cb.nByte = ROUND8(sizeof(VdbeFrame))
68732               + u.cb.nMem * sizeof(Mem)
68733               + u.cb.pProgram->nCsr * sizeof(VdbeCursor *);
68734     u.cb.pFrame = sqlite3DbMallocZero(db, u.cb.nByte);
68735     if( !u.cb.pFrame ){
68736       goto no_mem;
68737     }
68738     sqlite3VdbeMemRelease(u.cb.pRt);
68739     u.cb.pRt->flags = MEM_Frame;
68740     u.cb.pRt->u.pFrame = u.cb.pFrame;
68741 
68742     u.cb.pFrame->v = p;
68743     u.cb.pFrame->nChildMem = u.cb.nMem;
68744     u.cb.pFrame->nChildCsr = u.cb.pProgram->nCsr;
68745     u.cb.pFrame->pc = pc;
68746     u.cb.pFrame->aMem = p->aMem;
68747     u.cb.pFrame->nMem = p->nMem;
68748     u.cb.pFrame->apCsr = p->apCsr;
68749     u.cb.pFrame->nCursor = p->nCursor;
68750     u.cb.pFrame->aOp = p->aOp;
68751     u.cb.pFrame->nOp = p->nOp;
68752     u.cb.pFrame->token = u.cb.pProgram->token;
68753 
68754     u.cb.pEnd = &VdbeFrameMem(u.cb.pFrame)[u.cb.pFrame->nChildMem];
68755     for(u.cb.pMem=VdbeFrameMem(u.cb.pFrame); u.cb.pMem!=u.cb.pEnd; u.cb.pMem++){
68756       u.cb.pMem->flags = MEM_Null;
68757       u.cb.pMem->db = db;
68758     }
68759   }else{
68760     u.cb.pFrame = u.cb.pRt->u.pFrame;
68761     assert( u.cb.pProgram->nMem+u.cb.pProgram->nCsr==u.cb.pFrame->nChildMem );
68762     assert( u.cb.pProgram->nCsr==u.cb.pFrame->nChildCsr );
68763     assert( pc==u.cb.pFrame->pc );
68764   }
68765 
68766   p->nFrame++;
68767   u.cb.pFrame->pParent = p->pFrame;
68768   u.cb.pFrame->lastRowid = lastRowid;
68769   u.cb.pFrame->nChange = p->nChange;
68770   p->nChange = 0;
68771   p->pFrame = u.cb.pFrame;
68772   p->aMem = aMem = &VdbeFrameMem(u.cb.pFrame)[-1];
68773   p->nMem = u.cb.pFrame->nChildMem;
68774   p->nCursor = (u16)u.cb.pFrame->nChildCsr;
68775   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
68776   p->aOp = aOp = u.cb.pProgram->aOp;
68777   p->nOp = u.cb.pProgram->nOp;
68778   pc = -1;
68779 
68780   break;
68781 }
68782 
68783 /* Opcode: Param P1 P2 * * *
68784 **
68785 ** This opcode is only ever present in sub-programs called via the
68786 ** OP_Program instruction. Copy a value currently stored in a memory
68787 ** cell of the calling (parent) frame to cell P2 in the current frames
68788 ** address space. This is used by trigger programs to access the new.*
68789 ** and old.* values.
68790 **
68791 ** The address of the cell in the parent frame is determined by adding
68792 ** the value of the P1 argument to the value of the P1 argument to the
68793 ** calling OP_Program instruction.
68794 */
68795 case OP_Param: {           /* out2-prerelease */
68796 #if 0  /* local variables moved into u.cc */
68797   VdbeFrame *pFrame;
68798   Mem *pIn;
68799 #endif /* local variables moved into u.cc */
68800   u.cc.pFrame = p->pFrame;
68801   u.cc.pIn = &u.cc.pFrame->aMem[pOp->p1 + u.cc.pFrame->aOp[u.cc.pFrame->pc].p1];
68802   sqlite3VdbeMemShallowCopy(pOut, u.cc.pIn, MEM_Ephem);
68803   break;
68804 }
68805 
68806 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
68807 
68808 #ifndef SQLITE_OMIT_FOREIGN_KEY
68809 /* Opcode: FkCounter P1 P2 * * *
68810 **
68811 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
68812 ** If P1 is non-zero, the database constraint counter is incremented
68813 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
68814 ** statement counter is incremented (immediate foreign key constraints).
68815 */
68816 case OP_FkCounter: {
68817   if( pOp->p1 ){
68818     db->nDeferredCons += pOp->p2;
68819   }else{
68820     p->nFkConstraint += pOp->p2;
68821   }
68822   break;
68823 }
68824 
68825 /* Opcode: FkIfZero P1 P2 * * *
68826 **
68827 ** This opcode tests if a foreign key constraint-counter is currently zero.
68828 ** If so, jump to instruction P2. Otherwise, fall through to the next
68829 ** instruction.
68830 **
68831 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
68832 ** is zero (the one that counts deferred constraint violations). If P1 is
68833 ** zero, the jump is taken if the statement constraint-counter is zero
68834 ** (immediate foreign key constraint violations).
68835 */
68836 case OP_FkIfZero: {         /* jump */
68837   if( pOp->p1 ){
68838     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
68839   }else{
68840     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
68841   }
68842   break;
68843 }
68844 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
68845 
68846 #ifndef SQLITE_OMIT_AUTOINCREMENT
68847 /* Opcode: MemMax P1 P2 * * *
68848 **
68849 ** P1 is a register in the root frame of this VM (the root frame is
68850 ** different from the current frame if this instruction is being executed
68851 ** within a sub-program). Set the value of register P1 to the maximum of
68852 ** its current value and the value in register P2.
68853 **
68854 ** This instruction throws an error if the memory cell is not initially
68855 ** an integer.
68856 */
68857 case OP_MemMax: {        /* in2 */
68858 #if 0  /* local variables moved into u.cd */
68859   Mem *pIn1;
68860   VdbeFrame *pFrame;
68861 #endif /* local variables moved into u.cd */
68862   if( p->pFrame ){
68863     for(u.cd.pFrame=p->pFrame; u.cd.pFrame->pParent; u.cd.pFrame=u.cd.pFrame->pParent);
68864     u.cd.pIn1 = &u.cd.pFrame->aMem[pOp->p1];
68865   }else{
68866     u.cd.pIn1 = &aMem[pOp->p1];
68867   }
68868   assert( memIsValid(u.cd.pIn1) );
68869   sqlite3VdbeMemIntegerify(u.cd.pIn1);
68870   pIn2 = &aMem[pOp->p2];
68871   sqlite3VdbeMemIntegerify(pIn2);
68872   if( u.cd.pIn1->u.i<pIn2->u.i){
68873     u.cd.pIn1->u.i = pIn2->u.i;
68874   }
68875   break;
68876 }
68877 #endif /* SQLITE_OMIT_AUTOINCREMENT */
68878 
68879 /* Opcode: IfPos P1 P2 * * *
68880 **
68881 ** If the value of register P1 is 1 or greater, jump to P2.
68882 **
68883 ** It is illegal to use this instruction on a register that does
68884 ** not contain an integer.  An assertion fault will result if you try.
68885 */
68886 case OP_IfPos: {        /* jump, in1 */
68887   pIn1 = &aMem[pOp->p1];
68888   assert( pIn1->flags&MEM_Int );
68889   if( pIn1->u.i>0 ){
68890      pc = pOp->p2 - 1;
68891   }
68892   break;
68893 }
68894 
68895 /* Opcode: IfNeg P1 P2 * * *
68896 **
68897 ** If the value of register P1 is less than zero, jump to P2.
68898 **
68899 ** It is illegal to use this instruction on a register that does
68900 ** not contain an integer.  An assertion fault will result if you try.
68901 */
68902 case OP_IfNeg: {        /* jump, in1 */
68903   pIn1 = &aMem[pOp->p1];
68904   assert( pIn1->flags&MEM_Int );
68905   if( pIn1->u.i<0 ){
68906      pc = pOp->p2 - 1;
68907   }
68908   break;
68909 }
68910 
68911 /* Opcode: IfZero P1 P2 P3 * *
68912 **
68913 ** The register P1 must contain an integer.  Add literal P3 to the
68914 ** value in register P1.  If the result is exactly 0, jump to P2.
68915 **
68916 ** It is illegal to use this instruction on a register that does
68917 ** not contain an integer.  An assertion fault will result if you try.
68918 */
68919 case OP_IfZero: {        /* jump, in1 */
68920   pIn1 = &aMem[pOp->p1];
68921   assert( pIn1->flags&MEM_Int );
68922   pIn1->u.i += pOp->p3;
68923   if( pIn1->u.i==0 ){
68924      pc = pOp->p2 - 1;
68925   }
68926   break;
68927 }
68928 
68929 /* Opcode: AggStep * P2 P3 P4 P5
68930 **
68931 ** Execute the step function for an aggregate.  The
68932 ** function has P5 arguments.   P4 is a pointer to the FuncDef
68933 ** structure that specifies the function.  Use register
68934 ** P3 as the accumulator.
68935 **
68936 ** The P5 arguments are taken from register P2 and its
68937 ** successors.
68938 */
68939 case OP_AggStep: {
68940 #if 0  /* local variables moved into u.ce */
68941   int n;
68942   int i;
68943   Mem *pMem;
68944   Mem *pRec;
68945   sqlite3_context ctx;
68946   sqlite3_value **apVal;
68947 #endif /* local variables moved into u.ce */
68948 
68949   u.ce.n = pOp->p5;
68950   assert( u.ce.n>=0 );
68951   u.ce.pRec = &aMem[pOp->p2];
68952   u.ce.apVal = p->apArg;
68953   assert( u.ce.apVal || u.ce.n==0 );
68954   for(u.ce.i=0; u.ce.i<u.ce.n; u.ce.i++, u.ce.pRec++){
68955     assert( memIsValid(u.ce.pRec) );
68956     u.ce.apVal[u.ce.i] = u.ce.pRec;
68957     memAboutToChange(p, u.ce.pRec);
68958     sqlite3VdbeMemStoreType(u.ce.pRec);
68959   }
68960   u.ce.ctx.pFunc = pOp->p4.pFunc;
68961   assert( pOp->p3>0 && pOp->p3<=p->nMem );
68962   u.ce.ctx.pMem = u.ce.pMem = &aMem[pOp->p3];
68963   u.ce.pMem->n++;
68964   u.ce.ctx.s.flags = MEM_Null;
68965   u.ce.ctx.s.z = 0;
68966   u.ce.ctx.s.zMalloc = 0;
68967   u.ce.ctx.s.xDel = 0;
68968   u.ce.ctx.s.db = db;
68969   u.ce.ctx.isError = 0;
68970   u.ce.ctx.pColl = 0;
68971   if( u.ce.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
68972     assert( pOp>p->aOp );
68973     assert( pOp[-1].p4type==P4_COLLSEQ );
68974     assert( pOp[-1].opcode==OP_CollSeq );
68975     u.ce.ctx.pColl = pOp[-1].p4.pColl;
68976   }
68977   (u.ce.ctx.pFunc->xStep)(&u.ce.ctx, u.ce.n, u.ce.apVal); /* IMP: R-24505-23230 */
68978   if( u.ce.ctx.isError ){
68979     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ce.ctx.s));
68980     rc = u.ce.ctx.isError;
68981   }
68982 
68983   sqlite3VdbeMemRelease(&u.ce.ctx.s);
68984 
68985   break;
68986 }
68987 
68988 /* Opcode: AggFinal P1 P2 * P4 *
68989 **
68990 ** Execute the finalizer function for an aggregate.  P1 is
68991 ** the memory location that is the accumulator for the aggregate.
68992 **
68993 ** P2 is the number of arguments that the step function takes and
68994 ** P4 is a pointer to the FuncDef for this function.  The P2
68995 ** argument is not used by this opcode.  It is only there to disambiguate
68996 ** functions that can take varying numbers of arguments.  The
68997 ** P4 argument is only needed for the degenerate case where
68998 ** the step function was not previously called.
68999 */
69000 case OP_AggFinal: {
69001 #if 0  /* local variables moved into u.cf */
69002   Mem *pMem;
69003 #endif /* local variables moved into u.cf */
69004   assert( pOp->p1>0 && pOp->p1<=p->nMem );
69005   u.cf.pMem = &aMem[pOp->p1];
69006   assert( (u.cf.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
69007   rc = sqlite3VdbeMemFinalize(u.cf.pMem, pOp->p4.pFunc);
69008   if( rc ){
69009     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cf.pMem));
69010   }
69011   sqlite3VdbeChangeEncoding(u.cf.pMem, encoding);
69012   UPDATE_MAX_BLOBSIZE(u.cf.pMem);
69013   if( sqlite3VdbeMemTooBig(u.cf.pMem) ){
69014     goto too_big;
69015   }
69016   break;
69017 }
69018 
69019 #ifndef SQLITE_OMIT_WAL
69020 /* Opcode: Checkpoint P1 P2 P3 * *
69021 **
69022 ** Checkpoint database P1. This is a no-op if P1 is not currently in
69023 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
69024 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
69025 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
69026 ** WAL after the checkpoint into mem[P3+1] and the number of pages
69027 ** in the WAL that have been checkpointed after the checkpoint
69028 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
69029 ** mem[P3+2] are initialized to -1.
69030 */
69031 case OP_Checkpoint: {
69032 #if 0  /* local variables moved into u.cg */
69033   int i;                          /* Loop counter */
69034   int aRes[3];                    /* Results */
69035   Mem *pMem;                      /* Write results here */
69036 #endif /* local variables moved into u.cg */
69037 
69038   u.cg.aRes[0] = 0;
69039   u.cg.aRes[1] = u.cg.aRes[2] = -1;
69040   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
69041        || pOp->p2==SQLITE_CHECKPOINT_FULL
69042        || pOp->p2==SQLITE_CHECKPOINT_RESTART
69043   );
69044   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.cg.aRes[1], &u.cg.aRes[2]);
69045   if( rc==SQLITE_BUSY ){
69046     rc = SQLITE_OK;
69047     u.cg.aRes[0] = 1;
69048   }
69049   for(u.cg.i=0, u.cg.pMem = &aMem[pOp->p3]; u.cg.i<3; u.cg.i++, u.cg.pMem++){
69050     sqlite3VdbeMemSetInt64(u.cg.pMem, (i64)u.cg.aRes[u.cg.i]);
69051   }
69052   break;
69053 };
69054 #endif
69055 
69056 #ifndef SQLITE_OMIT_PRAGMA
69057 /* Opcode: JournalMode P1 P2 P3 * P5
69058 **
69059 ** Change the journal mode of database P1 to P3. P3 must be one of the
69060 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
69061 ** modes (delete, truncate, persist, off and memory), this is a simple
69062 ** operation. No IO is required.
69063 **
69064 ** If changing into or out of WAL mode the procedure is more complicated.
69065 **
69066 ** Write a string containing the final journal-mode to register P2.
69067 */
69068 case OP_JournalMode: {    /* out2-prerelease */
69069 #if 0  /* local variables moved into u.ch */
69070   Btree *pBt;                     /* Btree to change journal mode of */
69071   Pager *pPager;                  /* Pager associated with pBt */
69072   int eNew;                       /* New journal mode */
69073   int eOld;                       /* The old journal mode */
69074   const char *zFilename;          /* Name of database file for pPager */
69075 #endif /* local variables moved into u.ch */
69076 
69077   u.ch.eNew = pOp->p3;
69078   assert( u.ch.eNew==PAGER_JOURNALMODE_DELETE
69079        || u.ch.eNew==PAGER_JOURNALMODE_TRUNCATE
69080        || u.ch.eNew==PAGER_JOURNALMODE_PERSIST
69081        || u.ch.eNew==PAGER_JOURNALMODE_OFF
69082        || u.ch.eNew==PAGER_JOURNALMODE_MEMORY
69083        || u.ch.eNew==PAGER_JOURNALMODE_WAL
69084        || u.ch.eNew==PAGER_JOURNALMODE_QUERY
69085   );
69086   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69087 
69088   u.ch.pBt = db->aDb[pOp->p1].pBt;
69089   u.ch.pPager = sqlite3BtreePager(u.ch.pBt);
69090   u.ch.eOld = sqlite3PagerGetJournalMode(u.ch.pPager);
69091   if( u.ch.eNew==PAGER_JOURNALMODE_QUERY ) u.ch.eNew = u.ch.eOld;
69092   if( !sqlite3PagerOkToChangeJournalMode(u.ch.pPager) ) u.ch.eNew = u.ch.eOld;
69093 
69094 #ifndef SQLITE_OMIT_WAL
69095   u.ch.zFilename = sqlite3PagerFilename(u.ch.pPager);
69096 
69097   /* Do not allow a transition to journal_mode=WAL for a database
69098   ** in temporary storage or if the VFS does not support shared memory
69099   */
69100   if( u.ch.eNew==PAGER_JOURNALMODE_WAL
69101    && (u.ch.zFilename[0]==0                         /* Temp file */
69102        || !sqlite3PagerWalSupported(u.ch.pPager))   /* No shared-memory support */
69103   ){
69104     u.ch.eNew = u.ch.eOld;
69105   }
69106 
69107   if( (u.ch.eNew!=u.ch.eOld)
69108    && (u.ch.eOld==PAGER_JOURNALMODE_WAL || u.ch.eNew==PAGER_JOURNALMODE_WAL)
69109   ){
69110     if( !db->autoCommit || db->activeVdbeCnt>1 ){
69111       rc = SQLITE_ERROR;
69112       sqlite3SetString(&p->zErrMsg, db,
69113           "cannot change %s wal mode from within a transaction",
69114           (u.ch.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
69115       );
69116       break;
69117     }else{
69118 
69119       if( u.ch.eOld==PAGER_JOURNALMODE_WAL ){
69120         /* If leaving WAL mode, close the log file. If successful, the call
69121         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
69122         ** file. An EXCLUSIVE lock may still be held on the database file
69123         ** after a successful return.
69124         */
69125         rc = sqlite3PagerCloseWal(u.ch.pPager);
69126         if( rc==SQLITE_OK ){
69127           sqlite3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
69128         }
69129       }else if( u.ch.eOld==PAGER_JOURNALMODE_MEMORY ){
69130         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
69131         ** as an intermediate */
69132         sqlite3PagerSetJournalMode(u.ch.pPager, PAGER_JOURNALMODE_OFF);
69133       }
69134 
69135       /* Open a transaction on the database file. Regardless of the journal
69136       ** mode, this transaction always uses a rollback journal.
69137       */
69138       assert( sqlite3BtreeIsInTrans(u.ch.pBt)==0 );
69139       if( rc==SQLITE_OK ){
69140         rc = sqlite3BtreeSetVersion(u.ch.pBt, (u.ch.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
69141       }
69142     }
69143   }
69144 #endif /* ifndef SQLITE_OMIT_WAL */
69145 
69146   if( rc ){
69147     u.ch.eNew = u.ch.eOld;
69148   }
69149   u.ch.eNew = sqlite3PagerSetJournalMode(u.ch.pPager, u.ch.eNew);
69150 
69151   pOut = &aMem[pOp->p2];
69152   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
69153   pOut->z = (char *)sqlite3JournalModename(u.ch.eNew);
69154   pOut->n = sqlite3Strlen30(pOut->z);
69155   pOut->enc = SQLITE_UTF8;
69156   sqlite3VdbeChangeEncoding(pOut, encoding);
69157   break;
69158 };
69159 #endif /* SQLITE_OMIT_PRAGMA */
69160 
69161 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
69162 /* Opcode: Vacuum * * * * *
69163 **
69164 ** Vacuum the entire database.  This opcode will cause other virtual
69165 ** machines to be created and run.  It may not be called from within
69166 ** a transaction.
69167 */
69168 case OP_Vacuum: {
69169   rc = sqlite3RunVacuum(&p->zErrMsg, db);
69170   break;
69171 }
69172 #endif
69173 
69174 #if !defined(SQLITE_OMIT_AUTOVACUUM)
69175 /* Opcode: IncrVacuum P1 P2 * * *
69176 **
69177 ** Perform a single step of the incremental vacuum procedure on
69178 ** the P1 database. If the vacuum has finished, jump to instruction
69179 ** P2. Otherwise, fall through to the next instruction.
69180 */
69181 case OP_IncrVacuum: {        /* jump */
69182 #if 0  /* local variables moved into u.ci */
69183   Btree *pBt;
69184 #endif /* local variables moved into u.ci */
69185 
69186   assert( pOp->p1>=0 && pOp->p1<db->nDb );
69187   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69188   u.ci.pBt = db->aDb[pOp->p1].pBt;
69189   rc = sqlite3BtreeIncrVacuum(u.ci.pBt);
69190   if( rc==SQLITE_DONE ){
69191     pc = pOp->p2 - 1;
69192     rc = SQLITE_OK;
69193   }
69194   break;
69195 }
69196 #endif
69197 
69198 /* Opcode: Expire P1 * * * *
69199 **
69200 ** Cause precompiled statements to become expired. An expired statement
69201 ** fails with an error code of SQLITE_SCHEMA if it is ever executed
69202 ** (via sqlite3_step()).
69203 **
69204 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
69205 ** then only the currently executing statement is affected.
69206 */
69207 case OP_Expire: {
69208   if( !pOp->p1 ){
69209     sqlite3ExpirePreparedStatements(db);
69210   }else{
69211     p->expired = 1;
69212   }
69213   break;
69214 }
69215 
69216 #ifndef SQLITE_OMIT_SHARED_CACHE
69217 /* Opcode: TableLock P1 P2 P3 P4 *
69218 **
69219 ** Obtain a lock on a particular table. This instruction is only used when
69220 ** the shared-cache feature is enabled.
69221 **
69222 ** P1 is the index of the database in sqlite3.aDb[] of the database
69223 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
69224 ** a write lock if P3==1.
69225 **
69226 ** P2 contains the root-page of the table to lock.
69227 **
69228 ** P4 contains a pointer to the name of the table being locked. This is only
69229 ** used to generate an error message if the lock cannot be obtained.
69230 */
69231 case OP_TableLock: {
69232   u8 isWriteLock = (u8)pOp->p3;
69233   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
69234     int p1 = pOp->p1;
69235     assert( p1>=0 && p1<db->nDb );
69236     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
69237     assert( isWriteLock==0 || isWriteLock==1 );
69238     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
69239     if( (rc&0xFF)==SQLITE_LOCKED ){
69240       const char *z = pOp->p4.z;
69241       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
69242     }
69243   }
69244   break;
69245 }
69246 #endif /* SQLITE_OMIT_SHARED_CACHE */
69247 
69248 #ifndef SQLITE_OMIT_VIRTUALTABLE
69249 /* Opcode: VBegin * * * P4 *
69250 **
69251 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
69252 ** xBegin method for that table.
69253 **
69254 ** Also, whether or not P4 is set, check that this is not being called from
69255 ** within a callback to a virtual table xSync() method. If it is, the error
69256 ** code will be set to SQLITE_LOCKED.
69257 */
69258 case OP_VBegin: {
69259 #if 0  /* local variables moved into u.cj */
69260   VTable *pVTab;
69261 #endif /* local variables moved into u.cj */
69262   u.cj.pVTab = pOp->p4.pVtab;
69263   rc = sqlite3VtabBegin(db, u.cj.pVTab);
69264   if( u.cj.pVTab ) importVtabErrMsg(p, u.cj.pVTab->pVtab);
69265   break;
69266 }
69267 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69268 
69269 #ifndef SQLITE_OMIT_VIRTUALTABLE
69270 /* Opcode: VCreate P1 * * P4 *
69271 **
69272 ** P4 is the name of a virtual table in database P1. Call the xCreate method
69273 ** for that table.
69274 */
69275 case OP_VCreate: {
69276   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
69277   break;
69278 }
69279 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69280 
69281 #ifndef SQLITE_OMIT_VIRTUALTABLE
69282 /* Opcode: VDestroy P1 * * P4 *
69283 **
69284 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
69285 ** of that table.
69286 */
69287 case OP_VDestroy: {
69288   p->inVtabMethod = 2;
69289   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
69290   p->inVtabMethod = 0;
69291   break;
69292 }
69293 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69294 
69295 #ifndef SQLITE_OMIT_VIRTUALTABLE
69296 /* Opcode: VOpen P1 * * P4 *
69297 **
69298 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69299 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
69300 ** table and stores that cursor in P1.
69301 */
69302 case OP_VOpen: {
69303 #if 0  /* local variables moved into u.ck */
69304   VdbeCursor *pCur;
69305   sqlite3_vtab_cursor *pVtabCursor;
69306   sqlite3_vtab *pVtab;
69307   sqlite3_module *pModule;
69308 #endif /* local variables moved into u.ck */
69309 
69310   u.ck.pCur = 0;
69311   u.ck.pVtabCursor = 0;
69312   u.ck.pVtab = pOp->p4.pVtab->pVtab;
69313   u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
69314   assert(u.ck.pVtab && u.ck.pModule);
69315   rc = u.ck.pModule->xOpen(u.ck.pVtab, &u.ck.pVtabCursor);
69316   importVtabErrMsg(p, u.ck.pVtab);
69317   if( SQLITE_OK==rc ){
69318     /* Initialize sqlite3_vtab_cursor base class */
69319     u.ck.pVtabCursor->pVtab = u.ck.pVtab;
69320 
69321     /* Initialise vdbe cursor object */
69322     u.ck.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
69323     if( u.ck.pCur ){
69324       u.ck.pCur->pVtabCursor = u.ck.pVtabCursor;
69325       u.ck.pCur->pModule = u.ck.pVtabCursor->pVtab->pModule;
69326     }else{
69327       db->mallocFailed = 1;
69328       u.ck.pModule->xClose(u.ck.pVtabCursor);
69329     }
69330   }
69331   break;
69332 }
69333 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69334 
69335 #ifndef SQLITE_OMIT_VIRTUALTABLE
69336 /* Opcode: VFilter P1 P2 P3 P4 *
69337 **
69338 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
69339 ** the filtered result set is empty.
69340 **
69341 ** P4 is either NULL or a string that was generated by the xBestIndex
69342 ** method of the module.  The interpretation of the P4 string is left
69343 ** to the module implementation.
69344 **
69345 ** This opcode invokes the xFilter method on the virtual table specified
69346 ** by P1.  The integer query plan parameter to xFilter is stored in register
69347 ** P3. Register P3+1 stores the argc parameter to be passed to the
69348 ** xFilter method. Registers P3+2..P3+1+argc are the argc
69349 ** additional parameters which are passed to
69350 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
69351 **
69352 ** A jump is made to P2 if the result set after filtering would be empty.
69353 */
69354 case OP_VFilter: {   /* jump */
69355 #if 0  /* local variables moved into u.cl */
69356   int nArg;
69357   int iQuery;
69358   const sqlite3_module *pModule;
69359   Mem *pQuery;
69360   Mem *pArgc;
69361   sqlite3_vtab_cursor *pVtabCursor;
69362   sqlite3_vtab *pVtab;
69363   VdbeCursor *pCur;
69364   int res;
69365   int i;
69366   Mem **apArg;
69367 #endif /* local variables moved into u.cl */
69368 
69369   u.cl.pQuery = &aMem[pOp->p3];
69370   u.cl.pArgc = &u.cl.pQuery[1];
69371   u.cl.pCur = p->apCsr[pOp->p1];
69372   assert( memIsValid(u.cl.pQuery) );
69373   REGISTER_TRACE(pOp->p3, u.cl.pQuery);
69374   assert( u.cl.pCur->pVtabCursor );
69375   u.cl.pVtabCursor = u.cl.pCur->pVtabCursor;
69376   u.cl.pVtab = u.cl.pVtabCursor->pVtab;
69377   u.cl.pModule = u.cl.pVtab->pModule;
69378 
69379   /* Grab the index number and argc parameters */
69380   assert( (u.cl.pQuery->flags&MEM_Int)!=0 && u.cl.pArgc->flags==MEM_Int );
69381   u.cl.nArg = (int)u.cl.pArgc->u.i;
69382   u.cl.iQuery = (int)u.cl.pQuery->u.i;
69383 
69384   /* Invoke the xFilter method */
69385   {
69386     u.cl.res = 0;
69387     u.cl.apArg = p->apArg;
69388     for(u.cl.i = 0; u.cl.i<u.cl.nArg; u.cl.i++){
69389       u.cl.apArg[u.cl.i] = &u.cl.pArgc[u.cl.i+1];
69390       sqlite3VdbeMemStoreType(u.cl.apArg[u.cl.i]);
69391     }
69392 
69393     p->inVtabMethod = 1;
69394     rc = u.cl.pModule->xFilter(u.cl.pVtabCursor, u.cl.iQuery, pOp->p4.z, u.cl.nArg, u.cl.apArg);
69395     p->inVtabMethod = 0;
69396     importVtabErrMsg(p, u.cl.pVtab);
69397     if( rc==SQLITE_OK ){
69398       u.cl.res = u.cl.pModule->xEof(u.cl.pVtabCursor);
69399     }
69400 
69401     if( u.cl.res ){
69402       pc = pOp->p2 - 1;
69403     }
69404   }
69405   u.cl.pCur->nullRow = 0;
69406 
69407   break;
69408 }
69409 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69410 
69411 #ifndef SQLITE_OMIT_VIRTUALTABLE
69412 /* Opcode: VColumn P1 P2 P3 * *
69413 **
69414 ** Store the value of the P2-th column of
69415 ** the row of the virtual-table that the
69416 ** P1 cursor is pointing to into register P3.
69417 */
69418 case OP_VColumn: {
69419 #if 0  /* local variables moved into u.cm */
69420   sqlite3_vtab *pVtab;
69421   const sqlite3_module *pModule;
69422   Mem *pDest;
69423   sqlite3_context sContext;
69424 #endif /* local variables moved into u.cm */
69425 
69426   VdbeCursor *pCur = p->apCsr[pOp->p1];
69427   assert( pCur->pVtabCursor );
69428   assert( pOp->p3>0 && pOp->p3<=p->nMem );
69429   u.cm.pDest = &aMem[pOp->p3];
69430   memAboutToChange(p, u.cm.pDest);
69431   if( pCur->nullRow ){
69432     sqlite3VdbeMemSetNull(u.cm.pDest);
69433     break;
69434   }
69435   u.cm.pVtab = pCur->pVtabCursor->pVtab;
69436   u.cm.pModule = u.cm.pVtab->pModule;
69437   assert( u.cm.pModule->xColumn );
69438   memset(&u.cm.sContext, 0, sizeof(u.cm.sContext));
69439 
69440   /* The output cell may already have a buffer allocated. Move
69441   ** the current contents to u.cm.sContext.s so in case the user-function
69442   ** can use the already allocated buffer instead of allocating a
69443   ** new one.
69444   */
69445   sqlite3VdbeMemMove(&u.cm.sContext.s, u.cm.pDest);
69446   MemSetTypeFlag(&u.cm.sContext.s, MEM_Null);
69447 
69448   rc = u.cm.pModule->xColumn(pCur->pVtabCursor, &u.cm.sContext, pOp->p2);
69449   importVtabErrMsg(p, u.cm.pVtab);
69450   if( u.cm.sContext.isError ){
69451     rc = u.cm.sContext.isError;
69452   }
69453 
69454   /* Copy the result of the function to the P3 register. We
69455   ** do this regardless of whether or not an error occurred to ensure any
69456   ** dynamic allocation in u.cm.sContext.s (a Mem struct) is  released.
69457   */
69458   sqlite3VdbeChangeEncoding(&u.cm.sContext.s, encoding);
69459   sqlite3VdbeMemMove(u.cm.pDest, &u.cm.sContext.s);
69460   REGISTER_TRACE(pOp->p3, u.cm.pDest);
69461   UPDATE_MAX_BLOBSIZE(u.cm.pDest);
69462 
69463   if( sqlite3VdbeMemTooBig(u.cm.pDest) ){
69464     goto too_big;
69465   }
69466   break;
69467 }
69468 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69469 
69470 #ifndef SQLITE_OMIT_VIRTUALTABLE
69471 /* Opcode: VNext P1 P2 * * *
69472 **
69473 ** Advance virtual table P1 to the next row in its result set and
69474 ** jump to instruction P2.  Or, if the virtual table has reached
69475 ** the end of its result set, then fall through to the next instruction.
69476 */
69477 case OP_VNext: {   /* jump */
69478 #if 0  /* local variables moved into u.cn */
69479   sqlite3_vtab *pVtab;
69480   const sqlite3_module *pModule;
69481   int res;
69482   VdbeCursor *pCur;
69483 #endif /* local variables moved into u.cn */
69484 
69485   u.cn.res = 0;
69486   u.cn.pCur = p->apCsr[pOp->p1];
69487   assert( u.cn.pCur->pVtabCursor );
69488   if( u.cn.pCur->nullRow ){
69489     break;
69490   }
69491   u.cn.pVtab = u.cn.pCur->pVtabCursor->pVtab;
69492   u.cn.pModule = u.cn.pVtab->pModule;
69493   assert( u.cn.pModule->xNext );
69494 
69495   /* Invoke the xNext() method of the module. There is no way for the
69496   ** underlying implementation to return an error if one occurs during
69497   ** xNext(). Instead, if an error occurs, true is returned (indicating that
69498   ** data is available) and the error code returned when xColumn or
69499   ** some other method is next invoked on the save virtual table cursor.
69500   */
69501   p->inVtabMethod = 1;
69502   rc = u.cn.pModule->xNext(u.cn.pCur->pVtabCursor);
69503   p->inVtabMethod = 0;
69504   importVtabErrMsg(p, u.cn.pVtab);
69505   if( rc==SQLITE_OK ){
69506     u.cn.res = u.cn.pModule->xEof(u.cn.pCur->pVtabCursor);
69507   }
69508 
69509   if( !u.cn.res ){
69510     /* If there is data, jump to P2 */
69511     pc = pOp->p2 - 1;
69512   }
69513   break;
69514 }
69515 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69516 
69517 #ifndef SQLITE_OMIT_VIRTUALTABLE
69518 /* Opcode: VRename P1 * * P4 *
69519 **
69520 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69521 ** This opcode invokes the corresponding xRename method. The value
69522 ** in register P1 is passed as the zName argument to the xRename method.
69523 */
69524 case OP_VRename: {
69525 #if 0  /* local variables moved into u.co */
69526   sqlite3_vtab *pVtab;
69527   Mem *pName;
69528 #endif /* local variables moved into u.co */
69529 
69530   u.co.pVtab = pOp->p4.pVtab->pVtab;
69531   u.co.pName = &aMem[pOp->p1];
69532   assert( u.co.pVtab->pModule->xRename );
69533   assert( memIsValid(u.co.pName) );
69534   REGISTER_TRACE(pOp->p1, u.co.pName);
69535   assert( u.co.pName->flags & MEM_Str );
69536   rc = u.co.pVtab->pModule->xRename(u.co.pVtab, u.co.pName->z);
69537   importVtabErrMsg(p, u.co.pVtab);
69538   p->expired = 0;
69539 
69540   break;
69541 }
69542 #endif
69543 
69544 #ifndef SQLITE_OMIT_VIRTUALTABLE
69545 /* Opcode: VUpdate P1 P2 P3 P4 *
69546 **
69547 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
69548 ** This opcode invokes the corresponding xUpdate method. P2 values
69549 ** are contiguous memory cells starting at P3 to pass to the xUpdate
69550 ** invocation. The value in register (P3+P2-1) corresponds to the
69551 ** p2th element of the argv array passed to xUpdate.
69552 **
69553 ** The xUpdate method will do a DELETE or an INSERT or both.
69554 ** The argv[0] element (which corresponds to memory cell P3)
69555 ** is the rowid of a row to delete.  If argv[0] is NULL then no
69556 ** deletion occurs.  The argv[1] element is the rowid of the new
69557 ** row.  This can be NULL to have the virtual table select the new
69558 ** rowid for itself.  The subsequent elements in the array are
69559 ** the values of columns in the new row.
69560 **
69561 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
69562 ** a row to delete.
69563 **
69564 ** P1 is a boolean flag. If it is set to true and the xUpdate call
69565 ** is successful, then the value returned by sqlite3_last_insert_rowid()
69566 ** is set to the value of the rowid for the row just inserted.
69567 */
69568 case OP_VUpdate: {
69569 #if 0  /* local variables moved into u.cp */
69570   sqlite3_vtab *pVtab;
69571   sqlite3_module *pModule;
69572   int nArg;
69573   int i;
69574   sqlite_int64 rowid;
69575   Mem **apArg;
69576   Mem *pX;
69577 #endif /* local variables moved into u.cp */
69578 
69579   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
69580        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
69581   );
69582   u.cp.pVtab = pOp->p4.pVtab->pVtab;
69583   u.cp.pModule = (sqlite3_module *)u.cp.pVtab->pModule;
69584   u.cp.nArg = pOp->p2;
69585   assert( pOp->p4type==P4_VTAB );
69586   if( ALWAYS(u.cp.pModule->xUpdate) ){
69587     u8 vtabOnConflict = db->vtabOnConflict;
69588     u.cp.apArg = p->apArg;
69589     u.cp.pX = &aMem[pOp->p3];
69590     for(u.cp.i=0; u.cp.i<u.cp.nArg; u.cp.i++){
69591       assert( memIsValid(u.cp.pX) );
69592       memAboutToChange(p, u.cp.pX);
69593       sqlite3VdbeMemStoreType(u.cp.pX);
69594       u.cp.apArg[u.cp.i] = u.cp.pX;
69595       u.cp.pX++;
69596     }
69597     db->vtabOnConflict = pOp->p5;
69598     rc = u.cp.pModule->xUpdate(u.cp.pVtab, u.cp.nArg, u.cp.apArg, &u.cp.rowid);
69599     db->vtabOnConflict = vtabOnConflict;
69600     importVtabErrMsg(p, u.cp.pVtab);
69601     if( rc==SQLITE_OK && pOp->p1 ){
69602       assert( u.cp.nArg>1 && u.cp.apArg[0] && (u.cp.apArg[0]->flags&MEM_Null) );
69603       db->lastRowid = lastRowid = u.cp.rowid;
69604     }
69605     if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
69606       if( pOp->p5==OE_Ignore ){
69607         rc = SQLITE_OK;
69608       }else{
69609         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
69610       }
69611     }else{
69612       p->nChange++;
69613     }
69614   }
69615   break;
69616 }
69617 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69618 
69619 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
69620 /* Opcode: Pagecount P1 P2 * * *
69621 **
69622 ** Write the current number of pages in database P1 to memory cell P2.
69623 */
69624 case OP_Pagecount: {            /* out2-prerelease */
69625   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
69626   break;
69627 }
69628 #endif
69629 
69630 
69631 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
69632 /* Opcode: MaxPgcnt P1 P2 P3 * *
69633 **
69634 ** Try to set the maximum page count for database P1 to the value in P3.
69635 ** Do not let the maximum page count fall below the current page count and
69636 ** do not change the maximum page count value if P3==0.
69637 **
69638 ** Store the maximum page count after the change in register P2.
69639 */
69640 case OP_MaxPgcnt: {            /* out2-prerelease */
69641   unsigned int newMax;
69642   Btree *pBt;
69643 
69644   pBt = db->aDb[pOp->p1].pBt;
69645   newMax = 0;
69646   if( pOp->p3 ){
69647     newMax = sqlite3BtreeLastPage(pBt);
69648     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
69649   }
69650   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
69651   break;
69652 }
69653 #endif
69654 
69655 
69656 #ifndef SQLITE_OMIT_TRACE
69657 /* Opcode: Trace * * * P4 *
69658 **
69659 ** If tracing is enabled (by the sqlite3_trace()) interface, then
69660 ** the UTF-8 string contained in P4 is emitted on the trace callback.
69661 */
69662 case OP_Trace: {
69663 #if 0  /* local variables moved into u.cq */
69664   char *zTrace;
69665   char *z;
69666 #endif /* local variables moved into u.cq */
69667 
69668   if( db->xTrace && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
69669     u.cq.z = sqlite3VdbeExpandSql(p, u.cq.zTrace);
69670     db->xTrace(db->pTraceArg, u.cq.z);
69671     sqlite3DbFree(db, u.cq.z);
69672   }
69673 #ifdef SQLITE_DEBUG
69674   if( (db->flags & SQLITE_SqlTrace)!=0
69675    && (u.cq.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
69676   ){
69677     sqlite3DebugPrintf("SQL-trace: %s\n", u.cq.zTrace);
69678   }
69679 #endif /* SQLITE_DEBUG */
69680   break;
69681 }
69682 #endif
69683 
69684 
69685 /* Opcode: Noop * * * * *
69686 **
69687 ** Do nothing.  This instruction is often useful as a jump
69688 ** destination.
69689 */
69690 /*
69691 ** The magic Explain opcode are only inserted when explain==2 (which
69692 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
69693 ** This opcode records information from the optimizer.  It is the
69694 ** the same as a no-op.  This opcodesnever appears in a real VM program.
69695 */
69696 default: {          /* This is really OP_Noop and OP_Explain */
69697   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
69698   break;
69699 }
69700 
69701 /*****************************************************************************
69702 ** The cases of the switch statement above this line should all be indented
69703 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
69704 ** readability.  From this point on down, the normal indentation rules are
69705 ** restored.
69706 *****************************************************************************/
69707     }
69708 
69709 #ifdef VDBE_PROFILE
69710     {
69711       u64 elapsed = sqlite3Hwtime() - start;
69712       pOp->cycles += elapsed;
69713       pOp->cnt++;
69714 #if 0
69715         fprintf(stdout, "%10llu ", elapsed);
69716         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
69717 #endif
69718     }
69719 #endif
69720 
69721     /* The following code adds nothing to the actual functionality
69722     ** of the program.  It is only here for testing and debugging.
69723     ** On the other hand, it does burn CPU cycles every time through
69724     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
69725     */
69726 #ifndef NDEBUG
69727     assert( pc>=-1 && pc<p->nOp );
69728 
69729 #ifdef SQLITE_DEBUG
69730     if( p->trace ){
69731       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
69732       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
69733         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
69734       }
69735       if( pOp->opflags & OPFLG_OUT3 ){
69736         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
69737       }
69738     }
69739 #endif  /* SQLITE_DEBUG */
69740 #endif  /* NDEBUG */
69741   }  /* The end of the for(;;) loop the loops through opcodes */
69742 
69743   /* If we reach this point, it means that execution is finished with
69744   ** an error of some kind.
69745   */
69746 vdbe_error_halt:
69747   assert( rc );
69748   p->rc = rc;
69749   testcase( sqlite3GlobalConfig.xLog!=0 );
69750   sqlite3_log(rc, "statement aborts at %d: [%s] %s",
69751                    pc, p->zSql, p->zErrMsg);
69752   sqlite3VdbeHalt(p);
69753   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
69754   rc = SQLITE_ERROR;
69755   if( resetSchemaOnFault>0 ){
69756     sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
69757   }
69758 
69759   /* This is the only way out of this procedure.  We have to
69760   ** release the mutexes on btrees that were acquired at the
69761   ** top. */
69762 vdbe_return:
69763   db->lastRowid = lastRowid;
69764   sqlite3VdbeLeave(p);
69765   return rc;
69766 
69767   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
69768   ** is encountered.
69769   */
69770 too_big:
69771   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
69772   rc = SQLITE_TOOBIG;
69773   goto vdbe_error_halt;
69774 
69775   /* Jump to here if a malloc() fails.
69776   */
69777 no_mem:
69778   db->mallocFailed = 1;
69779   sqlite3SetString(&p->zErrMsg, db, "out of memory");
69780   rc = SQLITE_NOMEM;
69781   goto vdbe_error_halt;
69782 
69783   /* Jump to here for any other kind of fatal error.  The "rc" variable
69784   ** should hold the error number.
69785   */
69786 abort_due_to_error:
69787   assert( p->zErrMsg==0 );
69788   if( db->mallocFailed ) rc = SQLITE_NOMEM;
69789   if( rc!=SQLITE_IOERR_NOMEM ){
69790     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69791   }
69792   goto vdbe_error_halt;
69793 
69794   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
69795   ** flag.
69796   */
69797 abort_due_to_interrupt:
69798   assert( db->u1.isInterrupted );
69799   rc = SQLITE_INTERRUPT;
69800   p->rc = rc;
69801   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
69802   goto vdbe_error_halt;
69803 }
69804 
69805 /************** End of vdbe.c ************************************************/
69806 /************** Begin file vdbeblob.c ****************************************/
69807 /*
69808 ** 2007 May 1
69809 **
69810 ** The author disclaims copyright to this source code.  In place of
69811 ** a legal notice, here is a blessing:
69812 **
69813 **    May you do good and not evil.
69814 **    May you find forgiveness for yourself and forgive others.
69815 **    May you share freely, never taking more than you give.
69816 **
69817 *************************************************************************
69818 **
69819 ** This file contains code used to implement incremental BLOB I/O.
69820 */
69821 
69822 
69823 #ifndef SQLITE_OMIT_INCRBLOB
69824 
69825 /*
69826 ** Valid sqlite3_blob* handles point to Incrblob structures.
69827 */
69828 typedef struct Incrblob Incrblob;
69829 struct Incrblob {
69830   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
69831   int nByte;              /* Size of open blob, in bytes */
69832   int iOffset;            /* Byte offset of blob in cursor data */
69833   int iCol;               /* Table column this handle is open on */
69834   BtCursor *pCsr;         /* Cursor pointing at blob row */
69835   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
69836   sqlite3 *db;            /* The associated database */
69837 };
69838 
69839 
69840 /*
69841 ** This function is used by both blob_open() and blob_reopen(). It seeks
69842 ** the b-tree cursor associated with blob handle p to point to row iRow.
69843 ** If successful, SQLITE_OK is returned and subsequent calls to
69844 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
69845 **
69846 ** If an error occurs, or if the specified row does not exist or does not
69847 ** contain a value of type TEXT or BLOB in the column nominated when the
69848 ** blob handle was opened, then an error code is returned and *pzErr may
69849 ** be set to point to a buffer containing an error message. It is the
69850 ** responsibility of the caller to free the error message buffer using
69851 ** sqlite3DbFree().
69852 **
69853 ** If an error does occur, then the b-tree cursor is closed. All subsequent
69854 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
69855 ** immediately return SQLITE_ABORT.
69856 */
69857 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
69858   int rc;                         /* Error code */
69859   char *zErr = 0;                 /* Error message */
69860   Vdbe *v = (Vdbe *)p->pStmt;
69861 
69862   /* Set the value of the SQL statements only variable to integer iRow.
69863   ** This is done directly instead of using sqlite3_bind_int64() to avoid
69864   ** triggering asserts related to mutexes.
69865   */
69866   assert( v->aVar[0].flags&MEM_Int );
69867   v->aVar[0].u.i = iRow;
69868 
69869   rc = sqlite3_step(p->pStmt);
69870   if( rc==SQLITE_ROW ){
69871     u32 type = v->apCsr[0]->aType[p->iCol];
69872     if( type<12 ){
69873       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
69874           type==0?"null": type==7?"real": "integer"
69875       );
69876       rc = SQLITE_ERROR;
69877       sqlite3_finalize(p->pStmt);
69878       p->pStmt = 0;
69879     }else{
69880       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
69881       p->nByte = sqlite3VdbeSerialTypeLen(type);
69882       p->pCsr =  v->apCsr[0]->pCursor;
69883       sqlite3BtreeEnterCursor(p->pCsr);
69884       sqlite3BtreeCacheOverflow(p->pCsr);
69885       sqlite3BtreeLeaveCursor(p->pCsr);
69886     }
69887   }
69888 
69889   if( rc==SQLITE_ROW ){
69890     rc = SQLITE_OK;
69891   }else if( p->pStmt ){
69892     rc = sqlite3_finalize(p->pStmt);
69893     p->pStmt = 0;
69894     if( rc==SQLITE_OK ){
69895       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
69896       rc = SQLITE_ERROR;
69897     }else{
69898       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
69899     }
69900   }
69901 
69902   assert( rc!=SQLITE_OK || zErr==0 );
69903   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
69904 
69905   *pzErr = zErr;
69906   return rc;
69907 }
69908 
69909 /*
69910 ** Open a blob handle.
69911 */
69912 SQLITE_API int sqlite3_blob_open(
69913   sqlite3* db,            /* The database connection */
69914   const char *zDb,        /* The attached database containing the blob */
69915   const char *zTable,     /* The table containing the blob */
69916   const char *zColumn,    /* The column containing the blob */
69917   sqlite_int64 iRow,      /* The row containing the glob */
69918   int flags,              /* True -> read/write access, false -> read-only */
69919   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
69920 ){
69921   int nAttempt = 0;
69922   int iCol;               /* Index of zColumn in row-record */
69923 
69924   /* This VDBE program seeks a btree cursor to the identified
69925   ** db/table/row entry. The reason for using a vdbe program instead
69926   ** of writing code to use the b-tree layer directly is that the
69927   ** vdbe program will take advantage of the various transaction,
69928   ** locking and error handling infrastructure built into the vdbe.
69929   **
69930   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
69931   ** Code external to the Vdbe then "borrows" the b-tree cursor and
69932   ** uses it to implement the blob_read(), blob_write() and
69933   ** blob_bytes() functions.
69934   **
69935   ** The sqlite3_blob_close() function finalizes the vdbe program,
69936   ** which closes the b-tree cursor and (possibly) commits the
69937   ** transaction.
69938   */
69939   static const VdbeOpList openBlob[] = {
69940     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
69941     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
69942     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
69943 
69944     /* One of the following two instructions is replaced by an OP_Noop. */
69945     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
69946     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
69947 
69948     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
69949     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
69950     {OP_Column, 0, 0, 1},          /* 7  */
69951     {OP_ResultRow, 1, 0, 0},       /* 8  */
69952     {OP_Goto, 0, 5, 0},            /* 9  */
69953     {OP_Close, 0, 0, 0},           /* 10 */
69954     {OP_Halt, 0, 0, 0},            /* 11 */
69955   };
69956 
69957   int rc = SQLITE_OK;
69958   char *zErr = 0;
69959   Table *pTab;
69960   Parse *pParse = 0;
69961   Incrblob *pBlob = 0;
69962 
69963   flags = !!flags;                /* flags = (flags ? 1 : 0); */
69964   *ppBlob = 0;
69965 
69966   sqlite3_mutex_enter(db->mutex);
69967 
69968   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
69969   if( !pBlob ) goto blob_open_out;
69970   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
69971   if( !pParse ) goto blob_open_out;
69972 
69973   do {
69974     memset(pParse, 0, sizeof(Parse));
69975     pParse->db = db;
69976     sqlite3DbFree(db, zErr);
69977     zErr = 0;
69978 
69979     sqlite3BtreeEnterAll(db);
69980     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
69981     if( pTab && IsVirtual(pTab) ){
69982       pTab = 0;
69983       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
69984     }
69985 #ifndef SQLITE_OMIT_VIEW
69986     if( pTab && pTab->pSelect ){
69987       pTab = 0;
69988       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
69989     }
69990 #endif
69991     if( !pTab ){
69992       if( pParse->zErrMsg ){
69993         sqlite3DbFree(db, zErr);
69994         zErr = pParse->zErrMsg;
69995         pParse->zErrMsg = 0;
69996       }
69997       rc = SQLITE_ERROR;
69998       sqlite3BtreeLeaveAll(db);
69999       goto blob_open_out;
70000     }
70001 
70002     /* Now search pTab for the exact column. */
70003     for(iCol=0; iCol<pTab->nCol; iCol++) {
70004       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
70005         break;
70006       }
70007     }
70008     if( iCol==pTab->nCol ){
70009       sqlite3DbFree(db, zErr);
70010       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
70011       rc = SQLITE_ERROR;
70012       sqlite3BtreeLeaveAll(db);
70013       goto blob_open_out;
70014     }
70015 
70016     /* If the value is being opened for writing, check that the
70017     ** column is not indexed, and that it is not part of a foreign key.
70018     ** It is against the rules to open a column to which either of these
70019     ** descriptions applies for writing.  */
70020     if( flags ){
70021       const char *zFault = 0;
70022       Index *pIdx;
70023 #ifndef SQLITE_OMIT_FOREIGN_KEY
70024       if( db->flags&SQLITE_ForeignKeys ){
70025         /* Check that the column is not part of an FK child key definition. It
70026         ** is not necessary to check if it is part of a parent key, as parent
70027         ** key columns must be indexed. The check below will pick up this
70028         ** case.  */
70029         FKey *pFKey;
70030         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
70031           int j;
70032           for(j=0; j<pFKey->nCol; j++){
70033             if( pFKey->aCol[j].iFrom==iCol ){
70034               zFault = "foreign key";
70035             }
70036           }
70037         }
70038       }
70039 #endif
70040       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70041         int j;
70042         for(j=0; j<pIdx->nColumn; j++){
70043           if( pIdx->aiColumn[j]==iCol ){
70044             zFault = "indexed";
70045           }
70046         }
70047       }
70048       if( zFault ){
70049         sqlite3DbFree(db, zErr);
70050         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
70051         rc = SQLITE_ERROR;
70052         sqlite3BtreeLeaveAll(db);
70053         goto blob_open_out;
70054       }
70055     }
70056 
70057     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
70058     assert( pBlob->pStmt || db->mallocFailed );
70059     if( pBlob->pStmt ){
70060       Vdbe *v = (Vdbe *)pBlob->pStmt;
70061       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70062 
70063       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
70064 
70065 
70066       /* Configure the OP_Transaction */
70067       sqlite3VdbeChangeP1(v, 0, iDb);
70068       sqlite3VdbeChangeP2(v, 0, flags);
70069 
70070       /* Configure the OP_VerifyCookie */
70071       sqlite3VdbeChangeP1(v, 1, iDb);
70072       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
70073       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
70074 
70075       /* Make sure a mutex is held on the table to be accessed */
70076       sqlite3VdbeUsesBtree(v, iDb);
70077 
70078       /* Configure the OP_TableLock instruction */
70079 #ifdef SQLITE_OMIT_SHARED_CACHE
70080       sqlite3VdbeChangeToNoop(v, 2);
70081 #else
70082       sqlite3VdbeChangeP1(v, 2, iDb);
70083       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
70084       sqlite3VdbeChangeP3(v, 2, flags);
70085       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
70086 #endif
70087 
70088       /* Remove either the OP_OpenWrite or OpenRead. Set the P2
70089       ** parameter of the other to pTab->tnum.  */
70090       sqlite3VdbeChangeToNoop(v, 4 - flags);
70091       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
70092       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
70093 
70094       /* Configure the number of columns. Configure the cursor to
70095       ** think that the table has one more column than it really
70096       ** does. An OP_Column to retrieve this imaginary column will
70097       ** always return an SQL NULL. This is useful because it means
70098       ** we can invoke OP_Column to fill in the vdbe cursors type
70099       ** and offset cache without causing any IO.
70100       */
70101       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
70102       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
70103       if( !db->mallocFailed ){
70104         pParse->nVar = 1;
70105         pParse->nMem = 1;
70106         pParse->nTab = 1;
70107         sqlite3VdbeMakeReady(v, pParse);
70108       }
70109     }
70110 
70111     pBlob->flags = flags;
70112     pBlob->iCol = iCol;
70113     pBlob->db = db;
70114     sqlite3BtreeLeaveAll(db);
70115     if( db->mallocFailed ){
70116       goto blob_open_out;
70117     }
70118     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
70119     rc = blobSeekToRow(pBlob, iRow, &zErr);
70120   } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
70121 
70122 blob_open_out:
70123   if( rc==SQLITE_OK && db->mallocFailed==0 ){
70124     *ppBlob = (sqlite3_blob *)pBlob;
70125   }else{
70126     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
70127     sqlite3DbFree(db, pBlob);
70128   }
70129   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70130   sqlite3DbFree(db, zErr);
70131   sqlite3StackFree(db, pParse);
70132   rc = sqlite3ApiExit(db, rc);
70133   sqlite3_mutex_leave(db->mutex);
70134   return rc;
70135 }
70136 
70137 /*
70138 ** Close a blob handle that was previously created using
70139 ** sqlite3_blob_open().
70140 */
70141 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
70142   Incrblob *p = (Incrblob *)pBlob;
70143   int rc;
70144   sqlite3 *db;
70145 
70146   if( p ){
70147     db = p->db;
70148     sqlite3_mutex_enter(db->mutex);
70149     rc = sqlite3_finalize(p->pStmt);
70150     sqlite3DbFree(db, p);
70151     sqlite3_mutex_leave(db->mutex);
70152   }else{
70153     rc = SQLITE_OK;
70154   }
70155   return rc;
70156 }
70157 
70158 /*
70159 ** Perform a read or write operation on a blob
70160 */
70161 static int blobReadWrite(
70162   sqlite3_blob *pBlob,
70163   void *z,
70164   int n,
70165   int iOffset,
70166   int (*xCall)(BtCursor*, u32, u32, void*)
70167 ){
70168   int rc;
70169   Incrblob *p = (Incrblob *)pBlob;
70170   Vdbe *v;
70171   sqlite3 *db;
70172 
70173   if( p==0 ) return SQLITE_MISUSE_BKPT;
70174   db = p->db;
70175   sqlite3_mutex_enter(db->mutex);
70176   v = (Vdbe*)p->pStmt;
70177 
70178   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
70179     /* Request is out of range. Return a transient error. */
70180     rc = SQLITE_ERROR;
70181     sqlite3Error(db, SQLITE_ERROR, 0);
70182   }else if( v==0 ){
70183     /* If there is no statement handle, then the blob-handle has
70184     ** already been invalidated. Return SQLITE_ABORT in this case.
70185     */
70186     rc = SQLITE_ABORT;
70187   }else{
70188     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
70189     ** returned, clean-up the statement handle.
70190     */
70191     assert( db == v->db );
70192     sqlite3BtreeEnterCursor(p->pCsr);
70193     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
70194     sqlite3BtreeLeaveCursor(p->pCsr);
70195     if( rc==SQLITE_ABORT ){
70196       sqlite3VdbeFinalize(v);
70197       p->pStmt = 0;
70198     }else{
70199       db->errCode = rc;
70200       v->rc = rc;
70201     }
70202   }
70203   rc = sqlite3ApiExit(db, rc);
70204   sqlite3_mutex_leave(db->mutex);
70205   return rc;
70206 }
70207 
70208 /*
70209 ** Read data from a blob handle.
70210 */
70211 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
70212   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
70213 }
70214 
70215 /*
70216 ** Write data to a blob handle.
70217 */
70218 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
70219   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
70220 }
70221 
70222 /*
70223 ** Query a blob handle for the size of the data.
70224 **
70225 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
70226 ** so no mutex is required for access.
70227 */
70228 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
70229   Incrblob *p = (Incrblob *)pBlob;
70230   return (p && p->pStmt) ? p->nByte : 0;
70231 }
70232 
70233 /*
70234 ** Move an existing blob handle to point to a different row of the same
70235 ** database table.
70236 **
70237 ** If an error occurs, or if the specified row does not exist or does not
70238 ** contain a blob or text value, then an error code is returned and the
70239 ** database handle error code and message set. If this happens, then all
70240 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
70241 ** immediately return SQLITE_ABORT.
70242 */
70243 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
70244   int rc;
70245   Incrblob *p = (Incrblob *)pBlob;
70246   sqlite3 *db;
70247 
70248   if( p==0 ) return SQLITE_MISUSE_BKPT;
70249   db = p->db;
70250   sqlite3_mutex_enter(db->mutex);
70251 
70252   if( p->pStmt==0 ){
70253     /* If there is no statement handle, then the blob-handle has
70254     ** already been invalidated. Return SQLITE_ABORT in this case.
70255     */
70256     rc = SQLITE_ABORT;
70257   }else{
70258     char *zErr;
70259     rc = blobSeekToRow(p, iRow, &zErr);
70260     if( rc!=SQLITE_OK ){
70261       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
70262       sqlite3DbFree(db, zErr);
70263     }
70264     assert( rc!=SQLITE_SCHEMA );
70265   }
70266 
70267   rc = sqlite3ApiExit(db, rc);
70268   assert( rc==SQLITE_OK || p->pStmt==0 );
70269   sqlite3_mutex_leave(db->mutex);
70270   return rc;
70271 }
70272 
70273 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
70274 
70275 /************** End of vdbeblob.c ********************************************/
70276 /************** Begin file vdbesort.c ****************************************/
70277 /*
70278 ** 2011 July 9
70279 **
70280 ** The author disclaims copyright to this source code.  In place of
70281 ** a legal notice, here is a blessing:
70282 **
70283 **    May you do good and not evil.
70284 **    May you find forgiveness for yourself and forgive others.
70285 **    May you share freely, never taking more than you give.
70286 **
70287 *************************************************************************
70288 ** This file contains code for the VdbeSorter object, used in concert with
70289 ** a VdbeCursor to sort large numbers of keys (as may be required, for
70290 ** example, by CREATE INDEX statements on tables too large to fit in main
70291 ** memory).
70292 */
70293 
70294 
70295 #ifndef SQLITE_OMIT_MERGE_SORT
70296 
70297 typedef struct VdbeSorterIter VdbeSorterIter;
70298 typedef struct SorterRecord SorterRecord;
70299 
70300 /*
70301 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
70302 **
70303 ** As keys are added to the sorter, they are written to disk in a series
70304 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
70305 ** the same as the cache-size allowed for temporary databases. In order
70306 ** to allow the caller to extract keys from the sorter in sorted order,
70307 ** all PMAs currently stored on disk must be merged together. This comment
70308 ** describes the data structure used to do so. The structure supports
70309 ** merging any number of arrays in a single pass with no redundant comparison
70310 ** operations.
70311 **
70312 ** The aIter[] array contains an iterator for each of the PMAs being merged.
70313 ** An aIter[] iterator either points to a valid key or else is at EOF. For
70314 ** the purposes of the paragraphs below, we assume that the array is actually
70315 ** N elements in size, where N is the smallest power of 2 greater to or equal
70316 ** to the number of iterators being merged. The extra aIter[] elements are
70317 ** treated as if they are empty (always at EOF).
70318 **
70319 ** The aTree[] array is also N elements in size. The value of N is stored in
70320 ** the VdbeSorter.nTree variable.
70321 **
70322 ** The final (N/2) elements of aTree[] contain the results of comparing
70323 ** pairs of iterator keys together. Element i contains the result of
70324 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
70325 ** aTree element is set to the index of it.
70326 **
70327 ** For the purposes of this comparison, EOF is considered greater than any
70328 ** other key value. If the keys are equal (only possible with two EOF
70329 ** values), it doesn't matter which index is stored.
70330 **
70331 ** The (N/4) elements of aTree[] that preceed the final (N/2) described
70332 ** above contains the index of the smallest of each block of 4 iterators.
70333 ** And so on. So that aTree[1] contains the index of the iterator that
70334 ** currently points to the smallest key value. aTree[0] is unused.
70335 **
70336 ** Example:
70337 **
70338 **     aIter[0] -> Banana
70339 **     aIter[1] -> Feijoa
70340 **     aIter[2] -> Elderberry
70341 **     aIter[3] -> Currant
70342 **     aIter[4] -> Grapefruit
70343 **     aIter[5] -> Apple
70344 **     aIter[6] -> Durian
70345 **     aIter[7] -> EOF
70346 **
70347 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
70348 **
70349 ** The current element is "Apple" (the value of the key indicated by
70350 ** iterator 5). When the Next() operation is invoked, iterator 5 will
70351 ** be advanced to the next key in its segment. Say the next key is
70352 ** "Eggplant":
70353 **
70354 **     aIter[5] -> Eggplant
70355 **
70356 ** The contents of aTree[] are updated first by comparing the new iterator
70357 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
70358 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
70359 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
70360 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
70361 ** so the value written into element 1 of the array is 0. As follows:
70362 **
70363 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
70364 **
70365 ** In other words, each time we advance to the next sorter element, log2(N)
70366 ** key comparison operations are required, where N is the number of segments
70367 ** being merged (rounded up to the next power of 2).
70368 */
70369 struct VdbeSorter {
70370   int nInMemory;                  /* Current size of pRecord list as PMA */
70371   int nTree;                      /* Used size of aTree/aIter (power of 2) */
70372   VdbeSorterIter *aIter;          /* Array of iterators to merge */
70373   int *aTree;                     /* Current state of incremental merge */
70374   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
70375   i64 iReadOff;                   /* Current read offset within file pTemp1 */
70376   sqlite3_file *pTemp1;           /* PMA file 1 */
70377   int nPMA;                       /* Number of PMAs stored in pTemp1 */
70378   SorterRecord *pRecord;          /* Head of in-memory record list */
70379   int mnPmaSize;                  /* Minimum PMA size, in bytes */
70380   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
70381   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
70382 };
70383 
70384 /*
70385 ** The following type is an iterator for a PMA. It caches the current key in
70386 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
70387 */
70388 struct VdbeSorterIter {
70389   i64 iReadOff;                   /* Current read offset */
70390   i64 iEof;                       /* 1 byte past EOF for this iterator */
70391   sqlite3_file *pFile;            /* File iterator is reading from */
70392   int nAlloc;                     /* Bytes of space at aAlloc */
70393   u8 *aAlloc;                     /* Allocated space */
70394   int nKey;                       /* Number of bytes in key */
70395   u8 *aKey;                       /* Pointer to current key */
70396 };
70397 
70398 /*
70399 ** A structure to store a single record. All in-memory records are connected
70400 ** together into a linked list headed at VdbeSorter.pRecord using the
70401 ** SorterRecord.pNext pointer.
70402 */
70403 struct SorterRecord {
70404   void *pVal;
70405   int nVal;
70406   SorterRecord *pNext;
70407 };
70408 
70409 /* Minimum allowable value for the VdbeSorter.nWorking variable */
70410 #define SORTER_MIN_WORKING 10
70411 
70412 /* Maximum number of segments to merge in a single pass. */
70413 #define SORTER_MAX_MERGE_COUNT 16
70414 
70415 /*
70416 ** Free all memory belonging to the VdbeSorterIter object passed as the second
70417 ** argument. All structure fields are set to zero before returning.
70418 */
70419 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
70420   sqlite3DbFree(db, pIter->aAlloc);
70421   memset(pIter, 0, sizeof(VdbeSorterIter));
70422 }
70423 
70424 /*
70425 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
70426 ** no error occurs, or an SQLite error code if one does.
70427 */
70428 static int vdbeSorterIterNext(
70429   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
70430   VdbeSorterIter *pIter           /* Iterator to advance */
70431 ){
70432   int rc;                         /* Return Code */
70433   int nRead;                      /* Number of bytes read */
70434   int nRec = 0;                   /* Size of record in bytes */
70435   int iOff = 0;                   /* Size of serialized size varint in bytes */
70436 
70437   assert( pIter->iEof>=pIter->iReadOff );
70438   if( pIter->iEof-pIter->iReadOff>5 ){
70439     nRead = 5;
70440   }else{
70441     nRead = (int)(pIter->iEof - pIter->iReadOff);
70442   }
70443   if( nRead<=0 ){
70444     /* This is an EOF condition */
70445     vdbeSorterIterZero(db, pIter);
70446     return SQLITE_OK;
70447   }
70448 
70449   rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
70450   if( rc==SQLITE_OK ){
70451     iOff = getVarint32(pIter->aAlloc, nRec);
70452     if( (iOff+nRec)>nRead ){
70453       int nRead2;                   /* Number of extra bytes to read */
70454       if( (iOff+nRec)>pIter->nAlloc ){
70455         int nNew = pIter->nAlloc*2;
70456         while( (iOff+nRec)>nNew ) nNew = nNew*2;
70457         pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
70458         if( !pIter->aAlloc ) return SQLITE_NOMEM;
70459         pIter->nAlloc = nNew;
70460       }
70461 
70462       nRead2 = iOff + nRec - nRead;
70463       rc = sqlite3OsRead(
70464           pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
70465       );
70466     }
70467   }
70468 
70469   assert( rc!=SQLITE_OK || nRec>0 );
70470   pIter->iReadOff += iOff+nRec;
70471   pIter->nKey = nRec;
70472   pIter->aKey = &pIter->aAlloc[iOff];
70473   return rc;
70474 }
70475 
70476 /*
70477 ** Write a single varint, value iVal, to file-descriptor pFile. Return
70478 ** SQLITE_OK if successful, or an SQLite error code if some error occurs.
70479 **
70480 ** The value of *piOffset when this function is called is used as the byte
70481 ** offset in file pFile to write to. Before returning, *piOffset is
70482 ** incremented by the number of bytes written.
70483 */
70484 static int vdbeSorterWriteVarint(
70485   sqlite3_file *pFile,            /* File to write to */
70486   i64 iVal,                       /* Value to write as a varint */
70487   i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
70488 ){
70489   u8 aVarint[9];                  /* Buffer large enough for a varint */
70490   int nVarint;                    /* Number of used bytes in varint */
70491   int rc;                         /* Result of write() call */
70492 
70493   nVarint = sqlite3PutVarint(aVarint, iVal);
70494   rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
70495   *piOffset += nVarint;
70496 
70497   return rc;
70498 }
70499 
70500 /*
70501 ** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
70502 ** successful, or an SQLite error code if some error occurs.
70503 **
70504 ** The value of *piOffset when this function is called is used as the
70505 ** byte offset in file pFile from whence to read the varint. If successful
70506 ** (i.e. if no IO error occurs), then *piOffset is set to the offset of
70507 ** the first byte past the end of the varint before returning. *piVal is
70508 ** set to the integer value read. If an error occurs, the final values of
70509 ** both *piOffset and *piVal are undefined.
70510 */
70511 static int vdbeSorterReadVarint(
70512   sqlite3_file *pFile,            /* File to read from */
70513   i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
70514   i64 *piVal                      /* OUT: Value read from file */
70515 ){
70516   u8 aVarint[9];                  /* Buffer large enough for a varint */
70517   i64 iOff = *piOffset;           /* Offset in file to read from */
70518   int rc;                         /* Return code */
70519 
70520   rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
70521   if( rc==SQLITE_OK ){
70522     *piOffset += getVarint(aVarint, (u64 *)piVal);
70523   }
70524 
70525   return rc;
70526 }
70527 
70528 /*
70529 ** Initialize iterator pIter to scan through the PMA stored in file pFile
70530 ** starting at offset iStart and ending at offset iEof-1. This function
70531 ** leaves the iterator pointing to the first key in the PMA (or EOF if the
70532 ** PMA is empty).
70533 */
70534 static int vdbeSorterIterInit(
70535   sqlite3 *db,                    /* Database handle */
70536   VdbeSorter *pSorter,            /* Sorter object */
70537   i64 iStart,                     /* Start offset in pFile */
70538   VdbeSorterIter *pIter,          /* Iterator to populate */
70539   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
70540 ){
70541   int rc;
70542 
70543   assert( pSorter->iWriteOff>iStart );
70544   assert( pIter->aAlloc==0 );
70545   pIter->pFile = pSorter->pTemp1;
70546   pIter->iReadOff = iStart;
70547   pIter->nAlloc = 128;
70548   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
70549   if( !pIter->aAlloc ){
70550     rc = SQLITE_NOMEM;
70551   }else{
70552     i64 nByte;                         /* Total size of PMA in bytes */
70553     rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
70554     *pnByte += nByte;
70555     pIter->iEof = pIter->iReadOff + nByte;
70556   }
70557   if( rc==SQLITE_OK ){
70558     rc = vdbeSorterIterNext(db, pIter);
70559   }
70560   return rc;
70561 }
70562 
70563 
70564 /*
70565 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
70566 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
70567 ** used by the comparison. If an error occurs, return an SQLite error code.
70568 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
70569 ** value, depending on whether key1 is smaller, equal to or larger than key2.
70570 **
70571 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
70572 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
70573 ** is true and key1 contains even a single NULL value, it is considered to
70574 ** be less than key2. Even if key2 also contains NULL values.
70575 **
70576 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
70577 ** has been allocated and contains an unpacked record that is used as key2.
70578 */
70579 static void vdbeSorterCompare(
70580   VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
70581   int bOmitRowid,                 /* Ignore rowid field at end of keys */
70582   void *pKey1, int nKey1,         /* Left side of comparison */
70583   void *pKey2, int nKey2,         /* Right side of comparison */
70584   int *pRes                       /* OUT: Result of comparison */
70585 ){
70586   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
70587   VdbeSorter *pSorter = pCsr->pSorter;
70588   UnpackedRecord *r2 = pSorter->pUnpacked;
70589   int i;
70590 
70591   if( pKey2 ){
70592     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
70593   }
70594 
70595   if( bOmitRowid ){
70596     r2->nField = pKeyInfo->nField;
70597     assert( r2->nField>0 );
70598     for(i=0; i<r2->nField; i++){
70599       if( r2->aMem[i].flags & MEM_Null ){
70600         *pRes = -1;
70601         return;
70602       }
70603     }
70604     r2->flags |= UNPACKED_PREFIX_MATCH;
70605   }
70606 
70607   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
70608 }
70609 
70610 /*
70611 ** This function is called to compare two iterator keys when merging
70612 ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
70613 ** value to recalculate.
70614 */
70615 static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
70616   VdbeSorter *pSorter = pCsr->pSorter;
70617   int i1;
70618   int i2;
70619   int iRes;
70620   VdbeSorterIter *p1;
70621   VdbeSorterIter *p2;
70622 
70623   assert( iOut<pSorter->nTree && iOut>0 );
70624 
70625   if( iOut>=(pSorter->nTree/2) ){
70626     i1 = (iOut - pSorter->nTree/2) * 2;
70627     i2 = i1 + 1;
70628   }else{
70629     i1 = pSorter->aTree[iOut*2];
70630     i2 = pSorter->aTree[iOut*2+1];
70631   }
70632 
70633   p1 = &pSorter->aIter[i1];
70634   p2 = &pSorter->aIter[i2];
70635 
70636   if( p1->pFile==0 ){
70637     iRes = i2;
70638   }else if( p2->pFile==0 ){
70639     iRes = i1;
70640   }else{
70641     int res;
70642     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
70643     vdbeSorterCompare(
70644         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
70645     );
70646     if( res<=0 ){
70647       iRes = i1;
70648     }else{
70649       iRes = i2;
70650     }
70651   }
70652 
70653   pSorter->aTree[iOut] = iRes;
70654   return SQLITE_OK;
70655 }
70656 
70657 /*
70658 ** Initialize the temporary index cursor just opened as a sorter cursor.
70659 */
70660 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
70661   int pgsz;                       /* Page size of main database */
70662   int mxCache;                    /* Cache size */
70663   VdbeSorter *pSorter;            /* The new sorter */
70664   char *d;                        /* Dummy */
70665 
70666   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
70667   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
70668   if( pSorter==0 ){
70669     return SQLITE_NOMEM;
70670   }
70671 
70672   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
70673   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
70674   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
70675 
70676   if( !sqlite3TempInMemory(db) ){
70677     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
70678     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
70679     mxCache = db->aDb[0].pSchema->cache_size;
70680     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
70681     pSorter->mxPmaSize = mxCache * pgsz;
70682   }
70683 
70684   return SQLITE_OK;
70685 }
70686 
70687 /*
70688 ** Free the list of sorted records starting at pRecord.
70689 */
70690 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
70691   SorterRecord *p;
70692   SorterRecord *pNext;
70693   for(p=pRecord; p; p=pNext){
70694     pNext = p->pNext;
70695     sqlite3DbFree(db, p);
70696   }
70697 }
70698 
70699 /*
70700 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
70701 */
70702 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
70703   VdbeSorter *pSorter = pCsr->pSorter;
70704   if( pSorter ){
70705     if( pSorter->aIter ){
70706       int i;
70707       for(i=0; i<pSorter->nTree; i++){
70708         vdbeSorterIterZero(db, &pSorter->aIter[i]);
70709       }
70710       sqlite3DbFree(db, pSorter->aIter);
70711     }
70712     if( pSorter->pTemp1 ){
70713       sqlite3OsCloseFree(pSorter->pTemp1);
70714     }
70715     vdbeSorterRecordFree(db, pSorter->pRecord);
70716     sqlite3DbFree(db, pSorter->pUnpacked);
70717     sqlite3DbFree(db, pSorter);
70718     pCsr->pSorter = 0;
70719   }
70720 }
70721 
70722 /*
70723 ** Allocate space for a file-handle and open a temporary file. If successful,
70724 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
70725 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
70726 */
70727 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
70728   int dummy;
70729   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
70730       SQLITE_OPEN_TEMP_JOURNAL |
70731       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
70732       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
70733   );
70734 }
70735 
70736 /*
70737 ** Merge the two sorted lists p1 and p2 into a single list.
70738 ** Set *ppOut to the head of the new list.
70739 */
70740 static void vdbeSorterMerge(
70741   VdbeCursor *pCsr,               /* For pKeyInfo */
70742   SorterRecord *p1,               /* First list to merge */
70743   SorterRecord *p2,               /* Second list to merge */
70744   SorterRecord **ppOut            /* OUT: Head of merged list */
70745 ){
70746   SorterRecord *pFinal = 0;
70747   SorterRecord **pp = &pFinal;
70748   void *pVal2 = p2 ? p2->pVal : 0;
70749 
70750   while( p1 && p2 ){
70751     int res;
70752     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
70753     if( res<=0 ){
70754       *pp = p1;
70755       pp = &p1->pNext;
70756       p1 = p1->pNext;
70757       pVal2 = 0;
70758     }else{
70759       *pp = p2;
70760        pp = &p2->pNext;
70761       p2 = p2->pNext;
70762       if( p2==0 ) break;
70763       pVal2 = p2->pVal;
70764     }
70765   }
70766   *pp = p1 ? p1 : p2;
70767   *ppOut = pFinal;
70768 }
70769 
70770 /*
70771 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
70772 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
70773 ** occurs.
70774 */
70775 static int vdbeSorterSort(VdbeCursor *pCsr){
70776   int i;
70777   SorterRecord **aSlot;
70778   SorterRecord *p;
70779   VdbeSorter *pSorter = pCsr->pSorter;
70780 
70781   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
70782   if( !aSlot ){
70783     return SQLITE_NOMEM;
70784   }
70785 
70786   p = pSorter->pRecord;
70787   while( p ){
70788     SorterRecord *pNext = p->pNext;
70789     p->pNext = 0;
70790     for(i=0; aSlot[i]; i++){
70791       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70792       aSlot[i] = 0;
70793     }
70794     aSlot[i] = p;
70795     p = pNext;
70796   }
70797 
70798   p = 0;
70799   for(i=0; i<64; i++){
70800     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
70801   }
70802   pSorter->pRecord = p;
70803 
70804   sqlite3_free(aSlot);
70805   return SQLITE_OK;
70806 }
70807 
70808 
70809 /*
70810 ** Write the current contents of the in-memory linked-list to a PMA. Return
70811 ** SQLITE_OK if successful, or an SQLite error code otherwise.
70812 **
70813 ** The format of a PMA is:
70814 **
70815 **     * A varint. This varint contains the total number of bytes of content
70816 **       in the PMA (not including the varint itself).
70817 **
70818 **     * One or more records packed end-to-end in order of ascending keys.
70819 **       Each record consists of a varint followed by a blob of data (the
70820 **       key). The varint is the number of bytes in the blob of data.
70821 */
70822 static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
70823   int rc = SQLITE_OK;             /* Return code */
70824   VdbeSorter *pSorter = pCsr->pSorter;
70825 
70826   if( pSorter->nInMemory==0 ){
70827     assert( pSorter->pRecord==0 );
70828     return rc;
70829   }
70830 
70831   rc = vdbeSorterSort(pCsr);
70832 
70833   /* If the first temporary PMA file has not been opened, open it now. */
70834   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
70835     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
70836     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
70837     assert( pSorter->iWriteOff==0 );
70838     assert( pSorter->nPMA==0 );
70839   }
70840 
70841   if( rc==SQLITE_OK ){
70842     i64 iOff = pSorter->iWriteOff;
70843     SorterRecord *p;
70844     SorterRecord *pNext = 0;
70845     static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
70846 
70847     pSorter->nPMA++;
70848     rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
70849     for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
70850       pNext = p->pNext;
70851       rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
70852 
70853       if( rc==SQLITE_OK ){
70854         rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
70855         iOff += p->nVal;
70856       }
70857 
70858       sqlite3DbFree(db, p);
70859     }
70860 
70861     /* This assert verifies that unless an error has occurred, the size of
70862     ** the PMA on disk is the same as the expected size stored in
70863     ** pSorter->nInMemory. */
70864     assert( rc!=SQLITE_OK || pSorter->nInMemory==(
70865           iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
70866     ));
70867 
70868     pSorter->iWriteOff = iOff;
70869     if( rc==SQLITE_OK ){
70870       /* Terminate each file with 8 extra bytes so that from any offset
70871       ** in the file we can always read 9 bytes without a SHORT_READ error */
70872       rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
70873     }
70874     pSorter->pRecord = p;
70875   }
70876 
70877   return rc;
70878 }
70879 
70880 /*
70881 ** Add a record to the sorter.
70882 */
70883 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
70884   sqlite3 *db,                    /* Database handle */
70885   VdbeCursor *pCsr,               /* Sorter cursor */
70886   Mem *pVal                       /* Memory cell containing record */
70887 ){
70888   VdbeSorter *pSorter = pCsr->pSorter;
70889   int rc = SQLITE_OK;             /* Return Code */
70890   SorterRecord *pNew;             /* New list element */
70891 
70892   assert( pSorter );
70893   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
70894 
70895   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
70896   if( pNew==0 ){
70897     rc = SQLITE_NOMEM;
70898   }else{
70899     pNew->pVal = (void *)&pNew[1];
70900     memcpy(pNew->pVal, pVal->z, pVal->n);
70901     pNew->nVal = pVal->n;
70902     pNew->pNext = pSorter->pRecord;
70903     pSorter->pRecord = pNew;
70904   }
70905 
70906   /* See if the contents of the sorter should now be written out. They
70907   ** are written out when either of the following are true:
70908   **
70909   **   * The total memory allocated for the in-memory list is greater
70910   **     than (page-size * cache-size), or
70911   **
70912   **   * The total memory allocated for the in-memory list is greater
70913   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
70914   */
70915   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
70916         (pSorter->nInMemory>pSorter->mxPmaSize)
70917      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
70918   )){
70919     rc = vdbeSorterListToPMA(db, pCsr);
70920     pSorter->nInMemory = 0;
70921   }
70922 
70923   return rc;
70924 }
70925 
70926 /*
70927 ** Helper function for sqlite3VdbeSorterRewind().
70928 */
70929 static int vdbeSorterInitMerge(
70930   sqlite3 *db,                    /* Database handle */
70931   VdbeCursor *pCsr,               /* Cursor handle for this sorter */
70932   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
70933 ){
70934   VdbeSorter *pSorter = pCsr->pSorter;
70935   int rc = SQLITE_OK;             /* Return code */
70936   int i;                          /* Used to iterator through aIter[] */
70937   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
70938 
70939   /* Initialize the iterators. */
70940   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
70941     VdbeSorterIter *pIter = &pSorter->aIter[i];
70942     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
70943     pSorter->iReadOff = pIter->iEof;
70944     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
70945     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
70946   }
70947 
70948   /* Initialize the aTree[] array. */
70949   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
70950     rc = vdbeSorterDoCompare(pCsr, i);
70951   }
70952 
70953   *pnByte = nByte;
70954   return rc;
70955 }
70956 
70957 /*
70958 ** Once the sorter has been populated, this function is called to prepare
70959 ** for iterating through its contents in sorted order.
70960 */
70961 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
70962   VdbeSorter *pSorter = pCsr->pSorter;
70963   int rc;                         /* Return code */
70964   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
70965   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
70966   int nIter;                      /* Number of iterators used */
70967   int nByte;                      /* Bytes of space required for aIter/aTree */
70968   int N = 2;                      /* Power of 2 >= nIter */
70969 
70970   assert( pSorter );
70971 
70972   /* If no data has been written to disk, then do not do so now. Instead,
70973   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
70974   ** from the in-memory list.  */
70975   if( pSorter->nPMA==0 ){
70976     *pbEof = !pSorter->pRecord;
70977     assert( pSorter->aTree==0 );
70978     return vdbeSorterSort(pCsr);
70979   }
70980 
70981   /* Write the current b-tree to a PMA. Close the b-tree cursor. */
70982   rc = vdbeSorterListToPMA(db, pCsr);
70983   if( rc!=SQLITE_OK ) return rc;
70984 
70985   /* Allocate space for aIter[] and aTree[]. */
70986   nIter = pSorter->nPMA;
70987   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
70988   assert( nIter>0 );
70989   while( N<nIter ) N += N;
70990   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
70991   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
70992   if( !pSorter->aIter ) return SQLITE_NOMEM;
70993   pSorter->aTree = (int *)&pSorter->aIter[N];
70994   pSorter->nTree = N;
70995 
70996   do {
70997     int iNew;                     /* Index of new, merged, PMA */
70998 
70999     for(iNew=0;
71000         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
71001         iNew++
71002     ){
71003       i64 nWrite;                 /* Number of bytes in new PMA */
71004 
71005       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
71006       ** initialize an iterator for each of them and break out of the loop.
71007       ** These iterators will be incrementally merged as the VDBE layer calls
71008       ** sqlite3VdbeSorterNext().
71009       **
71010       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
71011       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
71012       ** are merged into a single PMA that is written to file pTemp2.
71013       */
71014       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
71015       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
71016       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71017         break;
71018       }
71019 
71020       /* Open the second temp file, if it is not already open. */
71021       if( pTemp2==0 ){
71022         assert( iWrite2==0 );
71023         rc = vdbeSorterOpenTempFile(db, &pTemp2);
71024       }
71025 
71026       if( rc==SQLITE_OK ){
71027         rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
71028       }
71029 
71030       if( rc==SQLITE_OK ){
71031         int bEof = 0;
71032         while( rc==SQLITE_OK && bEof==0 ){
71033           int nToWrite;
71034           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71035           assert( pIter->pFile );
71036           nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
71037           rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
71038           iWrite2 += nToWrite;
71039           if( rc==SQLITE_OK ){
71040             rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
71041           }
71042         }
71043       }
71044     }
71045 
71046     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
71047       break;
71048     }else{
71049       sqlite3_file *pTmp = pSorter->pTemp1;
71050       pSorter->nPMA = iNew;
71051       pSorter->pTemp1 = pTemp2;
71052       pTemp2 = pTmp;
71053       pSorter->iWriteOff = iWrite2;
71054       pSorter->iReadOff = 0;
71055       iWrite2 = 0;
71056     }
71057   }while( rc==SQLITE_OK );
71058 
71059   if( pTemp2 ){
71060     sqlite3OsCloseFree(pTemp2);
71061   }
71062   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71063   return rc;
71064 }
71065 
71066 /*
71067 ** Advance to the next element in the sorter.
71068 */
71069 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
71070   VdbeSorter *pSorter = pCsr->pSorter;
71071   int rc;                         /* Return code */
71072 
71073   if( pSorter->aTree ){
71074     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
71075     int i;                        /* Index of aTree[] to recalculate */
71076 
71077     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
71078     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
71079       rc = vdbeSorterDoCompare(pCsr, i);
71080     }
71081 
71082     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
71083   }else{
71084     SorterRecord *pFree = pSorter->pRecord;
71085     pSorter->pRecord = pFree->pNext;
71086     pFree->pNext = 0;
71087     vdbeSorterRecordFree(db, pFree);
71088     *pbEof = !pSorter->pRecord;
71089     rc = SQLITE_OK;
71090   }
71091   return rc;
71092 }
71093 
71094 /*
71095 ** Return a pointer to a buffer owned by the sorter that contains the
71096 ** current key.
71097 */
71098 static void *vdbeSorterRowkey(
71099   VdbeSorter *pSorter,            /* Sorter object */
71100   int *pnKey                      /* OUT: Size of current key in bytes */
71101 ){
71102   void *pKey;
71103   if( pSorter->aTree ){
71104     VdbeSorterIter *pIter;
71105     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
71106     *pnKey = pIter->nKey;
71107     pKey = pIter->aKey;
71108   }else{
71109     *pnKey = pSorter->pRecord->nVal;
71110     pKey = pSorter->pRecord->pVal;
71111   }
71112   return pKey;
71113 }
71114 
71115 /*
71116 ** Copy the current sorter key into the memory cell pOut.
71117 */
71118 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
71119   VdbeSorter *pSorter = pCsr->pSorter;
71120   void *pKey; int nKey;           /* Sorter key to copy into pOut */
71121 
71122   pKey = vdbeSorterRowkey(pSorter, &nKey);
71123   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
71124     return SQLITE_NOMEM;
71125   }
71126   pOut->n = nKey;
71127   MemSetTypeFlag(pOut, MEM_Blob);
71128   memcpy(pOut->z, pKey, nKey);
71129 
71130   return SQLITE_OK;
71131 }
71132 
71133 /*
71134 ** Compare the key in memory cell pVal with the key that the sorter cursor
71135 ** passed as the first argument currently points to. For the purposes of
71136 ** the comparison, ignore the rowid field at the end of each record.
71137 **
71138 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
71139 ** Otherwise, set *pRes to a negative, zero or positive value if the
71140 ** key in pVal is smaller than, equal to or larger than the current sorter
71141 ** key.
71142 */
71143 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
71144   VdbeCursor *pCsr,               /* Sorter cursor */
71145   Mem *pVal,                      /* Value to compare to current sorter key */
71146   int *pRes                       /* OUT: Result of comparison */
71147 ){
71148   VdbeSorter *pSorter = pCsr->pSorter;
71149   void *pKey; int nKey;           /* Sorter key to compare pVal with */
71150 
71151   pKey = vdbeSorterRowkey(pSorter, &nKey);
71152   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
71153   return SQLITE_OK;
71154 }
71155 
71156 #endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
71157 
71158 /************** End of vdbesort.c ********************************************/
71159 /************** Begin file journal.c *****************************************/
71160 /*
71161 ** 2007 August 22
71162 **
71163 ** The author disclaims copyright to this source code.  In place of
71164 ** a legal notice, here is a blessing:
71165 **
71166 **    May you do good and not evil.
71167 **    May you find forgiveness for yourself and forgive others.
71168 **    May you share freely, never taking more than you give.
71169 **
71170 *************************************************************************
71171 **
71172 ** This file implements a special kind of sqlite3_file object used
71173 ** by SQLite to create journal files if the atomic-write optimization
71174 ** is enabled.
71175 **
71176 ** The distinctive characteristic of this sqlite3_file is that the
71177 ** actual on disk file is created lazily. When the file is created,
71178 ** the caller specifies a buffer size for an in-memory buffer to
71179 ** be used to service read() and write() requests. The actual file
71180 ** on disk is not created or populated until either:
71181 **
71182 **   1) The in-memory representation grows too large for the allocated
71183 **      buffer, or
71184 **   2) The sqlite3JournalCreate() function is called.
71185 */
71186 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
71187 
71188 
71189 /*
71190 ** A JournalFile object is a subclass of sqlite3_file used by
71191 ** as an open file handle for journal files.
71192 */
71193 struct JournalFile {
71194   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
71195   int nBuf;                       /* Size of zBuf[] in bytes */
71196   char *zBuf;                     /* Space to buffer journal writes */
71197   int iSize;                      /* Amount of zBuf[] currently used */
71198   int flags;                      /* xOpen flags */
71199   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
71200   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
71201   const char *zJournal;           /* Name of the journal file */
71202 };
71203 typedef struct JournalFile JournalFile;
71204 
71205 /*
71206 ** If it does not already exists, create and populate the on-disk file
71207 ** for JournalFile p.
71208 */
71209 static int createFile(JournalFile *p){
71210   int rc = SQLITE_OK;
71211   if( !p->pReal ){
71212     sqlite3_file *pReal = (sqlite3_file *)&p[1];
71213     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
71214     if( rc==SQLITE_OK ){
71215       p->pReal = pReal;
71216       if( p->iSize>0 ){
71217         assert(p->iSize<=p->nBuf);
71218         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
71219       }
71220     }
71221   }
71222   return rc;
71223 }
71224 
71225 /*
71226 ** Close the file.
71227 */
71228 static int jrnlClose(sqlite3_file *pJfd){
71229   JournalFile *p = (JournalFile *)pJfd;
71230   if( p->pReal ){
71231     sqlite3OsClose(p->pReal);
71232   }
71233   sqlite3_free(p->zBuf);
71234   return SQLITE_OK;
71235 }
71236 
71237 /*
71238 ** Read data from the file.
71239 */
71240 static int jrnlRead(
71241   sqlite3_file *pJfd,    /* The journal file from which to read */
71242   void *zBuf,            /* Put the results here */
71243   int iAmt,              /* Number of bytes to read */
71244   sqlite_int64 iOfst     /* Begin reading at this offset */
71245 ){
71246   int rc = SQLITE_OK;
71247   JournalFile *p = (JournalFile *)pJfd;
71248   if( p->pReal ){
71249     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
71250   }else if( (iAmt+iOfst)>p->iSize ){
71251     rc = SQLITE_IOERR_SHORT_READ;
71252   }else{
71253     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
71254   }
71255   return rc;
71256 }
71257 
71258 /*
71259 ** Write data to the file.
71260 */
71261 static int jrnlWrite(
71262   sqlite3_file *pJfd,    /* The journal file into which to write */
71263   const void *zBuf,      /* Take data to be written from here */
71264   int iAmt,              /* Number of bytes to write */
71265   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
71266 ){
71267   int rc = SQLITE_OK;
71268   JournalFile *p = (JournalFile *)pJfd;
71269   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
71270     rc = createFile(p);
71271   }
71272   if( rc==SQLITE_OK ){
71273     if( p->pReal ){
71274       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
71275     }else{
71276       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
71277       if( p->iSize<(iOfst+iAmt) ){
71278         p->iSize = (iOfst+iAmt);
71279       }
71280     }
71281   }
71282   return rc;
71283 }
71284 
71285 /*
71286 ** Truncate the file.
71287 */
71288 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71289   int rc = SQLITE_OK;
71290   JournalFile *p = (JournalFile *)pJfd;
71291   if( p->pReal ){
71292     rc = sqlite3OsTruncate(p->pReal, size);
71293   }else if( size<p->iSize ){
71294     p->iSize = size;
71295   }
71296   return rc;
71297 }
71298 
71299 /*
71300 ** Sync the file.
71301 */
71302 static int jrnlSync(sqlite3_file *pJfd, int flags){
71303   int rc;
71304   JournalFile *p = (JournalFile *)pJfd;
71305   if( p->pReal ){
71306     rc = sqlite3OsSync(p->pReal, flags);
71307   }else{
71308     rc = SQLITE_OK;
71309   }
71310   return rc;
71311 }
71312 
71313 /*
71314 ** Query the size of the file in bytes.
71315 */
71316 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71317   int rc = SQLITE_OK;
71318   JournalFile *p = (JournalFile *)pJfd;
71319   if( p->pReal ){
71320     rc = sqlite3OsFileSize(p->pReal, pSize);
71321   }else{
71322     *pSize = (sqlite_int64) p->iSize;
71323   }
71324   return rc;
71325 }
71326 
71327 /*
71328 ** Table of methods for JournalFile sqlite3_file object.
71329 */
71330 static struct sqlite3_io_methods JournalFileMethods = {
71331   1,             /* iVersion */
71332   jrnlClose,     /* xClose */
71333   jrnlRead,      /* xRead */
71334   jrnlWrite,     /* xWrite */
71335   jrnlTruncate,  /* xTruncate */
71336   jrnlSync,      /* xSync */
71337   jrnlFileSize,  /* xFileSize */
71338   0,             /* xLock */
71339   0,             /* xUnlock */
71340   0,             /* xCheckReservedLock */
71341   0,             /* xFileControl */
71342   0,             /* xSectorSize */
71343   0,             /* xDeviceCharacteristics */
71344   0,             /* xShmMap */
71345   0,             /* xShmLock */
71346   0,             /* xShmBarrier */
71347   0              /* xShmUnmap */
71348 };
71349 
71350 /*
71351 ** Open a journal file.
71352 */
71353 SQLITE_PRIVATE int sqlite3JournalOpen(
71354   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
71355   const char *zName,         /* Name of the journal file */
71356   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
71357   int flags,                 /* Opening flags */
71358   int nBuf                   /* Bytes buffered before opening the file */
71359 ){
71360   JournalFile *p = (JournalFile *)pJfd;
71361   memset(p, 0, sqlite3JournalSize(pVfs));
71362   if( nBuf>0 ){
71363     p->zBuf = sqlite3MallocZero(nBuf);
71364     if( !p->zBuf ){
71365       return SQLITE_NOMEM;
71366     }
71367   }else{
71368     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
71369   }
71370   p->pMethod = &JournalFileMethods;
71371   p->nBuf = nBuf;
71372   p->flags = flags;
71373   p->zJournal = zName;
71374   p->pVfs = pVfs;
71375   return SQLITE_OK;
71376 }
71377 
71378 /*
71379 ** If the argument p points to a JournalFile structure, and the underlying
71380 ** file has not yet been created, create it now.
71381 */
71382 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
71383   if( p->pMethods!=&JournalFileMethods ){
71384     return SQLITE_OK;
71385   }
71386   return createFile((JournalFile *)p);
71387 }
71388 
71389 /*
71390 ** Return the number of bytes required to store a JournalFile that uses vfs
71391 ** pVfs to create the underlying on-disk files.
71392 */
71393 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
71394   return (pVfs->szOsFile+sizeof(JournalFile));
71395 }
71396 #endif
71397 
71398 /************** End of journal.c *********************************************/
71399 /************** Begin file memjournal.c **************************************/
71400 /*
71401 ** 2008 October 7
71402 **
71403 ** The author disclaims copyright to this source code.  In place of
71404 ** a legal notice, here is a blessing:
71405 **
71406 **    May you do good and not evil.
71407 **    May you find forgiveness for yourself and forgive others.
71408 **    May you share freely, never taking more than you give.
71409 **
71410 *************************************************************************
71411 **
71412 ** This file contains code use to implement an in-memory rollback journal.
71413 ** The in-memory rollback journal is used to journal transactions for
71414 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
71415 */
71416 
71417 /* Forward references to internal structures */
71418 typedef struct MemJournal MemJournal;
71419 typedef struct FilePoint FilePoint;
71420 typedef struct FileChunk FileChunk;
71421 
71422 /* Space to hold the rollback journal is allocated in increments of
71423 ** this many bytes.
71424 **
71425 ** The size chosen is a little less than a power of two.  That way,
71426 ** the FileChunk object will have a size that almost exactly fills
71427 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
71428 ** memory allocators.
71429 */
71430 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
71431 
71432 /* Macro to find the minimum of two numeric values.
71433 */
71434 #ifndef MIN
71435 # define MIN(x,y) ((x)<(y)?(x):(y))
71436 #endif
71437 
71438 /*
71439 ** The rollback journal is composed of a linked list of these structures.
71440 */
71441 struct FileChunk {
71442   FileChunk *pNext;               /* Next chunk in the journal */
71443   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
71444 };
71445 
71446 /*
71447 ** An instance of this object serves as a cursor into the rollback journal.
71448 ** The cursor can be either for reading or writing.
71449 */
71450 struct FilePoint {
71451   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
71452   FileChunk *pChunk;              /* Specific chunk into which cursor points */
71453 };
71454 
71455 /*
71456 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
71457 ** is an instance of this class.
71458 */
71459 struct MemJournal {
71460   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
71461   FileChunk *pFirst;              /* Head of in-memory chunk-list */
71462   FilePoint endpoint;             /* Pointer to the end of the file */
71463   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
71464 };
71465 
71466 /*
71467 ** Read data from the in-memory journal file.  This is the implementation
71468 ** of the sqlite3_vfs.xRead method.
71469 */
71470 static int memjrnlRead(
71471   sqlite3_file *pJfd,    /* The journal file from which to read */
71472   void *zBuf,            /* Put the results here */
71473   int iAmt,              /* Number of bytes to read */
71474   sqlite_int64 iOfst     /* Begin reading at this offset */
71475 ){
71476   MemJournal *p = (MemJournal *)pJfd;
71477   u8 *zOut = zBuf;
71478   int nRead = iAmt;
71479   int iChunkOffset;
71480   FileChunk *pChunk;
71481 
71482   /* SQLite never tries to read past the end of a rollback journal file */
71483   assert( iOfst+iAmt<=p->endpoint.iOffset );
71484 
71485   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
71486     sqlite3_int64 iOff = 0;
71487     for(pChunk=p->pFirst;
71488         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
71489         pChunk=pChunk->pNext
71490     ){
71491       iOff += JOURNAL_CHUNKSIZE;
71492     }
71493   }else{
71494     pChunk = p->readpoint.pChunk;
71495   }
71496 
71497   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
71498   do {
71499     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
71500     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
71501     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
71502     zOut += nCopy;
71503     nRead -= iSpace;
71504     iChunkOffset = 0;
71505   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
71506   p->readpoint.iOffset = iOfst+iAmt;
71507   p->readpoint.pChunk = pChunk;
71508 
71509   return SQLITE_OK;
71510 }
71511 
71512 /*
71513 ** Write data to the file.
71514 */
71515 static int memjrnlWrite(
71516   sqlite3_file *pJfd,    /* The journal file into which to write */
71517   const void *zBuf,      /* Take data to be written from here */
71518   int iAmt,              /* Number of bytes to write */
71519   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
71520 ){
71521   MemJournal *p = (MemJournal *)pJfd;
71522   int nWrite = iAmt;
71523   u8 *zWrite = (u8 *)zBuf;
71524 
71525   /* An in-memory journal file should only ever be appended to. Random
71526   ** access writes are not required by sqlite.
71527   */
71528   assert( iOfst==p->endpoint.iOffset );
71529   UNUSED_PARAMETER(iOfst);
71530 
71531   while( nWrite>0 ){
71532     FileChunk *pChunk = p->endpoint.pChunk;
71533     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
71534     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
71535 
71536     if( iChunkOffset==0 ){
71537       /* New chunk is required to extend the file. */
71538       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
71539       if( !pNew ){
71540         return SQLITE_IOERR_NOMEM;
71541       }
71542       pNew->pNext = 0;
71543       if( pChunk ){
71544         assert( p->pFirst );
71545         pChunk->pNext = pNew;
71546       }else{
71547         assert( !p->pFirst );
71548         p->pFirst = pNew;
71549       }
71550       p->endpoint.pChunk = pNew;
71551     }
71552 
71553     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
71554     zWrite += iSpace;
71555     nWrite -= iSpace;
71556     p->endpoint.iOffset += iSpace;
71557   }
71558 
71559   return SQLITE_OK;
71560 }
71561 
71562 /*
71563 ** Truncate the file.
71564 */
71565 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
71566   MemJournal *p = (MemJournal *)pJfd;
71567   FileChunk *pChunk;
71568   assert(size==0);
71569   UNUSED_PARAMETER(size);
71570   pChunk = p->pFirst;
71571   while( pChunk ){
71572     FileChunk *pTmp = pChunk;
71573     pChunk = pChunk->pNext;
71574     sqlite3_free(pTmp);
71575   }
71576   sqlite3MemJournalOpen(pJfd);
71577   return SQLITE_OK;
71578 }
71579 
71580 /*
71581 ** Close the file.
71582 */
71583 static int memjrnlClose(sqlite3_file *pJfd){
71584   memjrnlTruncate(pJfd, 0);
71585   return SQLITE_OK;
71586 }
71587 
71588 
71589 /*
71590 ** Sync the file.
71591 **
71592 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
71593 ** is never called in a working implementation.  This implementation
71594 ** exists purely as a contingency, in case some malfunction in some other
71595 ** part of SQLite causes Sync to be called by mistake.
71596 */
71597 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
71598   UNUSED_PARAMETER2(NotUsed, NotUsed2);
71599   return SQLITE_OK;
71600 }
71601 
71602 /*
71603 ** Query the size of the file in bytes.
71604 */
71605 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
71606   MemJournal *p = (MemJournal *)pJfd;
71607   *pSize = (sqlite_int64) p->endpoint.iOffset;
71608   return SQLITE_OK;
71609 }
71610 
71611 /*
71612 ** Table of methods for MemJournal sqlite3_file object.
71613 */
71614 static const struct sqlite3_io_methods MemJournalMethods = {
71615   1,                /* iVersion */
71616   memjrnlClose,     /* xClose */
71617   memjrnlRead,      /* xRead */
71618   memjrnlWrite,     /* xWrite */
71619   memjrnlTruncate,  /* xTruncate */
71620   memjrnlSync,      /* xSync */
71621   memjrnlFileSize,  /* xFileSize */
71622   0,                /* xLock */
71623   0,                /* xUnlock */
71624   0,                /* xCheckReservedLock */
71625   0,                /* xFileControl */
71626   0,                /* xSectorSize */
71627   0,                /* xDeviceCharacteristics */
71628   0,                /* xShmMap */
71629   0,                /* xShmLock */
71630   0,                /* xShmBarrier */
71631   0                 /* xShmUnlock */
71632 };
71633 
71634 /*
71635 ** Open a journal file.
71636 */
71637 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
71638   MemJournal *p = (MemJournal *)pJfd;
71639   assert( EIGHT_BYTE_ALIGNMENT(p) );
71640   memset(p, 0, sqlite3MemJournalSize());
71641   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
71642 }
71643 
71644 /*
71645 ** Return true if the file-handle passed as an argument is
71646 ** an in-memory journal
71647 */
71648 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
71649   return pJfd->pMethods==&MemJournalMethods;
71650 }
71651 
71652 /*
71653 ** Return the number of bytes required to store a MemJournal file descriptor.
71654 */
71655 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
71656   return sizeof(MemJournal);
71657 }
71658 
71659 /************** End of memjournal.c ******************************************/
71660 /************** Begin file walker.c ******************************************/
71661 /*
71662 ** 2008 August 16
71663 **
71664 ** The author disclaims copyright to this source code.  In place of
71665 ** a legal notice, here is a blessing:
71666 **
71667 **    May you do good and not evil.
71668 **    May you find forgiveness for yourself and forgive others.
71669 **    May you share freely, never taking more than you give.
71670 **
71671 *************************************************************************
71672 ** This file contains routines used for walking the parser tree for
71673 ** an SQL statement.
71674 */
71675 /* #include <stdlib.h> */
71676 /* #include <string.h> */
71677 
71678 
71679 /*
71680 ** Walk an expression tree.  Invoke the callback once for each node
71681 ** of the expression, while decending.  (In other words, the callback
71682 ** is invoked before visiting children.)
71683 **
71684 ** The return value from the callback should be one of the WRC_*
71685 ** constants to specify how to proceed with the walk.
71686 **
71687 **    WRC_Continue      Continue descending down the tree.
71688 **
71689 **    WRC_Prune         Do not descend into child nodes.  But allow
71690 **                      the walk to continue with sibling nodes.
71691 **
71692 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
71693 **                      return the top-level walk call.
71694 **
71695 ** The return value from this routine is WRC_Abort to abandon the tree walk
71696 ** and WRC_Continue to continue.
71697 */
71698 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
71699   int rc;
71700   if( pExpr==0 ) return WRC_Continue;
71701   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
71702   testcase( ExprHasProperty(pExpr, EP_Reduced) );
71703   rc = pWalker->xExprCallback(pWalker, pExpr);
71704   if( rc==WRC_Continue
71705               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
71706     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
71707     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
71708     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
71709       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
71710     }else{
71711       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
71712     }
71713   }
71714   return rc & WRC_Abort;
71715 }
71716 
71717 /*
71718 ** Call sqlite3WalkExpr() for every expression in list p or until
71719 ** an abort request is seen.
71720 */
71721 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
71722   int i;
71723   struct ExprList_item *pItem;
71724   if( p ){
71725     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
71726       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
71727     }
71728   }
71729   return WRC_Continue;
71730 }
71731 
71732 /*
71733 ** Walk all expressions associated with SELECT statement p.  Do
71734 ** not invoke the SELECT callback on p, but do (of course) invoke
71735 ** any expr callbacks and SELECT callbacks that come from subqueries.
71736 ** Return WRC_Abort or WRC_Continue.
71737 */
71738 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
71739   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
71740   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
71741   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
71742   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
71743   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
71744   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
71745   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
71746   return WRC_Continue;
71747 }
71748 
71749 /*
71750 ** Walk the parse trees associated with all subqueries in the
71751 ** FROM clause of SELECT statement p.  Do not invoke the select
71752 ** callback on p, but do invoke it on each FROM clause subquery
71753 ** and on any subqueries further down in the tree.  Return
71754 ** WRC_Abort or WRC_Continue;
71755 */
71756 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
71757   SrcList *pSrc;
71758   int i;
71759   struct SrcList_item *pItem;
71760 
71761   pSrc = p->pSrc;
71762   if( ALWAYS(pSrc) ){
71763     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
71764       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
71765         return WRC_Abort;
71766       }
71767     }
71768   }
71769   return WRC_Continue;
71770 }
71771 
71772 /*
71773 ** Call sqlite3WalkExpr() for every expression in Select statement p.
71774 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
71775 ** on the compound select chain, p->pPrior.
71776 **
71777 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
71778 ** there is an abort request.
71779 **
71780 ** If the Walker does not have an xSelectCallback() then this routine
71781 ** is a no-op returning WRC_Continue.
71782 */
71783 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
71784   int rc;
71785   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
71786   rc = WRC_Continue;
71787   while( p  ){
71788     rc = pWalker->xSelectCallback(pWalker, p);
71789     if( rc ) break;
71790     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
71791     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
71792     p = p->pPrior;
71793   }
71794   return rc & WRC_Abort;
71795 }
71796 
71797 /************** End of walker.c **********************************************/
71798 /************** Begin file resolve.c *****************************************/
71799 /*
71800 ** 2008 August 18
71801 **
71802 ** The author disclaims copyright to this source code.  In place of
71803 ** a legal notice, here is a blessing:
71804 **
71805 **    May you do good and not evil.
71806 **    May you find forgiveness for yourself and forgive others.
71807 **    May you share freely, never taking more than you give.
71808 **
71809 *************************************************************************
71810 **
71811 ** This file contains routines used for walking the parser tree and
71812 ** resolve all identifiers by associating them with a particular
71813 ** table and column.
71814 */
71815 /* #include <stdlib.h> */
71816 /* #include <string.h> */
71817 
71818 /*
71819 ** Turn the pExpr expression into an alias for the iCol-th column of the
71820 ** result set in pEList.
71821 **
71822 ** If the result set column is a simple column reference, then this routine
71823 ** makes an exact copy.  But for any other kind of expression, this
71824 ** routine make a copy of the result set column as the argument to the
71825 ** TK_AS operator.  The TK_AS operator causes the expression to be
71826 ** evaluated just once and then reused for each alias.
71827 **
71828 ** The reason for suppressing the TK_AS term when the expression is a simple
71829 ** column reference is so that the column reference will be recognized as
71830 ** usable by indices within the WHERE clause processing logic.
71831 **
71832 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
71833 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
71834 **
71835 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
71836 **
71837 ** Is equivalent to:
71838 **
71839 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
71840 **
71841 ** The result of random()%5 in the GROUP BY clause is probably different
71842 ** from the result in the result-set.  We might fix this someday.  Or
71843 ** then again, we might not...
71844 */
71845 static void resolveAlias(
71846   Parse *pParse,         /* Parsing context */
71847   ExprList *pEList,      /* A result set */
71848   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
71849   Expr *pExpr,           /* Transform this into an alias to the result set */
71850   const char *zType      /* "GROUP" or "ORDER" or "" */
71851 ){
71852   Expr *pOrig;           /* The iCol-th column of the result set */
71853   Expr *pDup;            /* Copy of pOrig */
71854   sqlite3 *db;           /* The database connection */
71855 
71856   assert( iCol>=0 && iCol<pEList->nExpr );
71857   pOrig = pEList->a[iCol].pExpr;
71858   assert( pOrig!=0 );
71859   assert( pOrig->flags & EP_Resolved );
71860   db = pParse->db;
71861   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
71862     pDup = sqlite3ExprDup(db, pOrig, 0);
71863     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
71864     if( pDup==0 ) return;
71865     if( pEList->a[iCol].iAlias==0 ){
71866       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
71867     }
71868     pDup->iTable = pEList->a[iCol].iAlias;
71869   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
71870     pDup = sqlite3ExprDup(db, pOrig, 0);
71871     if( pDup==0 ) return;
71872   }else{
71873     char *zToken = pOrig->u.zToken;
71874     assert( zToken!=0 );
71875     pOrig->u.zToken = 0;
71876     pDup = sqlite3ExprDup(db, pOrig, 0);
71877     pOrig->u.zToken = zToken;
71878     if( pDup==0 ) return;
71879     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
71880     pDup->flags2 |= EP2_MallocedToken;
71881     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
71882   }
71883   if( pExpr->flags & EP_ExpCollate ){
71884     pDup->pColl = pExpr->pColl;
71885     pDup->flags |= EP_ExpCollate;
71886   }
71887 
71888   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
71889   ** prevents ExprDelete() from deleting the Expr structure itself,
71890   ** allowing it to be repopulated by the memcpy() on the following line.
71891   */
71892   ExprSetProperty(pExpr, EP_Static);
71893   sqlite3ExprDelete(db, pExpr);
71894   memcpy(pExpr, pDup, sizeof(*pExpr));
71895   sqlite3DbFree(db, pDup);
71896 }
71897 
71898 /*
71899 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
71900 ** that name in the set of source tables in pSrcList and make the pExpr
71901 ** expression node refer back to that source column.  The following changes
71902 ** are made to pExpr:
71903 **
71904 **    pExpr->iDb           Set the index in db->aDb[] of the database X
71905 **                         (even if X is implied).
71906 **    pExpr->iTable        Set to the cursor number for the table obtained
71907 **                         from pSrcList.
71908 **    pExpr->pTab          Points to the Table structure of X.Y (even if
71909 **                         X and/or Y are implied.)
71910 **    pExpr->iColumn       Set to the column number within the table.
71911 **    pExpr->op            Set to TK_COLUMN.
71912 **    pExpr->pLeft         Any expression this points to is deleted
71913 **    pExpr->pRight        Any expression this points to is deleted.
71914 **
71915 ** The zDb variable is the name of the database (the "X").  This value may be
71916 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
71917 ** can be used.  The zTable variable is the name of the table (the "Y").  This
71918 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
71919 ** means that the form of the name is Z and that columns from any table
71920 ** can be used.
71921 **
71922 ** If the name cannot be resolved unambiguously, leave an error message
71923 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
71924 */
71925 static int lookupName(
71926   Parse *pParse,       /* The parsing context */
71927   const char *zDb,     /* Name of the database containing table, or NULL */
71928   const char *zTab,    /* Name of table containing column, or NULL */
71929   const char *zCol,    /* Name of the column. */
71930   NameContext *pNC,    /* The name context used to resolve the name */
71931   Expr *pExpr          /* Make this EXPR node point to the selected column */
71932 ){
71933   int i, j;            /* Loop counters */
71934   int cnt = 0;                      /* Number of matching column names */
71935   int cntTab = 0;                   /* Number of matching table names */
71936   sqlite3 *db = pParse->db;         /* The database connection */
71937   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
71938   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
71939   NameContext *pTopNC = pNC;        /* First namecontext in the list */
71940   Schema *pSchema = 0;              /* Schema of the expression */
71941   int isTrigger = 0;
71942 
71943   assert( pNC );     /* the name context cannot be NULL. */
71944   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
71945   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
71946 
71947   /* Initialize the node to no-match */
71948   pExpr->iTable = -1;
71949   pExpr->pTab = 0;
71950   ExprSetIrreducible(pExpr);
71951 
71952   /* Start at the inner-most context and move outward until a match is found */
71953   while( pNC && cnt==0 ){
71954     ExprList *pEList;
71955     SrcList *pSrcList = pNC->pSrcList;
71956 
71957     if( pSrcList ){
71958       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
71959         Table *pTab;
71960         int iDb;
71961         Column *pCol;
71962 
71963         pTab = pItem->pTab;
71964         assert( pTab!=0 && pTab->zName!=0 );
71965         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71966         assert( pTab->nCol>0 );
71967         if( zTab ){
71968           if( pItem->zAlias ){
71969             char *zTabName = pItem->zAlias;
71970             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
71971           }else{
71972             char *zTabName = pTab->zName;
71973             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
71974               continue;
71975             }
71976             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
71977               continue;
71978             }
71979           }
71980         }
71981         if( 0==(cntTab++) ){
71982           pExpr->iTable = pItem->iCursor;
71983           pExpr->pTab = pTab;
71984           pSchema = pTab->pSchema;
71985           pMatch = pItem;
71986         }
71987         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
71988           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
71989             IdList *pUsing;
71990             cnt++;
71991             pExpr->iTable = pItem->iCursor;
71992             pExpr->pTab = pTab;
71993             pMatch = pItem;
71994             pSchema = pTab->pSchema;
71995             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
71996             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
71997             if( i<pSrcList->nSrc-1 ){
71998               if( pItem[1].jointype & JT_NATURAL ){
71999                 /* If this match occurred in the left table of a natural join,
72000                 ** then skip the right table to avoid a duplicate match */
72001                 pItem++;
72002                 i++;
72003               }else if( (pUsing = pItem[1].pUsing)!=0 ){
72004                 /* If this match occurs on a column that is in the USING clause
72005                 ** of a join, skip the search of the right table of the join
72006                 ** to avoid a duplicate match there. */
72007                 int k;
72008                 for(k=0; k<pUsing->nId; k++){
72009                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
72010                     pItem++;
72011                     i++;
72012                     break;
72013                   }
72014                 }
72015               }
72016             }
72017             break;
72018           }
72019         }
72020       }
72021     }
72022 
72023 #ifndef SQLITE_OMIT_TRIGGER
72024     /* If we have not already resolved the name, then maybe
72025     ** it is a new.* or old.* trigger argument reference
72026     */
72027     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
72028       int op = pParse->eTriggerOp;
72029       Table *pTab = 0;
72030       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
72031       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
72032         pExpr->iTable = 1;
72033         pTab = pParse->pTriggerTab;
72034       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
72035         pExpr->iTable = 0;
72036         pTab = pParse->pTriggerTab;
72037       }
72038 
72039       if( pTab ){
72040         int iCol;
72041         pSchema = pTab->pSchema;
72042         cntTab++;
72043         for(iCol=0; iCol<pTab->nCol; iCol++){
72044           Column *pCol = &pTab->aCol[iCol];
72045           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
72046             if( iCol==pTab->iPKey ){
72047               iCol = -1;
72048             }
72049             break;
72050           }
72051         }
72052         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
72053           iCol = -1;        /* IMP: R-44911-55124 */
72054         }
72055         if( iCol<pTab->nCol ){
72056           cnt++;
72057           if( iCol<0 ){
72058             pExpr->affinity = SQLITE_AFF_INTEGER;
72059           }else if( pExpr->iTable==0 ){
72060             testcase( iCol==31 );
72061             testcase( iCol==32 );
72062             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72063           }else{
72064             testcase( iCol==31 );
72065             testcase( iCol==32 );
72066             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
72067           }
72068           pExpr->iColumn = (i16)iCol;
72069           pExpr->pTab = pTab;
72070           isTrigger = 1;
72071         }
72072       }
72073     }
72074 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
72075 
72076     /*
72077     ** Perhaps the name is a reference to the ROWID
72078     */
72079     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
72080       cnt = 1;
72081       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
72082       pExpr->affinity = SQLITE_AFF_INTEGER;
72083     }
72084 
72085     /*
72086     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
72087     ** might refer to an result-set alias.  This happens, for example, when
72088     ** we are resolving names in the WHERE clause of the following command:
72089     **
72090     **     SELECT a+b AS x FROM table WHERE x<10;
72091     **
72092     ** In cases like this, replace pExpr with a copy of the expression that
72093     ** forms the result set entry ("a+b" in the example) and return immediately.
72094     ** Note that the expression in the result set should have already been
72095     ** resolved by the time the WHERE clause is resolved.
72096     */
72097     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
72098       for(j=0; j<pEList->nExpr; j++){
72099         char *zAs = pEList->a[j].zName;
72100         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72101           Expr *pOrig;
72102           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
72103           assert( pExpr->x.pList==0 );
72104           assert( pExpr->x.pSelect==0 );
72105           pOrig = pEList->a[j].pExpr;
72106           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
72107             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
72108             return WRC_Abort;
72109           }
72110           resolveAlias(pParse, pEList, j, pExpr, "");
72111           cnt = 1;
72112           pMatch = 0;
72113           assert( zTab==0 && zDb==0 );
72114           goto lookupname_end;
72115         }
72116       }
72117     }
72118 
72119     /* Advance to the next name context.  The loop will exit when either
72120     ** we have a match (cnt>0) or when we run out of name contexts.
72121     */
72122     if( cnt==0 ){
72123       pNC = pNC->pNext;
72124     }
72125   }
72126 
72127   /*
72128   ** If X and Y are NULL (in other words if only the column name Z is
72129   ** supplied) and the value of Z is enclosed in double-quotes, then
72130   ** Z is a string literal if it doesn't match any column names.  In that
72131   ** case, we need to return right away and not make any changes to
72132   ** pExpr.
72133   **
72134   ** Because no reference was made to outer contexts, the pNC->nRef
72135   ** fields are not changed in any context.
72136   */
72137   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
72138     pExpr->op = TK_STRING;
72139     pExpr->pTab = 0;
72140     return WRC_Prune;
72141   }
72142 
72143   /*
72144   ** cnt==0 means there was not match.  cnt>1 means there were two or
72145   ** more matches.  Either way, we have an error.
72146   */
72147   if( cnt!=1 ){
72148     const char *zErr;
72149     zErr = cnt==0 ? "no such column" : "ambiguous column name";
72150     if( zDb ){
72151       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
72152     }else if( zTab ){
72153       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
72154     }else{
72155       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
72156     }
72157     pParse->checkSchema = 1;
72158     pTopNC->nErr++;
72159   }
72160 
72161   /* If a column from a table in pSrcList is referenced, then record
72162   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
72163   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
72164   ** column number is greater than the number of bits in the bitmask
72165   ** then set the high-order bit of the bitmask.
72166   */
72167   if( pExpr->iColumn>=0 && pMatch!=0 ){
72168     int n = pExpr->iColumn;
72169     testcase( n==BMS-1 );
72170     if( n>=BMS ){
72171       n = BMS-1;
72172     }
72173     assert( pMatch->iCursor==pExpr->iTable );
72174     pMatch->colUsed |= ((Bitmask)1)<<n;
72175   }
72176 
72177   /* Clean up and return
72178   */
72179   sqlite3ExprDelete(db, pExpr->pLeft);
72180   pExpr->pLeft = 0;
72181   sqlite3ExprDelete(db, pExpr->pRight);
72182   pExpr->pRight = 0;
72183   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
72184 lookupname_end:
72185   if( cnt==1 ){
72186     assert( pNC!=0 );
72187     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
72188     /* Increment the nRef value on all name contexts from TopNC up to
72189     ** the point where the name matched. */
72190     for(;;){
72191       assert( pTopNC!=0 );
72192       pTopNC->nRef++;
72193       if( pTopNC==pNC ) break;
72194       pTopNC = pTopNC->pNext;
72195     }
72196     return WRC_Prune;
72197   } else {
72198     return WRC_Abort;
72199   }
72200 }
72201 
72202 /*
72203 ** Allocate and return a pointer to an expression to load the column iCol
72204 ** from datasource iSrc in SrcList pSrc.
72205 */
72206 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
72207   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
72208   if( p ){
72209     struct SrcList_item *pItem = &pSrc->a[iSrc];
72210     p->pTab = pItem->pTab;
72211     p->iTable = pItem->iCursor;
72212     if( p->pTab->iPKey==iCol ){
72213       p->iColumn = -1;
72214     }else{
72215       p->iColumn = (ynVar)iCol;
72216       testcase( iCol==BMS );
72217       testcase( iCol==BMS-1 );
72218       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
72219     }
72220     ExprSetProperty(p, EP_Resolved);
72221   }
72222   return p;
72223 }
72224 
72225 /*
72226 ** This routine is callback for sqlite3WalkExpr().
72227 **
72228 ** Resolve symbolic names into TK_COLUMN operators for the current
72229 ** node in the expression tree.  Return 0 to continue the search down
72230 ** the tree or 2 to abort the tree walk.
72231 **
72232 ** This routine also does error checking and name resolution for
72233 ** function names.  The operator for aggregate functions is changed
72234 ** to TK_AGG_FUNCTION.
72235 */
72236 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
72237   NameContext *pNC;
72238   Parse *pParse;
72239 
72240   pNC = pWalker->u.pNC;
72241   assert( pNC!=0 );
72242   pParse = pNC->pParse;
72243   assert( pParse==pWalker->pParse );
72244 
72245   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
72246   ExprSetProperty(pExpr, EP_Resolved);
72247 #ifndef NDEBUG
72248   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
72249     SrcList *pSrcList = pNC->pSrcList;
72250     int i;
72251     for(i=0; i<pNC->pSrcList->nSrc; i++){
72252       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
72253     }
72254   }
72255 #endif
72256   switch( pExpr->op ){
72257 
72258 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
72259     /* The special operator TK_ROW means use the rowid for the first
72260     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
72261     ** clause processing on UPDATE and DELETE statements.
72262     */
72263     case TK_ROW: {
72264       SrcList *pSrcList = pNC->pSrcList;
72265       struct SrcList_item *pItem;
72266       assert( pSrcList && pSrcList->nSrc==1 );
72267       pItem = pSrcList->a;
72268       pExpr->op = TK_COLUMN;
72269       pExpr->pTab = pItem->pTab;
72270       pExpr->iTable = pItem->iCursor;
72271       pExpr->iColumn = -1;
72272       pExpr->affinity = SQLITE_AFF_INTEGER;
72273       break;
72274     }
72275 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
72276 
72277     /* A lone identifier is the name of a column.
72278     */
72279     case TK_ID: {
72280       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
72281     }
72282 
72283     /* A table name and column name:     ID.ID
72284     ** Or a database, table and column:  ID.ID.ID
72285     */
72286     case TK_DOT: {
72287       const char *zColumn;
72288       const char *zTable;
72289       const char *zDb;
72290       Expr *pRight;
72291 
72292       /* if( pSrcList==0 ) break; */
72293       pRight = pExpr->pRight;
72294       if( pRight->op==TK_ID ){
72295         zDb = 0;
72296         zTable = pExpr->pLeft->u.zToken;
72297         zColumn = pRight->u.zToken;
72298       }else{
72299         assert( pRight->op==TK_DOT );
72300         zDb = pExpr->pLeft->u.zToken;
72301         zTable = pRight->pLeft->u.zToken;
72302         zColumn = pRight->pRight->u.zToken;
72303       }
72304       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
72305     }
72306 
72307     /* Resolve function names
72308     */
72309     case TK_CONST_FUNC:
72310     case TK_FUNCTION: {
72311       ExprList *pList = pExpr->x.pList;    /* The argument list */
72312       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
72313       int no_such_func = 0;       /* True if no such function exists */
72314       int wrong_num_args = 0;     /* True if wrong number of arguments */
72315       int is_agg = 0;             /* True if is an aggregate function */
72316       int auth;                   /* Authorization to use the function */
72317       int nId;                    /* Number of characters in function name */
72318       const char *zId;            /* The function name. */
72319       FuncDef *pDef;              /* Information about the function */
72320       u8 enc = ENC(pParse->db);   /* The database encoding */
72321 
72322       testcase( pExpr->op==TK_CONST_FUNC );
72323       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72324       zId = pExpr->u.zToken;
72325       nId = sqlite3Strlen30(zId);
72326       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
72327       if( pDef==0 ){
72328         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
72329         if( pDef==0 ){
72330           no_such_func = 1;
72331         }else{
72332           wrong_num_args = 1;
72333         }
72334       }else{
72335         is_agg = pDef->xFunc==0;
72336       }
72337 #ifndef SQLITE_OMIT_AUTHORIZATION
72338       if( pDef ){
72339         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
72340         if( auth!=SQLITE_OK ){
72341           if( auth==SQLITE_DENY ){
72342             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
72343                                     pDef->zName);
72344             pNC->nErr++;
72345           }
72346           pExpr->op = TK_NULL;
72347           return WRC_Prune;
72348         }
72349       }
72350 #endif
72351       if( is_agg && !pNC->allowAgg ){
72352         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
72353         pNC->nErr++;
72354         is_agg = 0;
72355       }else if( no_such_func ){
72356         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
72357         pNC->nErr++;
72358       }else if( wrong_num_args ){
72359         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
72360              nId, zId);
72361         pNC->nErr++;
72362       }
72363       if( is_agg ){
72364         pExpr->op = TK_AGG_FUNCTION;
72365         pNC->hasAgg = 1;
72366       }
72367       if( is_agg ) pNC->allowAgg = 0;
72368       sqlite3WalkExprList(pWalker, pList);
72369       if( is_agg ) pNC->allowAgg = 1;
72370       /* FIX ME:  Compute pExpr->affinity based on the expected return
72371       ** type of the function
72372       */
72373       return WRC_Prune;
72374     }
72375 #ifndef SQLITE_OMIT_SUBQUERY
72376     case TK_SELECT:
72377     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
72378 #endif
72379     case TK_IN: {
72380       testcase( pExpr->op==TK_IN );
72381       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
72382         int nRef = pNC->nRef;
72383 #ifndef SQLITE_OMIT_CHECK
72384         if( pNC->isCheck ){
72385           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
72386         }
72387 #endif
72388         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
72389         assert( pNC->nRef>=nRef );
72390         if( nRef!=pNC->nRef ){
72391           ExprSetProperty(pExpr, EP_VarSelect);
72392         }
72393       }
72394       break;
72395     }
72396 #ifndef SQLITE_OMIT_CHECK
72397     case TK_VARIABLE: {
72398       if( pNC->isCheck ){
72399         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
72400       }
72401       break;
72402     }
72403 #endif
72404   }
72405   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
72406 }
72407 
72408 /*
72409 ** pEList is a list of expressions which are really the result set of the
72410 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
72411 ** This routine checks to see if pE is a simple identifier which corresponds
72412 ** to the AS-name of one of the terms of the expression list.  If it is,
72413 ** this routine return an integer between 1 and N where N is the number of
72414 ** elements in pEList, corresponding to the matching entry.  If there is
72415 ** no match, or if pE is not a simple identifier, then this routine
72416 ** return 0.
72417 **
72418 ** pEList has been resolved.  pE has not.
72419 */
72420 static int resolveAsName(
72421   Parse *pParse,     /* Parsing context for error messages */
72422   ExprList *pEList,  /* List of expressions to scan */
72423   Expr *pE           /* Expression we are trying to match */
72424 ){
72425   int i;             /* Loop counter */
72426 
72427   UNUSED_PARAMETER(pParse);
72428 
72429   if( pE->op==TK_ID ){
72430     char *zCol = pE->u.zToken;
72431     for(i=0; i<pEList->nExpr; i++){
72432       char *zAs = pEList->a[i].zName;
72433       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
72434         return i+1;
72435       }
72436     }
72437   }
72438   return 0;
72439 }
72440 
72441 /*
72442 ** pE is a pointer to an expression which is a single term in the
72443 ** ORDER BY of a compound SELECT.  The expression has not been
72444 ** name resolved.
72445 **
72446 ** At the point this routine is called, we already know that the
72447 ** ORDER BY term is not an integer index into the result set.  That
72448 ** case is handled by the calling routine.
72449 **
72450 ** Attempt to match pE against result set columns in the left-most
72451 ** SELECT statement.  Return the index i of the matching column,
72452 ** as an indication to the caller that it should sort by the i-th column.
72453 ** The left-most column is 1.  In other words, the value returned is the
72454 ** same integer value that would be used in the SQL statement to indicate
72455 ** the column.
72456 **
72457 ** If there is no match, return 0.  Return -1 if an error occurs.
72458 */
72459 static int resolveOrderByTermToExprList(
72460   Parse *pParse,     /* Parsing context for error messages */
72461   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
72462   Expr *pE           /* The specific ORDER BY term */
72463 ){
72464   int i;             /* Loop counter */
72465   ExprList *pEList;  /* The columns of the result set */
72466   NameContext nc;    /* Name context for resolving pE */
72467   sqlite3 *db;       /* Database connection */
72468   int rc;            /* Return code from subprocedures */
72469   u8 savedSuppErr;   /* Saved value of db->suppressErr */
72470 
72471   assert( sqlite3ExprIsInteger(pE, &i)==0 );
72472   pEList = pSelect->pEList;
72473 
72474   /* Resolve all names in the ORDER BY term expression
72475   */
72476   memset(&nc, 0, sizeof(nc));
72477   nc.pParse = pParse;
72478   nc.pSrcList = pSelect->pSrc;
72479   nc.pEList = pEList;
72480   nc.allowAgg = 1;
72481   nc.nErr = 0;
72482   db = pParse->db;
72483   savedSuppErr = db->suppressErr;
72484   db->suppressErr = 1;
72485   rc = sqlite3ResolveExprNames(&nc, pE);
72486   db->suppressErr = savedSuppErr;
72487   if( rc ) return 0;
72488 
72489   /* Try to match the ORDER BY expression against an expression
72490   ** in the result set.  Return an 1-based index of the matching
72491   ** result-set entry.
72492   */
72493   for(i=0; i<pEList->nExpr; i++){
72494     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
72495       return i+1;
72496     }
72497   }
72498 
72499   /* If no match, return 0. */
72500   return 0;
72501 }
72502 
72503 /*
72504 ** Generate an ORDER BY or GROUP BY term out-of-range error.
72505 */
72506 static void resolveOutOfRangeError(
72507   Parse *pParse,         /* The error context into which to write the error */
72508   const char *zType,     /* "ORDER" or "GROUP" */
72509   int i,                 /* The index (1-based) of the term out of range */
72510   int mx                 /* Largest permissible value of i */
72511 ){
72512   sqlite3ErrorMsg(pParse,
72513     "%r %s BY term out of range - should be "
72514     "between 1 and %d", i, zType, mx);
72515 }
72516 
72517 /*
72518 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
72519 ** each term of the ORDER BY clause is a constant integer between 1
72520 ** and N where N is the number of columns in the compound SELECT.
72521 **
72522 ** ORDER BY terms that are already an integer between 1 and N are
72523 ** unmodified.  ORDER BY terms that are integers outside the range of
72524 ** 1 through N generate an error.  ORDER BY terms that are expressions
72525 ** are matched against result set expressions of compound SELECT
72526 ** beginning with the left-most SELECT and working toward the right.
72527 ** At the first match, the ORDER BY expression is transformed into
72528 ** the integer column number.
72529 **
72530 ** Return the number of errors seen.
72531 */
72532 static int resolveCompoundOrderBy(
72533   Parse *pParse,        /* Parsing context.  Leave error messages here */
72534   Select *pSelect       /* The SELECT statement containing the ORDER BY */
72535 ){
72536   int i;
72537   ExprList *pOrderBy;
72538   ExprList *pEList;
72539   sqlite3 *db;
72540   int moreToDo = 1;
72541 
72542   pOrderBy = pSelect->pOrderBy;
72543   if( pOrderBy==0 ) return 0;
72544   db = pParse->db;
72545 #if SQLITE_MAX_COLUMN
72546   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72547     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
72548     return 1;
72549   }
72550 #endif
72551   for(i=0; i<pOrderBy->nExpr; i++){
72552     pOrderBy->a[i].done = 0;
72553   }
72554   pSelect->pNext = 0;
72555   while( pSelect->pPrior ){
72556     pSelect->pPrior->pNext = pSelect;
72557     pSelect = pSelect->pPrior;
72558   }
72559   while( pSelect && moreToDo ){
72560     struct ExprList_item *pItem;
72561     moreToDo = 0;
72562     pEList = pSelect->pEList;
72563     assert( pEList!=0 );
72564     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72565       int iCol = -1;
72566       Expr *pE, *pDup;
72567       if( pItem->done ) continue;
72568       pE = pItem->pExpr;
72569       if( sqlite3ExprIsInteger(pE, &iCol) ){
72570         if( iCol<=0 || iCol>pEList->nExpr ){
72571           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
72572           return 1;
72573         }
72574       }else{
72575         iCol = resolveAsName(pParse, pEList, pE);
72576         if( iCol==0 ){
72577           pDup = sqlite3ExprDup(db, pE, 0);
72578           if( !db->mallocFailed ){
72579             assert(pDup);
72580             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
72581           }
72582           sqlite3ExprDelete(db, pDup);
72583         }
72584       }
72585       if( iCol>0 ){
72586         CollSeq *pColl = pE->pColl;
72587         int flags = pE->flags & EP_ExpCollate;
72588         sqlite3ExprDelete(db, pE);
72589         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
72590         if( pE==0 ) return 1;
72591         pE->pColl = pColl;
72592         pE->flags |= EP_IntValue | flags;
72593         pE->u.iValue = iCol;
72594         pItem->iCol = (u16)iCol;
72595         pItem->done = 1;
72596       }else{
72597         moreToDo = 1;
72598       }
72599     }
72600     pSelect = pSelect->pNext;
72601   }
72602   for(i=0; i<pOrderBy->nExpr; i++){
72603     if( pOrderBy->a[i].done==0 ){
72604       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
72605             "column in the result set", i+1);
72606       return 1;
72607     }
72608   }
72609   return 0;
72610 }
72611 
72612 /*
72613 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
72614 ** the SELECT statement pSelect.  If any term is reference to a
72615 ** result set expression (as determined by the ExprList.a.iCol field)
72616 ** then convert that term into a copy of the corresponding result set
72617 ** column.
72618 **
72619 ** If any errors are detected, add an error message to pParse and
72620 ** return non-zero.  Return zero if no errors are seen.
72621 */
72622 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
72623   Parse *pParse,        /* Parsing context.  Leave error messages here */
72624   Select *pSelect,      /* The SELECT statement containing the clause */
72625   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
72626   const char *zType     /* "ORDER" or "GROUP" */
72627 ){
72628   int i;
72629   sqlite3 *db = pParse->db;
72630   ExprList *pEList;
72631   struct ExprList_item *pItem;
72632 
72633   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
72634 #if SQLITE_MAX_COLUMN
72635   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
72636     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
72637     return 1;
72638   }
72639 #endif
72640   pEList = pSelect->pEList;
72641   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
72642   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72643     if( pItem->iCol ){
72644       if( pItem->iCol>pEList->nExpr ){
72645         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
72646         return 1;
72647       }
72648       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
72649     }
72650   }
72651   return 0;
72652 }
72653 
72654 /*
72655 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
72656 ** The Name context of the SELECT statement is pNC.  zType is either
72657 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
72658 **
72659 ** This routine resolves each term of the clause into an expression.
72660 ** If the order-by term is an integer I between 1 and N (where N is the
72661 ** number of columns in the result set of the SELECT) then the expression
72662 ** in the resolution is a copy of the I-th result-set expression.  If
72663 ** the order-by term is an identify that corresponds to the AS-name of
72664 ** a result-set expression, then the term resolves to a copy of the
72665 ** result-set expression.  Otherwise, the expression is resolved in
72666 ** the usual way - using sqlite3ResolveExprNames().
72667 **
72668 ** This routine returns the number of errors.  If errors occur, then
72669 ** an appropriate error message might be left in pParse.  (OOM errors
72670 ** excepted.)
72671 */
72672 static int resolveOrderGroupBy(
72673   NameContext *pNC,     /* The name context of the SELECT statement */
72674   Select *pSelect,      /* The SELECT statement holding pOrderBy */
72675   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
72676   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
72677 ){
72678   int i;                         /* Loop counter */
72679   int iCol;                      /* Column number */
72680   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
72681   Parse *pParse;                 /* Parsing context */
72682   int nResult;                   /* Number of terms in the result set */
72683 
72684   if( pOrderBy==0 ) return 0;
72685   nResult = pSelect->pEList->nExpr;
72686   pParse = pNC->pParse;
72687   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
72688     Expr *pE = pItem->pExpr;
72689     iCol = resolveAsName(pParse, pSelect->pEList, pE);
72690     if( iCol>0 ){
72691       /* If an AS-name match is found, mark this ORDER BY column as being
72692       ** a copy of the iCol-th result-set column.  The subsequent call to
72693       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
72694       ** copy of the iCol-th result-set expression. */
72695       pItem->iCol = (u16)iCol;
72696       continue;
72697     }
72698     if( sqlite3ExprIsInteger(pE, &iCol) ){
72699       /* The ORDER BY term is an integer constant.  Again, set the column
72700       ** number so that sqlite3ResolveOrderGroupBy() will convert the
72701       ** order-by term to a copy of the result-set expression */
72702       if( iCol<1 ){
72703         resolveOutOfRangeError(pParse, zType, i+1, nResult);
72704         return 1;
72705       }
72706       pItem->iCol = (u16)iCol;
72707       continue;
72708     }
72709 
72710     /* Otherwise, treat the ORDER BY term as an ordinary expression */
72711     pItem->iCol = 0;
72712     if( sqlite3ResolveExprNames(pNC, pE) ){
72713       return 1;
72714     }
72715   }
72716   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
72717 }
72718 
72719 /*
72720 ** Resolve names in the SELECT statement p and all of its descendents.
72721 */
72722 static int resolveSelectStep(Walker *pWalker, Select *p){
72723   NameContext *pOuterNC;  /* Context that contains this SELECT */
72724   NameContext sNC;        /* Name context of this SELECT */
72725   int isCompound;         /* True if p is a compound select */
72726   int nCompound;          /* Number of compound terms processed so far */
72727   Parse *pParse;          /* Parsing context */
72728   ExprList *pEList;       /* Result set expression list */
72729   int i;                  /* Loop counter */
72730   ExprList *pGroupBy;     /* The GROUP BY clause */
72731   Select *pLeftmost;      /* Left-most of SELECT of a compound */
72732   sqlite3 *db;            /* Database connection */
72733 
72734 
72735   assert( p!=0 );
72736   if( p->selFlags & SF_Resolved ){
72737     return WRC_Prune;
72738   }
72739   pOuterNC = pWalker->u.pNC;
72740   pParse = pWalker->pParse;
72741   db = pParse->db;
72742 
72743   /* Normally sqlite3SelectExpand() will be called first and will have
72744   ** already expanded this SELECT.  However, if this is a subquery within
72745   ** an expression, sqlite3ResolveExprNames() will be called without a
72746   ** prior call to sqlite3SelectExpand().  When that happens, let
72747   ** sqlite3SelectPrep() do all of the processing for this SELECT.
72748   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
72749   ** this routine in the correct order.
72750   */
72751   if( (p->selFlags & SF_Expanded)==0 ){
72752     sqlite3SelectPrep(pParse, p, pOuterNC);
72753     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
72754   }
72755 
72756   isCompound = p->pPrior!=0;
72757   nCompound = 0;
72758   pLeftmost = p;
72759   while( p ){
72760     assert( (p->selFlags & SF_Expanded)!=0 );
72761     assert( (p->selFlags & SF_Resolved)==0 );
72762     p->selFlags |= SF_Resolved;
72763 
72764     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
72765     ** are not allowed to refer to any names, so pass an empty NameContext.
72766     */
72767     memset(&sNC, 0, sizeof(sNC));
72768     sNC.pParse = pParse;
72769     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
72770         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
72771       return WRC_Abort;
72772     }
72773 
72774     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
72775     ** resolve the result-set expression list.
72776     */
72777     sNC.allowAgg = 1;
72778     sNC.pSrcList = p->pSrc;
72779     sNC.pNext = pOuterNC;
72780 
72781     /* Resolve names in the result set. */
72782     pEList = p->pEList;
72783     assert( pEList!=0 );
72784     for(i=0; i<pEList->nExpr; i++){
72785       Expr *pX = pEList->a[i].pExpr;
72786       if( sqlite3ResolveExprNames(&sNC, pX) ){
72787         return WRC_Abort;
72788       }
72789     }
72790 
72791     /* Recursively resolve names in all subqueries
72792     */
72793     for(i=0; i<p->pSrc->nSrc; i++){
72794       struct SrcList_item *pItem = &p->pSrc->a[i];
72795       if( pItem->pSelect ){
72796         NameContext *pNC;         /* Used to iterate name contexts */
72797         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
72798         const char *zSavedContext = pParse->zAuthContext;
72799 
72800         /* Count the total number of references to pOuterNC and all of its
72801         ** parent contexts. After resolving references to expressions in
72802         ** pItem->pSelect, check if this value has changed. If so, then
72803         ** SELECT statement pItem->pSelect must be correlated. Set the
72804         ** pItem->isCorrelated flag if this is the case. */
72805         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
72806 
72807         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
72808         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
72809         pParse->zAuthContext = zSavedContext;
72810         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
72811 
72812         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
72813         assert( pItem->isCorrelated==0 && nRef<=0 );
72814         pItem->isCorrelated = (nRef!=0);
72815       }
72816     }
72817 
72818     /* If there are no aggregate functions in the result-set, and no GROUP BY
72819     ** expression, do not allow aggregates in any of the other expressions.
72820     */
72821     assert( (p->selFlags & SF_Aggregate)==0 );
72822     pGroupBy = p->pGroupBy;
72823     if( pGroupBy || sNC.hasAgg ){
72824       p->selFlags |= SF_Aggregate;
72825     }else{
72826       sNC.allowAgg = 0;
72827     }
72828 
72829     /* If a HAVING clause is present, then there must be a GROUP BY clause.
72830     */
72831     if( p->pHaving && !pGroupBy ){
72832       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
72833       return WRC_Abort;
72834     }
72835 
72836     /* Add the expression list to the name-context before parsing the
72837     ** other expressions in the SELECT statement. This is so that
72838     ** expressions in the WHERE clause (etc.) can refer to expressions by
72839     ** aliases in the result set.
72840     **
72841     ** Minor point: If this is the case, then the expression will be
72842     ** re-evaluated for each reference to it.
72843     */
72844     sNC.pEList = p->pEList;
72845     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
72846        sqlite3ResolveExprNames(&sNC, p->pHaving)
72847     ){
72848       return WRC_Abort;
72849     }
72850 
72851     /* The ORDER BY and GROUP BY clauses may not refer to terms in
72852     ** outer queries
72853     */
72854     sNC.pNext = 0;
72855     sNC.allowAgg = 1;
72856 
72857     /* Process the ORDER BY clause for singleton SELECT statements.
72858     ** The ORDER BY clause for compounds SELECT statements is handled
72859     ** below, after all of the result-sets for all of the elements of
72860     ** the compound have been resolved.
72861     */
72862     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
72863       return WRC_Abort;
72864     }
72865     if( db->mallocFailed ){
72866       return WRC_Abort;
72867     }
72868 
72869     /* Resolve the GROUP BY clause.  At the same time, make sure
72870     ** the GROUP BY clause does not contain aggregate functions.
72871     */
72872     if( pGroupBy ){
72873       struct ExprList_item *pItem;
72874 
72875       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
72876         return WRC_Abort;
72877       }
72878       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
72879         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
72880           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
72881               "the GROUP BY clause");
72882           return WRC_Abort;
72883         }
72884       }
72885     }
72886 
72887     /* Advance to the next term of the compound
72888     */
72889     p = p->pPrior;
72890     nCompound++;
72891   }
72892 
72893   /* Resolve the ORDER BY on a compound SELECT after all terms of
72894   ** the compound have been resolved.
72895   */
72896   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
72897     return WRC_Abort;
72898   }
72899 
72900   return WRC_Prune;
72901 }
72902 
72903 /*
72904 ** This routine walks an expression tree and resolves references to
72905 ** table columns and result-set columns.  At the same time, do error
72906 ** checking on function usage and set a flag if any aggregate functions
72907 ** are seen.
72908 **
72909 ** To resolve table columns references we look for nodes (or subtrees) of the
72910 ** form X.Y.Z or Y.Z or just Z where
72911 **
72912 **      X:   The name of a database.  Ex:  "main" or "temp" or
72913 **           the symbolic name assigned to an ATTACH-ed database.
72914 **
72915 **      Y:   The name of a table in a FROM clause.  Or in a trigger
72916 **           one of the special names "old" or "new".
72917 **
72918 **      Z:   The name of a column in table Y.
72919 **
72920 ** The node at the root of the subtree is modified as follows:
72921 **
72922 **    Expr.op        Changed to TK_COLUMN
72923 **    Expr.pTab      Points to the Table object for X.Y
72924 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
72925 **    Expr.iTable    The VDBE cursor number for X.Y
72926 **
72927 **
72928 ** To resolve result-set references, look for expression nodes of the
72929 ** form Z (with no X and Y prefix) where the Z matches the right-hand
72930 ** size of an AS clause in the result-set of a SELECT.  The Z expression
72931 ** is replaced by a copy of the left-hand side of the result-set expression.
72932 ** Table-name and function resolution occurs on the substituted expression
72933 ** tree.  For example, in:
72934 **
72935 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
72936 **
72937 ** The "x" term of the order by is replaced by "a+b" to render:
72938 **
72939 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
72940 **
72941 ** Function calls are checked to make sure that the function is
72942 ** defined and that the correct number of arguments are specified.
72943 ** If the function is an aggregate function, then the pNC->hasAgg is
72944 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
72945 ** If an expression contains aggregate functions then the EP_Agg
72946 ** property on the expression is set.
72947 **
72948 ** An error message is left in pParse if anything is amiss.  The number
72949 ** if errors is returned.
72950 */
72951 SQLITE_PRIVATE int sqlite3ResolveExprNames(
72952   NameContext *pNC,       /* Namespace to resolve expressions in. */
72953   Expr *pExpr             /* The expression to be analyzed. */
72954 ){
72955   int savedHasAgg;
72956   Walker w;
72957 
72958   if( pExpr==0 ) return 0;
72959 #if SQLITE_MAX_EXPR_DEPTH>0
72960   {
72961     Parse *pParse = pNC->pParse;
72962     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
72963       return 1;
72964     }
72965     pParse->nHeight += pExpr->nHeight;
72966   }
72967 #endif
72968   savedHasAgg = pNC->hasAgg;
72969   pNC->hasAgg = 0;
72970   w.xExprCallback = resolveExprStep;
72971   w.xSelectCallback = resolveSelectStep;
72972   w.pParse = pNC->pParse;
72973   w.u.pNC = pNC;
72974   sqlite3WalkExpr(&w, pExpr);
72975 #if SQLITE_MAX_EXPR_DEPTH>0
72976   pNC->pParse->nHeight -= pExpr->nHeight;
72977 #endif
72978   if( pNC->nErr>0 || w.pParse->nErr>0 ){
72979     ExprSetProperty(pExpr, EP_Error);
72980   }
72981   if( pNC->hasAgg ){
72982     ExprSetProperty(pExpr, EP_Agg);
72983   }else if( savedHasAgg ){
72984     pNC->hasAgg = 1;
72985   }
72986   return ExprHasProperty(pExpr, EP_Error);
72987 }
72988 
72989 
72990 /*
72991 ** Resolve all names in all expressions of a SELECT and in all
72992 ** decendents of the SELECT, including compounds off of p->pPrior,
72993 ** subqueries in expressions, and subqueries used as FROM clause
72994 ** terms.
72995 **
72996 ** See sqlite3ResolveExprNames() for a description of the kinds of
72997 ** transformations that occur.
72998 **
72999 ** All SELECT statements should have been expanded using
73000 ** sqlite3SelectExpand() prior to invoking this routine.
73001 */
73002 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
73003   Parse *pParse,         /* The parser context */
73004   Select *p,             /* The SELECT statement being coded. */
73005   NameContext *pOuterNC  /* Name context for parent SELECT statement */
73006 ){
73007   Walker w;
73008 
73009   assert( p!=0 );
73010   w.xExprCallback = resolveExprStep;
73011   w.xSelectCallback = resolveSelectStep;
73012   w.pParse = pParse;
73013   w.u.pNC = pOuterNC;
73014   sqlite3WalkSelect(&w, p);
73015 }
73016 
73017 /************** End of resolve.c *********************************************/
73018 /************** Begin file expr.c ********************************************/
73019 /*
73020 ** 2001 September 15
73021 **
73022 ** The author disclaims copyright to this source code.  In place of
73023 ** a legal notice, here is a blessing:
73024 **
73025 **    May you do good and not evil.
73026 **    May you find forgiveness for yourself and forgive others.
73027 **    May you share freely, never taking more than you give.
73028 **
73029 *************************************************************************
73030 ** This file contains routines used for analyzing expressions and
73031 ** for generating VDBE code that evaluates expressions in SQLite.
73032 */
73033 
73034 /*
73035 ** Return the 'affinity' of the expression pExpr if any.
73036 **
73037 ** If pExpr is a column, a reference to a column via an 'AS' alias,
73038 ** or a sub-select with a column as the return value, then the
73039 ** affinity of that column is returned. Otherwise, 0x00 is returned,
73040 ** indicating no affinity for the expression.
73041 **
73042 ** i.e. the WHERE clause expresssions in the following statements all
73043 ** have an affinity:
73044 **
73045 ** CREATE TABLE t1(a);
73046 ** SELECT * FROM t1 WHERE a;
73047 ** SELECT a AS b FROM t1 WHERE b;
73048 ** SELECT * FROM t1 WHERE (select a from t1);
73049 */
73050 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
73051   int op = pExpr->op;
73052   if( op==TK_SELECT ){
73053     assert( pExpr->flags&EP_xIsSelect );
73054     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
73055   }
73056 #ifndef SQLITE_OMIT_CAST
73057   if( op==TK_CAST ){
73058     assert( !ExprHasProperty(pExpr, EP_IntValue) );
73059     return sqlite3AffinityType(pExpr->u.zToken);
73060   }
73061 #endif
73062   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
73063    && pExpr->pTab!=0
73064   ){
73065     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
73066     ** a TK_COLUMN but was previously evaluated and cached in a register */
73067     int j = pExpr->iColumn;
73068     if( j<0 ) return SQLITE_AFF_INTEGER;
73069     assert( pExpr->pTab && j<pExpr->pTab->nCol );
73070     return pExpr->pTab->aCol[j].affinity;
73071   }
73072   return pExpr->affinity;
73073 }
73074 
73075 /*
73076 ** Set the explicit collating sequence for an expression to the
73077 ** collating sequence supplied in the second argument.
73078 */
73079 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
73080   if( pExpr && pColl ){
73081     pExpr->pColl = pColl;
73082     pExpr->flags |= EP_ExpCollate;
73083   }
73084   return pExpr;
73085 }
73086 
73087 /*
73088 ** Set the collating sequence for expression pExpr to be the collating
73089 ** sequence named by pToken.   Return a pointer to the revised expression.
73090 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
73091 ** flag.  An explicit collating sequence will override implicit
73092 ** collating sequences.
73093 */
73094 SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
73095   char *zColl = 0;            /* Dequoted name of collation sequence */
73096   CollSeq *pColl;
73097   sqlite3 *db = pParse->db;
73098   zColl = sqlite3NameFromToken(db, pCollName);
73099   pColl = sqlite3LocateCollSeq(pParse, zColl);
73100   sqlite3ExprSetColl(pExpr, pColl);
73101   sqlite3DbFree(db, zColl);
73102   return pExpr;
73103 }
73104 
73105 /*
73106 ** Return the default collation sequence for the expression pExpr. If
73107 ** there is no default collation type, return 0.
73108 */
73109 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
73110   CollSeq *pColl = 0;
73111   Expr *p = pExpr;
73112   while( p ){
73113     int op;
73114     pColl = p->pColl;
73115     if( pColl ) break;
73116     op = p->op;
73117     if( p->pTab!=0 && (
73118         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
73119     )){
73120       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
73121       ** a TK_COLUMN but was previously evaluated and cached in a register */
73122       const char *zColl;
73123       int j = p->iColumn;
73124       if( j>=0 ){
73125         sqlite3 *db = pParse->db;
73126         zColl = p->pTab->aCol[j].zColl;
73127         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
73128         pExpr->pColl = pColl;
73129       }
73130       break;
73131     }
73132     if( op!=TK_CAST && op!=TK_UPLUS ){
73133       break;
73134     }
73135     p = p->pLeft;
73136   }
73137   if( sqlite3CheckCollSeq(pParse, pColl) ){
73138     pColl = 0;
73139   }
73140   return pColl;
73141 }
73142 
73143 /*
73144 ** pExpr is an operand of a comparison operator.  aff2 is the
73145 ** type affinity of the other operand.  This routine returns the
73146 ** type affinity that should be used for the comparison operator.
73147 */
73148 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
73149   char aff1 = sqlite3ExprAffinity(pExpr);
73150   if( aff1 && aff2 ){
73151     /* Both sides of the comparison are columns. If one has numeric
73152     ** affinity, use that. Otherwise use no affinity.
73153     */
73154     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
73155       return SQLITE_AFF_NUMERIC;
73156     }else{
73157       return SQLITE_AFF_NONE;
73158     }
73159   }else if( !aff1 && !aff2 ){
73160     /* Neither side of the comparison is a column.  Compare the
73161     ** results directly.
73162     */
73163     return SQLITE_AFF_NONE;
73164   }else{
73165     /* One side is a column, the other is not. Use the columns affinity. */
73166     assert( aff1==0 || aff2==0 );
73167     return (aff1 + aff2);
73168   }
73169 }
73170 
73171 /*
73172 ** pExpr is a comparison operator.  Return the type affinity that should
73173 ** be applied to both operands prior to doing the comparison.
73174 */
73175 static char comparisonAffinity(Expr *pExpr){
73176   char aff;
73177   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
73178           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
73179           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
73180   assert( pExpr->pLeft );
73181   aff = sqlite3ExprAffinity(pExpr->pLeft);
73182   if( pExpr->pRight ){
73183     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
73184   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73185     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
73186   }else if( !aff ){
73187     aff = SQLITE_AFF_NONE;
73188   }
73189   return aff;
73190 }
73191 
73192 /*
73193 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
73194 ** idx_affinity is the affinity of an indexed column. Return true
73195 ** if the index with affinity idx_affinity may be used to implement
73196 ** the comparison in pExpr.
73197 */
73198 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
73199   char aff = comparisonAffinity(pExpr);
73200   switch( aff ){
73201     case SQLITE_AFF_NONE:
73202       return 1;
73203     case SQLITE_AFF_TEXT:
73204       return idx_affinity==SQLITE_AFF_TEXT;
73205     default:
73206       return sqlite3IsNumericAffinity(idx_affinity);
73207   }
73208 }
73209 
73210 /*
73211 ** Return the P5 value that should be used for a binary comparison
73212 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
73213 */
73214 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
73215   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
73216   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
73217   return aff;
73218 }
73219 
73220 /*
73221 ** Return a pointer to the collation sequence that should be used by
73222 ** a binary comparison operator comparing pLeft and pRight.
73223 **
73224 ** If the left hand expression has a collating sequence type, then it is
73225 ** used. Otherwise the collation sequence for the right hand expression
73226 ** is used, or the default (BINARY) if neither expression has a collating
73227 ** type.
73228 **
73229 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
73230 ** it is not considered.
73231 */
73232 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
73233   Parse *pParse,
73234   Expr *pLeft,
73235   Expr *pRight
73236 ){
73237   CollSeq *pColl;
73238   assert( pLeft );
73239   if( pLeft->flags & EP_ExpCollate ){
73240     assert( pLeft->pColl );
73241     pColl = pLeft->pColl;
73242   }else if( pRight && pRight->flags & EP_ExpCollate ){
73243     assert( pRight->pColl );
73244     pColl = pRight->pColl;
73245   }else{
73246     pColl = sqlite3ExprCollSeq(pParse, pLeft);
73247     if( !pColl ){
73248       pColl = sqlite3ExprCollSeq(pParse, pRight);
73249     }
73250   }
73251   return pColl;
73252 }
73253 
73254 /*
73255 ** Generate code for a comparison operator.
73256 */
73257 static int codeCompare(
73258   Parse *pParse,    /* The parsing (and code generating) context */
73259   Expr *pLeft,      /* The left operand */
73260   Expr *pRight,     /* The right operand */
73261   int opcode,       /* The comparison opcode */
73262   int in1, int in2, /* Register holding operands */
73263   int dest,         /* Jump here if true.  */
73264   int jumpIfNull    /* If true, jump if either operand is NULL */
73265 ){
73266   int p5;
73267   int addr;
73268   CollSeq *p4;
73269 
73270   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
73271   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
73272   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
73273                            (void*)p4, P4_COLLSEQ);
73274   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
73275   return addr;
73276 }
73277 
73278 #if SQLITE_MAX_EXPR_DEPTH>0
73279 /*
73280 ** Check that argument nHeight is less than or equal to the maximum
73281 ** expression depth allowed. If it is not, leave an error message in
73282 ** pParse.
73283 */
73284 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
73285   int rc = SQLITE_OK;
73286   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
73287   if( nHeight>mxHeight ){
73288     sqlite3ErrorMsg(pParse,
73289        "Expression tree is too large (maximum depth %d)", mxHeight
73290     );
73291     rc = SQLITE_ERROR;
73292   }
73293   return rc;
73294 }
73295 
73296 /* The following three functions, heightOfExpr(), heightOfExprList()
73297 ** and heightOfSelect(), are used to determine the maximum height
73298 ** of any expression tree referenced by the structure passed as the
73299 ** first argument.
73300 **
73301 ** If this maximum height is greater than the current value pointed
73302 ** to by pnHeight, the second parameter, then set *pnHeight to that
73303 ** value.
73304 */
73305 static void heightOfExpr(Expr *p, int *pnHeight){
73306   if( p ){
73307     if( p->nHeight>*pnHeight ){
73308       *pnHeight = p->nHeight;
73309     }
73310   }
73311 }
73312 static void heightOfExprList(ExprList *p, int *pnHeight){
73313   if( p ){
73314     int i;
73315     for(i=0; i<p->nExpr; i++){
73316       heightOfExpr(p->a[i].pExpr, pnHeight);
73317     }
73318   }
73319 }
73320 static void heightOfSelect(Select *p, int *pnHeight){
73321   if( p ){
73322     heightOfExpr(p->pWhere, pnHeight);
73323     heightOfExpr(p->pHaving, pnHeight);
73324     heightOfExpr(p->pLimit, pnHeight);
73325     heightOfExpr(p->pOffset, pnHeight);
73326     heightOfExprList(p->pEList, pnHeight);
73327     heightOfExprList(p->pGroupBy, pnHeight);
73328     heightOfExprList(p->pOrderBy, pnHeight);
73329     heightOfSelect(p->pPrior, pnHeight);
73330   }
73331 }
73332 
73333 /*
73334 ** Set the Expr.nHeight variable in the structure passed as an
73335 ** argument. An expression with no children, Expr.pList or
73336 ** Expr.pSelect member has a height of 1. Any other expression
73337 ** has a height equal to the maximum height of any other
73338 ** referenced Expr plus one.
73339 */
73340 static void exprSetHeight(Expr *p){
73341   int nHeight = 0;
73342   heightOfExpr(p->pLeft, &nHeight);
73343   heightOfExpr(p->pRight, &nHeight);
73344   if( ExprHasProperty(p, EP_xIsSelect) ){
73345     heightOfSelect(p->x.pSelect, &nHeight);
73346   }else{
73347     heightOfExprList(p->x.pList, &nHeight);
73348   }
73349   p->nHeight = nHeight + 1;
73350 }
73351 
73352 /*
73353 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
73354 ** the height is greater than the maximum allowed expression depth,
73355 ** leave an error in pParse.
73356 */
73357 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
73358   exprSetHeight(p);
73359   sqlite3ExprCheckHeight(pParse, p->nHeight);
73360 }
73361 
73362 /*
73363 ** Return the maximum height of any expression tree referenced
73364 ** by the select statement passed as an argument.
73365 */
73366 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
73367   int nHeight = 0;
73368   heightOfSelect(p, &nHeight);
73369   return nHeight;
73370 }
73371 #else
73372   #define exprSetHeight(y)
73373 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
73374 
73375 /*
73376 ** This routine is the core allocator for Expr nodes.
73377 **
73378 ** Construct a new expression node and return a pointer to it.  Memory
73379 ** for this node and for the pToken argument is a single allocation
73380 ** obtained from sqlite3DbMalloc().  The calling function
73381 ** is responsible for making sure the node eventually gets freed.
73382 **
73383 ** If dequote is true, then the token (if it exists) is dequoted.
73384 ** If dequote is false, no dequoting is performance.  The deQuote
73385 ** parameter is ignored if pToken is NULL or if the token does not
73386 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
73387 ** then the EP_DblQuoted flag is set on the expression node.
73388 **
73389 ** Special case:  If op==TK_INTEGER and pToken points to a string that
73390 ** can be translated into a 32-bit integer, then the token is not
73391 ** stored in u.zToken.  Instead, the integer values is written
73392 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
73393 ** is allocated to hold the integer text and the dequote flag is ignored.
73394 */
73395 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
73396   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
73397   int op,                 /* Expression opcode */
73398   const Token *pToken,    /* Token argument.  Might be NULL */
73399   int dequote             /* True to dequote */
73400 ){
73401   Expr *pNew;
73402   int nExtra = 0;
73403   int iValue = 0;
73404 
73405   if( pToken ){
73406     if( op!=TK_INTEGER || pToken->z==0
73407           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
73408       nExtra = pToken->n+1;
73409       assert( iValue>=0 );
73410     }
73411   }
73412   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
73413   if( pNew ){
73414     pNew->op = (u8)op;
73415     pNew->iAgg = -1;
73416     if( pToken ){
73417       if( nExtra==0 ){
73418         pNew->flags |= EP_IntValue;
73419         pNew->u.iValue = iValue;
73420       }else{
73421         int c;
73422         pNew->u.zToken = (char*)&pNew[1];
73423         memcpy(pNew->u.zToken, pToken->z, pToken->n);
73424         pNew->u.zToken[pToken->n] = 0;
73425         if( dequote && nExtra>=3
73426              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
73427           sqlite3Dequote(pNew->u.zToken);
73428           if( c=='"' ) pNew->flags |= EP_DblQuoted;
73429         }
73430       }
73431     }
73432 #if SQLITE_MAX_EXPR_DEPTH>0
73433     pNew->nHeight = 1;
73434 #endif
73435   }
73436   return pNew;
73437 }
73438 
73439 /*
73440 ** Allocate a new expression node from a zero-terminated token that has
73441 ** already been dequoted.
73442 */
73443 SQLITE_PRIVATE Expr *sqlite3Expr(
73444   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
73445   int op,                 /* Expression opcode */
73446   const char *zToken      /* Token argument.  Might be NULL */
73447 ){
73448   Token x;
73449   x.z = zToken;
73450   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
73451   return sqlite3ExprAlloc(db, op, &x, 0);
73452 }
73453 
73454 /*
73455 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
73456 **
73457 ** If pRoot==NULL that means that a memory allocation error has occurred.
73458 ** In that case, delete the subtrees pLeft and pRight.
73459 */
73460 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
73461   sqlite3 *db,
73462   Expr *pRoot,
73463   Expr *pLeft,
73464   Expr *pRight
73465 ){
73466   if( pRoot==0 ){
73467     assert( db->mallocFailed );
73468     sqlite3ExprDelete(db, pLeft);
73469     sqlite3ExprDelete(db, pRight);
73470   }else{
73471     if( pRight ){
73472       pRoot->pRight = pRight;
73473       if( pRight->flags & EP_ExpCollate ){
73474         pRoot->flags |= EP_ExpCollate;
73475         pRoot->pColl = pRight->pColl;
73476       }
73477     }
73478     if( pLeft ){
73479       pRoot->pLeft = pLeft;
73480       if( pLeft->flags & EP_ExpCollate ){
73481         pRoot->flags |= EP_ExpCollate;
73482         pRoot->pColl = pLeft->pColl;
73483       }
73484     }
73485     exprSetHeight(pRoot);
73486   }
73487 }
73488 
73489 /*
73490 ** Allocate a Expr node which joins as many as two subtrees.
73491 **
73492 ** One or both of the subtrees can be NULL.  Return a pointer to the new
73493 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
73494 ** free the subtrees and return NULL.
73495 */
73496 SQLITE_PRIVATE Expr *sqlite3PExpr(
73497   Parse *pParse,          /* Parsing context */
73498   int op,                 /* Expression opcode */
73499   Expr *pLeft,            /* Left operand */
73500   Expr *pRight,           /* Right operand */
73501   const Token *pToken     /* Argument token */
73502 ){
73503   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
73504   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
73505   if( p ) {
73506     sqlite3ExprCheckHeight(pParse, p->nHeight);
73507   }
73508   return p;
73509 }
73510 
73511 /*
73512 ** Join two expressions using an AND operator.  If either expression is
73513 ** NULL, then just return the other expression.
73514 */
73515 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
73516   if( pLeft==0 ){
73517     return pRight;
73518   }else if( pRight==0 ){
73519     return pLeft;
73520   }else{
73521     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
73522     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
73523     return pNew;
73524   }
73525 }
73526 
73527 /*
73528 ** Construct a new expression node for a function with multiple
73529 ** arguments.
73530 */
73531 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
73532   Expr *pNew;
73533   sqlite3 *db = pParse->db;
73534   assert( pToken );
73535   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
73536   if( pNew==0 ){
73537     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
73538     return 0;
73539   }
73540   pNew->x.pList = pList;
73541   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
73542   sqlite3ExprSetHeight(pParse, pNew);
73543   return pNew;
73544 }
73545 
73546 /*
73547 ** Assign a variable number to an expression that encodes a wildcard
73548 ** in the original SQL statement.
73549 **
73550 ** Wildcards consisting of a single "?" are assigned the next sequential
73551 ** variable number.
73552 **
73553 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
73554 ** sure "nnn" is not too be to avoid a denial of service attack when
73555 ** the SQL statement comes from an external source.
73556 **
73557 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
73558 ** as the previous instance of the same wildcard.  Or if this is the first
73559 ** instance of the wildcard, the next sequenial variable number is
73560 ** assigned.
73561 */
73562 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
73563   sqlite3 *db = pParse->db;
73564   const char *z;
73565 
73566   if( pExpr==0 ) return;
73567   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
73568   z = pExpr->u.zToken;
73569   assert( z!=0 );
73570   assert( z[0]!=0 );
73571   if( z[1]==0 ){
73572     /* Wildcard of the form "?".  Assign the next variable number */
73573     assert( z[0]=='?' );
73574     pExpr->iColumn = (ynVar)(++pParse->nVar);
73575   }else{
73576     ynVar x = 0;
73577     u32 n = sqlite3Strlen30(z);
73578     if( z[0]=='?' ){
73579       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
73580       ** use it as the variable number */
73581       i64 i;
73582       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
73583       pExpr->iColumn = x = (ynVar)i;
73584       testcase( i==0 );
73585       testcase( i==1 );
73586       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
73587       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
73588       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73589         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
73590             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
73591         x = 0;
73592       }
73593       if( i>pParse->nVar ){
73594         pParse->nVar = (int)i;
73595       }
73596     }else{
73597       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
73598       ** number as the prior appearance of the same name, or if the name
73599       ** has never appeared before, reuse the same variable number
73600       */
73601       ynVar i;
73602       for(i=0; i<pParse->nzVar; i++){
73603         if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
73604           pExpr->iColumn = x = (ynVar)i+1;
73605           break;
73606         }
73607       }
73608       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
73609     }
73610     if( x>0 ){
73611       if( x>pParse->nzVar ){
73612         char **a;
73613         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
73614         if( a==0 ) return;  /* Error reported through db->mallocFailed */
73615         pParse->azVar = a;
73616         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
73617         pParse->nzVar = x;
73618       }
73619       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
73620         sqlite3DbFree(db, pParse->azVar[x-1]);
73621         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
73622       }
73623     }
73624   }
73625   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
73626     sqlite3ErrorMsg(pParse, "too many SQL variables");
73627   }
73628 }
73629 
73630 /*
73631 ** Recursively delete an expression tree.
73632 */
73633 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
73634   if( p==0 ) return;
73635   /* Sanity check: Assert that the IntValue is non-negative if it exists */
73636   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
73637   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
73638     sqlite3ExprDelete(db, p->pLeft);
73639     sqlite3ExprDelete(db, p->pRight);
73640     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
73641       sqlite3DbFree(db, p->u.zToken);
73642     }
73643     if( ExprHasProperty(p, EP_xIsSelect) ){
73644       sqlite3SelectDelete(db, p->x.pSelect);
73645     }else{
73646       sqlite3ExprListDelete(db, p->x.pList);
73647     }
73648   }
73649   if( !ExprHasProperty(p, EP_Static) ){
73650     sqlite3DbFree(db, p);
73651   }
73652 }
73653 
73654 /*
73655 ** Return the number of bytes allocated for the expression structure
73656 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
73657 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
73658 */
73659 static int exprStructSize(Expr *p){
73660   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
73661   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
73662   return EXPR_FULLSIZE;
73663 }
73664 
73665 /*
73666 ** The dupedExpr*Size() routines each return the number of bytes required
73667 ** to store a copy of an expression or expression tree.  They differ in
73668 ** how much of the tree is measured.
73669 **
73670 **     dupedExprStructSize()     Size of only the Expr structure
73671 **     dupedExprNodeSize()       Size of Expr + space for token
73672 **     dupedExprSize()           Expr + token + subtree components
73673 **
73674 ***************************************************************************
73675 **
73676 ** The dupedExprStructSize() function returns two values OR-ed together:
73677 ** (1) the space required for a copy of the Expr structure only and
73678 ** (2) the EP_xxx flags that indicate what the structure size should be.
73679 ** The return values is always one of:
73680 **
73681 **      EXPR_FULLSIZE
73682 **      EXPR_REDUCEDSIZE   | EP_Reduced
73683 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
73684 **
73685 ** The size of the structure can be found by masking the return value
73686 ** of this routine with 0xfff.  The flags can be found by masking the
73687 ** return value with EP_Reduced|EP_TokenOnly.
73688 **
73689 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
73690 ** (unreduced) Expr objects as they or originally constructed by the parser.
73691 ** During expression analysis, extra information is computed and moved into
73692 ** later parts of teh Expr object and that extra information might get chopped
73693 ** off if the expression is reduced.  Note also that it does not work to
73694 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
73695 ** to reduce a pristine expression tree from the parser.  The implementation
73696 ** of dupedExprStructSize() contain multiple assert() statements that attempt
73697 ** to enforce this constraint.
73698 */
73699 static int dupedExprStructSize(Expr *p, int flags){
73700   int nSize;
73701   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
73702   if( 0==(flags&EXPRDUP_REDUCE) ){
73703     nSize = EXPR_FULLSIZE;
73704   }else{
73705     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
73706     assert( !ExprHasProperty(p, EP_FromJoin) );
73707     assert( (p->flags2 & EP2_MallocedToken)==0 );
73708     assert( (p->flags2 & EP2_Irreducible)==0 );
73709     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
73710       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
73711     }else{
73712       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
73713     }
73714   }
73715   return nSize;
73716 }
73717 
73718 /*
73719 ** This function returns the space in bytes required to store the copy
73720 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
73721 ** string is defined.)
73722 */
73723 static int dupedExprNodeSize(Expr *p, int flags){
73724   int nByte = dupedExprStructSize(p, flags) & 0xfff;
73725   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
73726     nByte += sqlite3Strlen30(p->u.zToken)+1;
73727   }
73728   return ROUND8(nByte);
73729 }
73730 
73731 /*
73732 ** Return the number of bytes required to create a duplicate of the
73733 ** expression passed as the first argument. The second argument is a
73734 ** mask containing EXPRDUP_XXX flags.
73735 **
73736 ** The value returned includes space to create a copy of the Expr struct
73737 ** itself and the buffer referred to by Expr.u.zToken, if any.
73738 **
73739 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
73740 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
73741 ** and Expr.pRight variables (but not for any structures pointed to or
73742 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
73743 */
73744 static int dupedExprSize(Expr *p, int flags){
73745   int nByte = 0;
73746   if( p ){
73747     nByte = dupedExprNodeSize(p, flags);
73748     if( flags&EXPRDUP_REDUCE ){
73749       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
73750     }
73751   }
73752   return nByte;
73753 }
73754 
73755 /*
73756 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
73757 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
73758 ** to store the copy of expression p, the copies of p->u.zToken
73759 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
73760 ** if any. Before returning, *pzBuffer is set to the first byte passed the
73761 ** portion of the buffer copied into by this function.
73762 */
73763 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
73764   Expr *pNew = 0;                      /* Value to return */
73765   if( p ){
73766     const int isReduced = (flags&EXPRDUP_REDUCE);
73767     u8 *zAlloc;
73768     u32 staticFlag = 0;
73769 
73770     assert( pzBuffer==0 || isReduced );
73771 
73772     /* Figure out where to write the new Expr structure. */
73773     if( pzBuffer ){
73774       zAlloc = *pzBuffer;
73775       staticFlag = EP_Static;
73776     }else{
73777       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
73778     }
73779     pNew = (Expr *)zAlloc;
73780 
73781     if( pNew ){
73782       /* Set nNewSize to the size allocated for the structure pointed to
73783       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
73784       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
73785       ** by the copy of the p->u.zToken string (if any).
73786       */
73787       const unsigned nStructSize = dupedExprStructSize(p, flags);
73788       const int nNewSize = nStructSize & 0xfff;
73789       int nToken;
73790       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
73791         nToken = sqlite3Strlen30(p->u.zToken) + 1;
73792       }else{
73793         nToken = 0;
73794       }
73795       if( isReduced ){
73796         assert( ExprHasProperty(p, EP_Reduced)==0 );
73797         memcpy(zAlloc, p, nNewSize);
73798       }else{
73799         int nSize = exprStructSize(p);
73800         memcpy(zAlloc, p, nSize);
73801         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
73802       }
73803 
73804       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
73805       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
73806       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
73807       pNew->flags |= staticFlag;
73808 
73809       /* Copy the p->u.zToken string, if any. */
73810       if( nToken ){
73811         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
73812         memcpy(zToken, p->u.zToken, nToken);
73813       }
73814 
73815       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
73816         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
73817         if( ExprHasProperty(p, EP_xIsSelect) ){
73818           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
73819         }else{
73820           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
73821         }
73822       }
73823 
73824       /* Fill in pNew->pLeft and pNew->pRight. */
73825       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
73826         zAlloc += dupedExprNodeSize(p, flags);
73827         if( ExprHasProperty(pNew, EP_Reduced) ){
73828           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
73829           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
73830         }
73831         if( pzBuffer ){
73832           *pzBuffer = zAlloc;
73833         }
73834       }else{
73835         pNew->flags2 = 0;
73836         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
73837           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
73838           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
73839         }
73840       }
73841 
73842     }
73843   }
73844   return pNew;
73845 }
73846 
73847 /*
73848 ** The following group of routines make deep copies of expressions,
73849 ** expression lists, ID lists, and select statements.  The copies can
73850 ** be deleted (by being passed to their respective ...Delete() routines)
73851 ** without effecting the originals.
73852 **
73853 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
73854 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
73855 ** by subsequent calls to sqlite*ListAppend() routines.
73856 **
73857 ** Any tables that the SrcList might point to are not duplicated.
73858 **
73859 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
73860 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
73861 ** truncated version of the usual Expr structure that will be stored as
73862 ** part of the in-memory representation of the database schema.
73863 */
73864 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
73865   return exprDup(db, p, flags, 0);
73866 }
73867 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
73868   ExprList *pNew;
73869   struct ExprList_item *pItem, *pOldItem;
73870   int i;
73871   if( p==0 ) return 0;
73872   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
73873   if( pNew==0 ) return 0;
73874   pNew->iECursor = 0;
73875   pNew->nExpr = pNew->nAlloc = p->nExpr;
73876   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
73877   if( pItem==0 ){
73878     sqlite3DbFree(db, pNew);
73879     return 0;
73880   }
73881   pOldItem = p->a;
73882   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
73883     Expr *pOldExpr = pOldItem->pExpr;
73884     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
73885     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73886     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
73887     pItem->sortOrder = pOldItem->sortOrder;
73888     pItem->done = 0;
73889     pItem->iCol = pOldItem->iCol;
73890     pItem->iAlias = pOldItem->iAlias;
73891   }
73892   return pNew;
73893 }
73894 
73895 /*
73896 ** If cursors, triggers, views and subqueries are all omitted from
73897 ** the build, then none of the following routines, except for
73898 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
73899 ** called with a NULL argument.
73900 */
73901 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
73902  || !defined(SQLITE_OMIT_SUBQUERY)
73903 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
73904   SrcList *pNew;
73905   int i;
73906   int nByte;
73907   if( p==0 ) return 0;
73908   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
73909   pNew = sqlite3DbMallocRaw(db, nByte );
73910   if( pNew==0 ) return 0;
73911   pNew->nSrc = pNew->nAlloc = p->nSrc;
73912   for(i=0; i<p->nSrc; i++){
73913     struct SrcList_item *pNewItem = &pNew->a[i];
73914     struct SrcList_item *pOldItem = &p->a[i];
73915     Table *pTab;
73916     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
73917     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73918     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
73919     pNewItem->jointype = pOldItem->jointype;
73920     pNewItem->iCursor = pOldItem->iCursor;
73921     pNewItem->addrFillSub = pOldItem->addrFillSub;
73922     pNewItem->regReturn = pOldItem->regReturn;
73923     pNewItem->isCorrelated = pOldItem->isCorrelated;
73924     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
73925     pNewItem->notIndexed = pOldItem->notIndexed;
73926     pNewItem->pIndex = pOldItem->pIndex;
73927     pTab = pNewItem->pTab = pOldItem->pTab;
73928     if( pTab ){
73929       pTab->nRef++;
73930     }
73931     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
73932     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
73933     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
73934     pNewItem->colUsed = pOldItem->colUsed;
73935   }
73936   return pNew;
73937 }
73938 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
73939   IdList *pNew;
73940   int i;
73941   if( p==0 ) return 0;
73942   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
73943   if( pNew==0 ) return 0;
73944   pNew->nId = pNew->nAlloc = p->nId;
73945   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
73946   if( pNew->a==0 ){
73947     sqlite3DbFree(db, pNew);
73948     return 0;
73949   }
73950   for(i=0; i<p->nId; i++){
73951     struct IdList_item *pNewItem = &pNew->a[i];
73952     struct IdList_item *pOldItem = &p->a[i];
73953     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
73954     pNewItem->idx = pOldItem->idx;
73955   }
73956   return pNew;
73957 }
73958 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
73959   Select *pNew;
73960   if( p==0 ) return 0;
73961   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
73962   if( pNew==0 ) return 0;
73963   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
73964   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
73965   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
73966   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
73967   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
73968   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
73969   pNew->op = p->op;
73970   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
73971   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
73972   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
73973   pNew->iLimit = 0;
73974   pNew->iOffset = 0;
73975   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
73976   pNew->pRightmost = 0;
73977   pNew->addrOpenEphm[0] = -1;
73978   pNew->addrOpenEphm[1] = -1;
73979   pNew->addrOpenEphm[2] = -1;
73980   return pNew;
73981 }
73982 #else
73983 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
73984   assert( p==0 );
73985   return 0;
73986 }
73987 #endif
73988 
73989 
73990 /*
73991 ** Add a new element to the end of an expression list.  If pList is
73992 ** initially NULL, then create a new expression list.
73993 **
73994 ** If a memory allocation error occurs, the entire list is freed and
73995 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
73996 ** that the new entry was successfully appended.
73997 */
73998 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
73999   Parse *pParse,          /* Parsing context */
74000   ExprList *pList,        /* List to which to append. Might be NULL */
74001   Expr *pExpr             /* Expression to be appended. Might be NULL */
74002 ){
74003   sqlite3 *db = pParse->db;
74004   if( pList==0 ){
74005     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
74006     if( pList==0 ){
74007       goto no_mem;
74008     }
74009     assert( pList->nAlloc==0 );
74010   }
74011   if( pList->nAlloc<=pList->nExpr ){
74012     struct ExprList_item *a;
74013     int n = pList->nAlloc*2 + 4;
74014     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
74015     if( a==0 ){
74016       goto no_mem;
74017     }
74018     pList->a = a;
74019     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
74020   }
74021   assert( pList->a!=0 );
74022   if( 1 ){
74023     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
74024     memset(pItem, 0, sizeof(*pItem));
74025     pItem->pExpr = pExpr;
74026   }
74027   return pList;
74028 
74029 no_mem:
74030   /* Avoid leaking memory if malloc has failed. */
74031   sqlite3ExprDelete(db, pExpr);
74032   sqlite3ExprListDelete(db, pList);
74033   return 0;
74034 }
74035 
74036 /*
74037 ** Set the ExprList.a[].zName element of the most recently added item
74038 ** on the expression list.
74039 **
74040 ** pList might be NULL following an OOM error.  But pName should never be
74041 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74042 ** is set.
74043 */
74044 SQLITE_PRIVATE void sqlite3ExprListSetName(
74045   Parse *pParse,          /* Parsing context */
74046   ExprList *pList,        /* List to which to add the span. */
74047   Token *pName,           /* Name to be added */
74048   int dequote             /* True to cause the name to be dequoted */
74049 ){
74050   assert( pList!=0 || pParse->db->mallocFailed!=0 );
74051   if( pList ){
74052     struct ExprList_item *pItem;
74053     assert( pList->nExpr>0 );
74054     pItem = &pList->a[pList->nExpr-1];
74055     assert( pItem->zName==0 );
74056     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
74057     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
74058   }
74059 }
74060 
74061 /*
74062 ** Set the ExprList.a[].zSpan element of the most recently added item
74063 ** on the expression list.
74064 **
74065 ** pList might be NULL following an OOM error.  But pSpan should never be
74066 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
74067 ** is set.
74068 */
74069 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
74070   Parse *pParse,          /* Parsing context */
74071   ExprList *pList,        /* List to which to add the span. */
74072   ExprSpan *pSpan         /* The span to be added */
74073 ){
74074   sqlite3 *db = pParse->db;
74075   assert( pList!=0 || db->mallocFailed!=0 );
74076   if( pList ){
74077     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
74078     assert( pList->nExpr>0 );
74079     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
74080     sqlite3DbFree(db, pItem->zSpan);
74081     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
74082                                     (int)(pSpan->zEnd - pSpan->zStart));
74083   }
74084 }
74085 
74086 /*
74087 ** If the expression list pEList contains more than iLimit elements,
74088 ** leave an error message in pParse.
74089 */
74090 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
74091   Parse *pParse,
74092   ExprList *pEList,
74093   const char *zObject
74094 ){
74095   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
74096   testcase( pEList && pEList->nExpr==mx );
74097   testcase( pEList && pEList->nExpr==mx+1 );
74098   if( pEList && pEList->nExpr>mx ){
74099     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
74100   }
74101 }
74102 
74103 /*
74104 ** Delete an entire expression list.
74105 */
74106 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
74107   int i;
74108   struct ExprList_item *pItem;
74109   if( pList==0 ) return;
74110   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
74111   assert( pList->nExpr<=pList->nAlloc );
74112   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
74113     sqlite3ExprDelete(db, pItem->pExpr);
74114     sqlite3DbFree(db, pItem->zName);
74115     sqlite3DbFree(db, pItem->zSpan);
74116   }
74117   sqlite3DbFree(db, pList->a);
74118   sqlite3DbFree(db, pList);
74119 }
74120 
74121 /*
74122 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
74123 ** to an integer.  These routines are checking an expression to see
74124 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
74125 ** not constant.
74126 **
74127 ** These callback routines are used to implement the following:
74128 **
74129 **     sqlite3ExprIsConstant()
74130 **     sqlite3ExprIsConstantNotJoin()
74131 **     sqlite3ExprIsConstantOrFunction()
74132 **
74133 */
74134 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
74135 
74136   /* If pWalker->u.i is 3 then any term of the expression that comes from
74137   ** the ON or USING clauses of a join disqualifies the expression
74138   ** from being considered constant. */
74139   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
74140     pWalker->u.i = 0;
74141     return WRC_Abort;
74142   }
74143 
74144   switch( pExpr->op ){
74145     /* Consider functions to be constant if all their arguments are constant
74146     ** and pWalker->u.i==2 */
74147     case TK_FUNCTION:
74148       if( pWalker->u.i==2 ) return 0;
74149       /* Fall through */
74150     case TK_ID:
74151     case TK_COLUMN:
74152     case TK_AGG_FUNCTION:
74153     case TK_AGG_COLUMN:
74154       testcase( pExpr->op==TK_ID );
74155       testcase( pExpr->op==TK_COLUMN );
74156       testcase( pExpr->op==TK_AGG_FUNCTION );
74157       testcase( pExpr->op==TK_AGG_COLUMN );
74158       pWalker->u.i = 0;
74159       return WRC_Abort;
74160     default:
74161       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
74162       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
74163       return WRC_Continue;
74164   }
74165 }
74166 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
74167   UNUSED_PARAMETER(NotUsed);
74168   pWalker->u.i = 0;
74169   return WRC_Abort;
74170 }
74171 static int exprIsConst(Expr *p, int initFlag){
74172   Walker w;
74173   w.u.i = initFlag;
74174   w.xExprCallback = exprNodeIsConstant;
74175   w.xSelectCallback = selectNodeIsConstant;
74176   sqlite3WalkExpr(&w, p);
74177   return w.u.i;
74178 }
74179 
74180 /*
74181 ** Walk an expression tree.  Return 1 if the expression is constant
74182 ** and 0 if it involves variables or function calls.
74183 **
74184 ** For the purposes of this function, a double-quoted string (ex: "abc")
74185 ** is considered a variable but a single-quoted string (ex: 'abc') is
74186 ** a constant.
74187 */
74188 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
74189   return exprIsConst(p, 1);
74190 }
74191 
74192 /*
74193 ** Walk an expression tree.  Return 1 if the expression is constant
74194 ** that does no originate from the ON or USING clauses of a join.
74195 ** Return 0 if it involves variables or function calls or terms from
74196 ** an ON or USING clause.
74197 */
74198 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
74199   return exprIsConst(p, 3);
74200 }
74201 
74202 /*
74203 ** Walk an expression tree.  Return 1 if the expression is constant
74204 ** or a function call with constant arguments.  Return and 0 if there
74205 ** are any variables.
74206 **
74207 ** For the purposes of this function, a double-quoted string (ex: "abc")
74208 ** is considered a variable but a single-quoted string (ex: 'abc') is
74209 ** a constant.
74210 */
74211 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
74212   return exprIsConst(p, 2);
74213 }
74214 
74215 /*
74216 ** If the expression p codes a constant integer that is small enough
74217 ** to fit in a 32-bit integer, return 1 and put the value of the integer
74218 ** in *pValue.  If the expression is not an integer or if it is too big
74219 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
74220 */
74221 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
74222   int rc = 0;
74223 
74224   /* If an expression is an integer literal that fits in a signed 32-bit
74225   ** integer, then the EP_IntValue flag will have already been set */
74226   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
74227            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
74228 
74229   if( p->flags & EP_IntValue ){
74230     *pValue = p->u.iValue;
74231     return 1;
74232   }
74233   switch( p->op ){
74234     case TK_UPLUS: {
74235       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
74236       break;
74237     }
74238     case TK_UMINUS: {
74239       int v;
74240       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
74241         *pValue = -v;
74242         rc = 1;
74243       }
74244       break;
74245     }
74246     default: break;
74247   }
74248   return rc;
74249 }
74250 
74251 /*
74252 ** Return FALSE if there is no chance that the expression can be NULL.
74253 **
74254 ** If the expression might be NULL or if the expression is too complex
74255 ** to tell return TRUE.
74256 **
74257 ** This routine is used as an optimization, to skip OP_IsNull opcodes
74258 ** when we know that a value cannot be NULL.  Hence, a false positive
74259 ** (returning TRUE when in fact the expression can never be NULL) might
74260 ** be a small performance hit but is otherwise harmless.  On the other
74261 ** hand, a false negative (returning FALSE when the result could be NULL)
74262 ** will likely result in an incorrect answer.  So when in doubt, return
74263 ** TRUE.
74264 */
74265 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
74266   u8 op;
74267   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74268   op = p->op;
74269   if( op==TK_REGISTER ) op = p->op2;
74270   switch( op ){
74271     case TK_INTEGER:
74272     case TK_STRING:
74273     case TK_FLOAT:
74274     case TK_BLOB:
74275       return 0;
74276     default:
74277       return 1;
74278   }
74279 }
74280 
74281 /*
74282 ** Generate an OP_IsNull instruction that tests register iReg and jumps
74283 ** to location iDest if the value in iReg is NULL.  The value in iReg
74284 ** was computed by pExpr.  If we can look at pExpr at compile-time and
74285 ** determine that it can never generate a NULL, then the OP_IsNull operation
74286 ** can be omitted.
74287 */
74288 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
74289   Vdbe *v,            /* The VDBE under construction */
74290   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
74291   int iReg,           /* Test the value in this register for NULL */
74292   int iDest           /* Jump here if the value is null */
74293 ){
74294   if( sqlite3ExprCanBeNull(pExpr) ){
74295     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
74296   }
74297 }
74298 
74299 /*
74300 ** Return TRUE if the given expression is a constant which would be
74301 ** unchanged by OP_Affinity with the affinity given in the second
74302 ** argument.
74303 **
74304 ** This routine is used to determine if the OP_Affinity operation
74305 ** can be omitted.  When in doubt return FALSE.  A false negative
74306 ** is harmless.  A false positive, however, can result in the wrong
74307 ** answer.
74308 */
74309 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
74310   u8 op;
74311   if( aff==SQLITE_AFF_NONE ) return 1;
74312   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
74313   op = p->op;
74314   if( op==TK_REGISTER ) op = p->op2;
74315   switch( op ){
74316     case TK_INTEGER: {
74317       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
74318     }
74319     case TK_FLOAT: {
74320       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
74321     }
74322     case TK_STRING: {
74323       return aff==SQLITE_AFF_TEXT;
74324     }
74325     case TK_BLOB: {
74326       return 1;
74327     }
74328     case TK_COLUMN: {
74329       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
74330       return p->iColumn<0
74331           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
74332     }
74333     default: {
74334       return 0;
74335     }
74336   }
74337 }
74338 
74339 /*
74340 ** Return TRUE if the given string is a row-id column name.
74341 */
74342 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
74343   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
74344   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
74345   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
74346   return 0;
74347 }
74348 
74349 /*
74350 ** Return true if we are able to the IN operator optimization on a
74351 ** query of the form
74352 **
74353 **       x IN (SELECT ...)
74354 **
74355 ** Where the SELECT... clause is as specified by the parameter to this
74356 ** routine.
74357 **
74358 ** The Select object passed in has already been preprocessed and no
74359 ** errors have been found.
74360 */
74361 #ifndef SQLITE_OMIT_SUBQUERY
74362 static int isCandidateForInOpt(Select *p){
74363   SrcList *pSrc;
74364   ExprList *pEList;
74365   Table *pTab;
74366   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
74367   if( p->pPrior ) return 0;              /* Not a compound SELECT */
74368   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
74369     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
74370     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
74371     return 0; /* No DISTINCT keyword and no aggregate functions */
74372   }
74373   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
74374   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
74375   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
74376   if( p->pWhere ) return 0;              /* Has no WHERE clause */
74377   pSrc = p->pSrc;
74378   assert( pSrc!=0 );
74379   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
74380   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
74381   pTab = pSrc->a[0].pTab;
74382   if( NEVER(pTab==0) ) return 0;
74383   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
74384   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
74385   pEList = p->pEList;
74386   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
74387   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
74388   return 1;
74389 }
74390 #endif /* SQLITE_OMIT_SUBQUERY */
74391 
74392 /*
74393 ** This function is used by the implementation of the IN (...) operator.
74394 ** It's job is to find or create a b-tree structure that may be used
74395 ** either to test for membership of the (...) set or to iterate through
74396 ** its members, skipping duplicates.
74397 **
74398 ** The index of the cursor opened on the b-tree (database table, database index
74399 ** or ephermal table) is stored in pX->iTable before this function returns.
74400 ** The returned value of this function indicates the b-tree type, as follows:
74401 **
74402 **   IN_INDEX_ROWID - The cursor was opened on a database table.
74403 **   IN_INDEX_INDEX - The cursor was opened on a database index.
74404 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
74405 **                    populated epheremal table.
74406 **
74407 ** An existing b-tree may only be used if the SELECT is of the simple
74408 ** form:
74409 **
74410 **     SELECT <column> FROM <table>
74411 **
74412 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
74413 ** through the set members, skipping any duplicates. In this case an
74414 ** epheremal table must be used unless the selected <column> is guaranteed
74415 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
74416 ** has a UNIQUE constraint or UNIQUE index.
74417 **
74418 ** If the prNotFound parameter is not 0, then the b-tree will be used
74419 ** for fast set membership tests. In this case an epheremal table must
74420 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
74421 ** be found with <column> as its left-most column.
74422 **
74423 ** When the b-tree is being used for membership tests, the calling function
74424 ** needs to know whether or not the structure contains an SQL NULL
74425 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
74426 ** If there is any chance that the (...) might contain a NULL value at
74427 ** runtime, then a register is allocated and the register number written
74428 ** to *prNotFound. If there is no chance that the (...) contains a
74429 ** NULL value, then *prNotFound is left unchanged.
74430 **
74431 ** If a register is allocated and its location stored in *prNotFound, then
74432 ** its initial value is NULL.  If the (...) does not remain constant
74433 ** for the duration of the query (i.e. the SELECT within the (...)
74434 ** is a correlated subquery) then the value of the allocated register is
74435 ** reset to NULL each time the subquery is rerun. This allows the
74436 ** caller to use vdbe code equivalent to the following:
74437 **
74438 **   if( register==NULL ){
74439 **     has_null = <test if data structure contains null>
74440 **     register = 1
74441 **   }
74442 **
74443 ** in order to avoid running the <test if data structure contains null>
74444 ** test more often than is necessary.
74445 */
74446 #ifndef SQLITE_OMIT_SUBQUERY
74447 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
74448   Select *p;                            /* SELECT to the right of IN operator */
74449   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
74450   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
74451   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
74452 
74453   assert( pX->op==TK_IN );
74454 
74455   /* Check to see if an existing table or index can be used to
74456   ** satisfy the query.  This is preferable to generating a new
74457   ** ephemeral table.
74458   */
74459   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
74460   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
74461     sqlite3 *db = pParse->db;              /* Database connection */
74462     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
74463     int iCol = pExpr->iColumn;             /* Index of column <column> */
74464     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
74465     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
74466     int iDb;                               /* Database idx for pTab */
74467 
74468     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
74469     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74470     sqlite3CodeVerifySchema(pParse, iDb);
74471     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
74472 
74473     /* This function is only called from two places. In both cases the vdbe
74474     ** has already been allocated. So assume sqlite3GetVdbe() is always
74475     ** successful here.
74476     */
74477     assert(v);
74478     if( iCol<0 ){
74479       int iMem = ++pParse->nMem;
74480       int iAddr;
74481 
74482       iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
74483 
74484       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
74485       eType = IN_INDEX_ROWID;
74486 
74487       sqlite3VdbeJumpHere(v, iAddr);
74488     }else{
74489       Index *pIdx;                         /* Iterator variable */
74490 
74491       /* The collation sequence used by the comparison. If an index is to
74492       ** be used in place of a temp-table, it must be ordered according
74493       ** to this collation sequence.  */
74494       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
74495 
74496       /* Check that the affinity that will be used to perform the
74497       ** comparison is the same as the affinity of the column. If
74498       ** it is not, it is not possible to use any index.
74499       */
74500       char aff = comparisonAffinity(pX);
74501       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
74502 
74503       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
74504         if( (pIdx->aiColumn[0]==iCol)
74505          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
74506          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
74507         ){
74508           int iMem = ++pParse->nMem;
74509           int iAddr;
74510           char *pKey;
74511 
74512           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
74513           iAddr = sqlite3VdbeAddOp1(v, OP_Once, iMem);
74514 
74515           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
74516                                pKey,P4_KEYINFO_HANDOFF);
74517           VdbeComment((v, "%s", pIdx->zName));
74518           eType = IN_INDEX_INDEX;
74519 
74520           sqlite3VdbeJumpHere(v, iAddr);
74521           if( prNotFound && !pTab->aCol[iCol].notNull ){
74522             *prNotFound = ++pParse->nMem;
74523           }
74524         }
74525       }
74526     }
74527   }
74528 
74529   if( eType==0 ){
74530     /* Could not found an existing table or index to use as the RHS b-tree.
74531     ** We will have to generate an ephemeral table to do the job.
74532     */
74533     double savedNQueryLoop = pParse->nQueryLoop;
74534     int rMayHaveNull = 0;
74535     eType = IN_INDEX_EPH;
74536     if( prNotFound ){
74537       *prNotFound = rMayHaveNull = ++pParse->nMem;
74538     }else{
74539       testcase( pParse->nQueryLoop>(double)1 );
74540       pParse->nQueryLoop = (double)1;
74541       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
74542         eType = IN_INDEX_ROWID;
74543       }
74544     }
74545     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
74546     pParse->nQueryLoop = savedNQueryLoop;
74547   }else{
74548     pX->iTable = iTab;
74549   }
74550   return eType;
74551 }
74552 #endif
74553 
74554 /*
74555 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
74556 ** or IN operators.  Examples:
74557 **
74558 **     (SELECT a FROM b)          -- subquery
74559 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
74560 **     x IN (4,5,11)              -- IN operator with list on right-hand side
74561 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
74562 **
74563 ** The pExpr parameter describes the expression that contains the IN
74564 ** operator or subquery.
74565 **
74566 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
74567 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
74568 ** to some integer key column of a table B-Tree. In this case, use an
74569 ** intkey B-Tree to store the set of IN(...) values instead of the usual
74570 ** (slower) variable length keys B-Tree.
74571 **
74572 ** If rMayHaveNull is non-zero, that means that the operation is an IN
74573 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
74574 ** Furthermore, the IN is in a WHERE clause and that we really want
74575 ** to iterate over the RHS of the IN operator in order to quickly locate
74576 ** all corresponding LHS elements.  All this routine does is initialize
74577 ** the register given by rMayHaveNull to NULL.  Calling routines will take
74578 ** care of changing this register value to non-NULL if the RHS is NULL-free.
74579 **
74580 ** If rMayHaveNull is zero, that means that the subquery is being used
74581 ** for membership testing only.  There is no need to initialize any
74582 ** registers to indicate the presense or absence of NULLs on the RHS.
74583 **
74584 ** For a SELECT or EXISTS operator, return the register that holds the
74585 ** result.  For IN operators or if an error occurs, the return value is 0.
74586 */
74587 #ifndef SQLITE_OMIT_SUBQUERY
74588 SQLITE_PRIVATE int sqlite3CodeSubselect(
74589   Parse *pParse,          /* Parsing context */
74590   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
74591   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
74592   int isRowid             /* If true, LHS of IN operator is a rowid */
74593 ){
74594   int testAddr = -1;                      /* One-time test address */
74595   int rReg = 0;                           /* Register storing resulting */
74596   Vdbe *v = sqlite3GetVdbe(pParse);
74597   if( NEVER(v==0) ) return 0;
74598   sqlite3ExprCachePush(pParse);
74599 
74600   /* This code must be run in its entirety every time it is encountered
74601   ** if any of the following is true:
74602   **
74603   **    *  The right-hand side is a correlated subquery
74604   **    *  The right-hand side is an expression list containing variables
74605   **    *  We are inside a trigger
74606   **
74607   ** If all of the above are false, then we can run this code just once
74608   ** save the results, and reuse the same result on subsequent invocations.
74609   */
74610   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
74611     int mem = ++pParse->nMem;
74612     testAddr = sqlite3VdbeAddOp1(v, OP_Once, mem);
74613   }
74614 
74615 #ifndef SQLITE_OMIT_EXPLAIN
74616   if( pParse->explain==2 ){
74617     char *zMsg = sqlite3MPrintf(
74618         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
74619         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
74620     );
74621     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
74622   }
74623 #endif
74624 
74625   switch( pExpr->op ){
74626     case TK_IN: {
74627       char affinity;              /* Affinity of the LHS of the IN */
74628       KeyInfo keyInfo;            /* Keyinfo for the generated table */
74629       int addr;                   /* Address of OP_OpenEphemeral instruction */
74630       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
74631 
74632       if( rMayHaveNull ){
74633         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
74634       }
74635 
74636       affinity = sqlite3ExprAffinity(pLeft);
74637 
74638       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
74639       ** expression it is handled the same way.  An ephemeral table is
74640       ** filled with single-field index keys representing the results
74641       ** from the SELECT or the <exprlist>.
74642       **
74643       ** If the 'x' expression is a column value, or the SELECT...
74644       ** statement returns a column value, then the affinity of that
74645       ** column is used to build the index keys. If both 'x' and the
74646       ** SELECT... statement are columns, then numeric affinity is used
74647       ** if either column has NUMERIC or INTEGER affinity. If neither
74648       ** 'x' nor the SELECT... statement are columns, then numeric affinity
74649       ** is used.
74650       */
74651       pExpr->iTable = pParse->nTab++;
74652       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
74653       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
74654       memset(&keyInfo, 0, sizeof(keyInfo));
74655       keyInfo.nField = 1;
74656 
74657       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74658         /* Case 1:     expr IN (SELECT ...)
74659         **
74660         ** Generate code to write the results of the select into the temporary
74661         ** table allocated and opened above.
74662         */
74663         SelectDest dest;
74664         ExprList *pEList;
74665 
74666         assert( !isRowid );
74667         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
74668         dest.affinity = (u8)affinity;
74669         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
74670         pExpr->x.pSelect->iLimit = 0;
74671         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
74672           return 0;
74673         }
74674         pEList = pExpr->x.pSelect->pEList;
74675         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
74676           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
74677               pEList->a[0].pExpr);
74678         }
74679       }else if( ALWAYS(pExpr->x.pList!=0) ){
74680         /* Case 2:     expr IN (exprlist)
74681         **
74682         ** For each expression, build an index key from the evaluation and
74683         ** store it in the temporary table. If <expr> is a column, then use
74684         ** that columns affinity when building index keys. If <expr> is not
74685         ** a column, use numeric affinity.
74686         */
74687         int i;
74688         ExprList *pList = pExpr->x.pList;
74689         struct ExprList_item *pItem;
74690         int r1, r2, r3;
74691 
74692         if( !affinity ){
74693           affinity = SQLITE_AFF_NONE;
74694         }
74695         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
74696 
74697         /* Loop through each expression in <exprlist>. */
74698         r1 = sqlite3GetTempReg(pParse);
74699         r2 = sqlite3GetTempReg(pParse);
74700         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
74701         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
74702           Expr *pE2 = pItem->pExpr;
74703           int iValToIns;
74704 
74705           /* If the expression is not constant then we will need to
74706           ** disable the test that was generated above that makes sure
74707           ** this code only executes once.  Because for a non-constant
74708           ** expression we need to rerun this code each time.
74709           */
74710           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
74711             sqlite3VdbeChangeToNoop(v, testAddr);
74712             testAddr = -1;
74713           }
74714 
74715           /* Evaluate the expression and insert it into the temp table */
74716           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
74717             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
74718           }else{
74719             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
74720             if( isRowid ){
74721               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
74722                                 sqlite3VdbeCurrentAddr(v)+2);
74723               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
74724             }else{
74725               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
74726               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
74727               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
74728             }
74729           }
74730         }
74731         sqlite3ReleaseTempReg(pParse, r1);
74732         sqlite3ReleaseTempReg(pParse, r2);
74733       }
74734       if( !isRowid ){
74735         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
74736       }
74737       break;
74738     }
74739 
74740     case TK_EXISTS:
74741     case TK_SELECT:
74742     default: {
74743       /* If this has to be a scalar SELECT.  Generate code to put the
74744       ** value of this select in a memory cell and record the number
74745       ** of the memory cell in iColumn.  If this is an EXISTS, write
74746       ** an integer 0 (not exists) or 1 (exists) into a memory cell
74747       ** and record that memory cell in iColumn.
74748       */
74749       Select *pSel;                         /* SELECT statement to encode */
74750       SelectDest dest;                      /* How to deal with SELECt result */
74751 
74752       testcase( pExpr->op==TK_EXISTS );
74753       testcase( pExpr->op==TK_SELECT );
74754       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
74755 
74756       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
74757       pSel = pExpr->x.pSelect;
74758       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
74759       if( pExpr->op==TK_SELECT ){
74760         dest.eDest = SRT_Mem;
74761         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
74762         VdbeComment((v, "Init subquery result"));
74763       }else{
74764         dest.eDest = SRT_Exists;
74765         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
74766         VdbeComment((v, "Init EXISTS result"));
74767       }
74768       sqlite3ExprDelete(pParse->db, pSel->pLimit);
74769       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
74770                                   &sqlite3IntTokens[1]);
74771       pSel->iLimit = 0;
74772       if( sqlite3Select(pParse, pSel, &dest) ){
74773         return 0;
74774       }
74775       rReg = dest.iParm;
74776       ExprSetIrreducible(pExpr);
74777       break;
74778     }
74779   }
74780 
74781   if( testAddr>=0 ){
74782     sqlite3VdbeJumpHere(v, testAddr);
74783   }
74784   sqlite3ExprCachePop(pParse, 1);
74785 
74786   return rReg;
74787 }
74788 #endif /* SQLITE_OMIT_SUBQUERY */
74789 
74790 #ifndef SQLITE_OMIT_SUBQUERY
74791 /*
74792 ** Generate code for an IN expression.
74793 **
74794 **      x IN (SELECT ...)
74795 **      x IN (value, value, ...)
74796 **
74797 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
74798 ** is an array of zero or more values.  The expression is true if the LHS is
74799 ** contained within the RHS.  The value of the expression is unknown (NULL)
74800 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
74801 ** RHS contains one or more NULL values.
74802 **
74803 ** This routine generates code will jump to destIfFalse if the LHS is not
74804 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
74805 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
74806 ** within the RHS then fall through.
74807 */
74808 static void sqlite3ExprCodeIN(
74809   Parse *pParse,        /* Parsing and code generating context */
74810   Expr *pExpr,          /* The IN expression */
74811   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
74812   int destIfNull        /* Jump here if the results are unknown due to NULLs */
74813 ){
74814   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
74815   char affinity;        /* Comparison affinity to use */
74816   int eType;            /* Type of the RHS */
74817   int r1;               /* Temporary use register */
74818   Vdbe *v;              /* Statement under construction */
74819 
74820   /* Compute the RHS.   After this step, the table with cursor
74821   ** pExpr->iTable will contains the values that make up the RHS.
74822   */
74823   v = pParse->pVdbe;
74824   assert( v!=0 );       /* OOM detected prior to this routine */
74825   VdbeNoopComment((v, "begin IN expr"));
74826   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
74827 
74828   /* Figure out the affinity to use to create a key from the results
74829   ** of the expression. affinityStr stores a static string suitable for
74830   ** P4 of OP_MakeRecord.
74831   */
74832   affinity = comparisonAffinity(pExpr);
74833 
74834   /* Code the LHS, the <expr> from "<expr> IN (...)".
74835   */
74836   sqlite3ExprCachePush(pParse);
74837   r1 = sqlite3GetTempReg(pParse);
74838   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
74839 
74840   /* If the LHS is NULL, then the result is either false or NULL depending
74841   ** on whether the RHS is empty or not, respectively.
74842   */
74843   if( destIfNull==destIfFalse ){
74844     /* Shortcut for the common case where the false and NULL outcomes are
74845     ** the same. */
74846     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
74847   }else{
74848     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
74849     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
74850     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
74851     sqlite3VdbeJumpHere(v, addr1);
74852   }
74853 
74854   if( eType==IN_INDEX_ROWID ){
74855     /* In this case, the RHS is the ROWID of table b-tree
74856     */
74857     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
74858     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
74859   }else{
74860     /* In this case, the RHS is an index b-tree.
74861     */
74862     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
74863 
74864     /* If the set membership test fails, then the result of the
74865     ** "x IN (...)" expression must be either 0 or NULL. If the set
74866     ** contains no NULL values, then the result is 0. If the set
74867     ** contains one or more NULL values, then the result of the
74868     ** expression is also NULL.
74869     */
74870     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
74871       /* This branch runs if it is known at compile time that the RHS
74872       ** cannot contain NULL values. This happens as the result
74873       ** of a "NOT NULL" constraint in the database schema.
74874       **
74875       ** Also run this branch if NULL is equivalent to FALSE
74876       ** for this particular IN operator.
74877       */
74878       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
74879 
74880     }else{
74881       /* In this branch, the RHS of the IN might contain a NULL and
74882       ** the presence of a NULL on the RHS makes a difference in the
74883       ** outcome.
74884       */
74885       int j1, j2, j3;
74886 
74887       /* First check to see if the LHS is contained in the RHS.  If so,
74888       ** then the presence of NULLs in the RHS does not matter, so jump
74889       ** over all of the code that follows.
74890       */
74891       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
74892 
74893       /* Here we begin generating code that runs if the LHS is not
74894       ** contained within the RHS.  Generate additional code that
74895       ** tests the RHS for NULLs.  If the RHS contains a NULL then
74896       ** jump to destIfNull.  If there are no NULLs in the RHS then
74897       ** jump to destIfFalse.
74898       */
74899       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
74900       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
74901       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
74902       sqlite3VdbeJumpHere(v, j3);
74903       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
74904       sqlite3VdbeJumpHere(v, j2);
74905 
74906       /* Jump to the appropriate target depending on whether or not
74907       ** the RHS contains a NULL
74908       */
74909       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
74910       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
74911 
74912       /* The OP_Found at the top of this branch jumps here when true,
74913       ** causing the overall IN expression evaluation to fall through.
74914       */
74915       sqlite3VdbeJumpHere(v, j1);
74916     }
74917   }
74918   sqlite3ReleaseTempReg(pParse, r1);
74919   sqlite3ExprCachePop(pParse, 1);
74920   VdbeComment((v, "end IN expr"));
74921 }
74922 #endif /* SQLITE_OMIT_SUBQUERY */
74923 
74924 /*
74925 ** Duplicate an 8-byte value
74926 */
74927 static char *dup8bytes(Vdbe *v, const char *in){
74928   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
74929   if( out ){
74930     memcpy(out, in, 8);
74931   }
74932   return out;
74933 }
74934 
74935 #ifndef SQLITE_OMIT_FLOATING_POINT
74936 /*
74937 ** Generate an instruction that will put the floating point
74938 ** value described by z[0..n-1] into register iMem.
74939 **
74940 ** The z[] string will probably not be zero-terminated.  But the
74941 ** z[n] character is guaranteed to be something that does not look
74942 ** like the continuation of the number.
74943 */
74944 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
74945   if( ALWAYS(z!=0) ){
74946     double value;
74947     char *zV;
74948     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
74949     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
74950     if( negateFlag ) value = -value;
74951     zV = dup8bytes(v, (char*)&value);
74952     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
74953   }
74954 }
74955 #endif
74956 
74957 
74958 /*
74959 ** Generate an instruction that will put the integer describe by
74960 ** text z[0..n-1] into register iMem.
74961 **
74962 ** Expr.u.zToken is always UTF8 and zero-terminated.
74963 */
74964 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
74965   Vdbe *v = pParse->pVdbe;
74966   if( pExpr->flags & EP_IntValue ){
74967     int i = pExpr->u.iValue;
74968     assert( i>=0 );
74969     if( negFlag ) i = -i;
74970     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
74971   }else{
74972     int c;
74973     i64 value;
74974     const char *z = pExpr->u.zToken;
74975     assert( z!=0 );
74976     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
74977     if( c==0 || (c==2 && negFlag) ){
74978       char *zV;
74979       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
74980       zV = dup8bytes(v, (char*)&value);
74981       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
74982     }else{
74983 #ifdef SQLITE_OMIT_FLOATING_POINT
74984       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
74985 #else
74986       codeReal(v, z, negFlag, iMem);
74987 #endif
74988     }
74989   }
74990 }
74991 
74992 /*
74993 ** Clear a cache entry.
74994 */
74995 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
74996   if( p->tempReg ){
74997     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
74998       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
74999     }
75000     p->tempReg = 0;
75001   }
75002 }
75003 
75004 
75005 /*
75006 ** Record in the column cache that a particular column from a
75007 ** particular table is stored in a particular register.
75008 */
75009 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
75010   int i;
75011   int minLru;
75012   int idxLru;
75013   struct yColCache *p;
75014 
75015   assert( iReg>0 );  /* Register numbers are always positive */
75016   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
75017 
75018   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
75019   ** for testing only - to verify that SQLite always gets the same answer
75020   ** with and without the column cache.
75021   */
75022   if( pParse->db->flags & SQLITE_ColumnCache ) return;
75023 
75024   /* First replace any existing entry.
75025   **
75026   ** Actually, the way the column cache is currently used, we are guaranteed
75027   ** that the object will never already be in cache.  Verify this guarantee.
75028   */
75029 #ifndef NDEBUG
75030   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75031 #if 0 /* This code wold remove the entry from the cache if it existed */
75032     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
75033       cacheEntryClear(pParse, p);
75034       p->iLevel = pParse->iCacheLevel;
75035       p->iReg = iReg;
75036       p->lru = pParse->iCacheCnt++;
75037       return;
75038     }
75039 #endif
75040     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
75041   }
75042 #endif
75043 
75044   /* Find an empty slot and replace it */
75045   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75046     if( p->iReg==0 ){
75047       p->iLevel = pParse->iCacheLevel;
75048       p->iTable = iTab;
75049       p->iColumn = iCol;
75050       p->iReg = iReg;
75051       p->tempReg = 0;
75052       p->lru = pParse->iCacheCnt++;
75053       return;
75054     }
75055   }
75056 
75057   /* Replace the last recently used */
75058   minLru = 0x7fffffff;
75059   idxLru = -1;
75060   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75061     if( p->lru<minLru ){
75062       idxLru = i;
75063       minLru = p->lru;
75064     }
75065   }
75066   if( ALWAYS(idxLru>=0) ){
75067     p = &pParse->aColCache[idxLru];
75068     p->iLevel = pParse->iCacheLevel;
75069     p->iTable = iTab;
75070     p->iColumn = iCol;
75071     p->iReg = iReg;
75072     p->tempReg = 0;
75073     p->lru = pParse->iCacheCnt++;
75074     return;
75075   }
75076 }
75077 
75078 /*
75079 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
75080 ** Purge the range of registers from the column cache.
75081 */
75082 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
75083   int i;
75084   int iLast = iReg + nReg - 1;
75085   struct yColCache *p;
75086   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75087     int r = p->iReg;
75088     if( r>=iReg && r<=iLast ){
75089       cacheEntryClear(pParse, p);
75090       p->iReg = 0;
75091     }
75092   }
75093 }
75094 
75095 /*
75096 ** Remember the current column cache context.  Any new entries added
75097 ** added to the column cache after this call are removed when the
75098 ** corresponding pop occurs.
75099 */
75100 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
75101   pParse->iCacheLevel++;
75102 }
75103 
75104 /*
75105 ** Remove from the column cache any entries that were added since the
75106 ** the previous N Push operations.  In other words, restore the cache
75107 ** to the state it was in N Pushes ago.
75108 */
75109 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
75110   int i;
75111   struct yColCache *p;
75112   assert( N>0 );
75113   assert( pParse->iCacheLevel>=N );
75114   pParse->iCacheLevel -= N;
75115   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75116     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
75117       cacheEntryClear(pParse, p);
75118       p->iReg = 0;
75119     }
75120   }
75121 }
75122 
75123 /*
75124 ** When a cached column is reused, make sure that its register is
75125 ** no longer available as a temp register.  ticket #3879:  that same
75126 ** register might be in the cache in multiple places, so be sure to
75127 ** get them all.
75128 */
75129 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
75130   int i;
75131   struct yColCache *p;
75132   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75133     if( p->iReg==iReg ){
75134       p->tempReg = 0;
75135     }
75136   }
75137 }
75138 
75139 /*
75140 ** Generate code to extract the value of the iCol-th column of a table.
75141 */
75142 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
75143   Vdbe *v,        /* The VDBE under construction */
75144   Table *pTab,    /* The table containing the value */
75145   int iTabCur,    /* The cursor for this table */
75146   int iCol,       /* Index of the column to extract */
75147   int regOut      /* Extract the valud into this register */
75148 ){
75149   if( iCol<0 || iCol==pTab->iPKey ){
75150     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
75151   }else{
75152     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
75153     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
75154   }
75155   if( iCol>=0 ){
75156     sqlite3ColumnDefault(v, pTab, iCol, regOut);
75157   }
75158 }
75159 
75160 /*
75161 ** Generate code that will extract the iColumn-th column from
75162 ** table pTab and store the column value in a register.  An effort
75163 ** is made to store the column value in register iReg, but this is
75164 ** not guaranteed.  The location of the column value is returned.
75165 **
75166 ** There must be an open cursor to pTab in iTable when this routine
75167 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
75168 */
75169 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
75170   Parse *pParse,   /* Parsing and code generating context */
75171   Table *pTab,     /* Description of the table we are reading from */
75172   int iColumn,     /* Index of the table column */
75173   int iTable,      /* The cursor pointing to the table */
75174   int iReg         /* Store results here */
75175 ){
75176   Vdbe *v = pParse->pVdbe;
75177   int i;
75178   struct yColCache *p;
75179 
75180   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75181     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
75182       p->lru = pParse->iCacheCnt++;
75183       sqlite3ExprCachePinRegister(pParse, p->iReg);
75184       return p->iReg;
75185     }
75186   }
75187   assert( v!=0 );
75188   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
75189   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
75190   return iReg;
75191 }
75192 
75193 /*
75194 ** Clear all column cache entries.
75195 */
75196 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
75197   int i;
75198   struct yColCache *p;
75199 
75200   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75201     if( p->iReg ){
75202       cacheEntryClear(pParse, p);
75203       p->iReg = 0;
75204     }
75205   }
75206 }
75207 
75208 /*
75209 ** Record the fact that an affinity change has occurred on iCount
75210 ** registers starting with iStart.
75211 */
75212 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
75213   sqlite3ExprCacheRemove(pParse, iStart, iCount);
75214 }
75215 
75216 /*
75217 ** Generate code to move content from registers iFrom...iFrom+nReg-1
75218 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
75219 */
75220 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
75221   int i;
75222   struct yColCache *p;
75223   if( NEVER(iFrom==iTo) ) return;
75224   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
75225   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75226     int x = p->iReg;
75227     if( x>=iFrom && x<iFrom+nReg ){
75228       p->iReg += iTo-iFrom;
75229     }
75230   }
75231 }
75232 
75233 /*
75234 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
75235 ** over to iTo..iTo+nReg-1.
75236 */
75237 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
75238   int i;
75239   if( NEVER(iFrom==iTo) ) return;
75240   for(i=0; i<nReg; i++){
75241     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
75242   }
75243 }
75244 
75245 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
75246 /*
75247 ** Return true if any register in the range iFrom..iTo (inclusive)
75248 ** is used as part of the column cache.
75249 **
75250 ** This routine is used within assert() and testcase() macros only
75251 ** and does not appear in a normal build.
75252 */
75253 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
75254   int i;
75255   struct yColCache *p;
75256   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
75257     int r = p->iReg;
75258     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
75259   }
75260   return 0;
75261 }
75262 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
75263 
75264 /*
75265 ** Generate code into the current Vdbe to evaluate the given
75266 ** expression.  Attempt to store the results in register "target".
75267 ** Return the register where results are stored.
75268 **
75269 ** With this routine, there is no guarantee that results will
75270 ** be stored in target.  The result might be stored in some other
75271 ** register if it is convenient to do so.  The calling function
75272 ** must check the return code and move the results to the desired
75273 ** register.
75274 */
75275 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
75276   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
75277   int op;                   /* The opcode being coded */
75278   int inReg = target;       /* Results stored in register inReg */
75279   int regFree1 = 0;         /* If non-zero free this temporary register */
75280   int regFree2 = 0;         /* If non-zero free this temporary register */
75281   int r1, r2, r3, r4;       /* Various register numbers */
75282   sqlite3 *db = pParse->db; /* The database connection */
75283 
75284   assert( target>0 && target<=pParse->nMem );
75285   if( v==0 ){
75286     assert( pParse->db->mallocFailed );
75287     return 0;
75288   }
75289 
75290   if( pExpr==0 ){
75291     op = TK_NULL;
75292   }else{
75293     op = pExpr->op;
75294   }
75295   switch( op ){
75296     case TK_AGG_COLUMN: {
75297       AggInfo *pAggInfo = pExpr->pAggInfo;
75298       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
75299       if( !pAggInfo->directMode ){
75300         assert( pCol->iMem>0 );
75301         inReg = pCol->iMem;
75302         break;
75303       }else if( pAggInfo->useSortingIdx ){
75304         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
75305                               pCol->iSorterColumn, target);
75306         break;
75307       }
75308       /* Otherwise, fall thru into the TK_COLUMN case */
75309     }
75310     case TK_COLUMN: {
75311       if( pExpr->iTable<0 ){
75312         /* This only happens when coding check constraints */
75313         assert( pParse->ckBase>0 );
75314         inReg = pExpr->iColumn + pParse->ckBase;
75315       }else{
75316         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
75317                                  pExpr->iColumn, pExpr->iTable, target);
75318       }
75319       break;
75320     }
75321     case TK_INTEGER: {
75322       codeInteger(pParse, pExpr, 0, target);
75323       break;
75324     }
75325 #ifndef SQLITE_OMIT_FLOATING_POINT
75326     case TK_FLOAT: {
75327       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75328       codeReal(v, pExpr->u.zToken, 0, target);
75329       break;
75330     }
75331 #endif
75332     case TK_STRING: {
75333       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75334       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
75335       break;
75336     }
75337     case TK_NULL: {
75338       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75339       break;
75340     }
75341 #ifndef SQLITE_OMIT_BLOB_LITERAL
75342     case TK_BLOB: {
75343       int n;
75344       const char *z;
75345       char *zBlob;
75346       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75347       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
75348       assert( pExpr->u.zToken[1]=='\'' );
75349       z = &pExpr->u.zToken[2];
75350       n = sqlite3Strlen30(z) - 1;
75351       assert( z[n]=='\'' );
75352       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
75353       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
75354       break;
75355     }
75356 #endif
75357     case TK_VARIABLE: {
75358       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75359       assert( pExpr->u.zToken!=0 );
75360       assert( pExpr->u.zToken[0]!=0 );
75361       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
75362       if( pExpr->u.zToken[1]!=0 ){
75363         assert( pExpr->u.zToken[0]=='?'
75364              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
75365         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
75366       }
75367       break;
75368     }
75369     case TK_REGISTER: {
75370       inReg = pExpr->iTable;
75371       break;
75372     }
75373     case TK_AS: {
75374       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75375       break;
75376     }
75377 #ifndef SQLITE_OMIT_CAST
75378     case TK_CAST: {
75379       /* Expressions of the form:   CAST(pLeft AS token) */
75380       int aff, to_op;
75381       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75382       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75383       aff = sqlite3AffinityType(pExpr->u.zToken);
75384       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
75385       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
75386       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
75387       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
75388       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
75389       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
75390       testcase( to_op==OP_ToText );
75391       testcase( to_op==OP_ToBlob );
75392       testcase( to_op==OP_ToNumeric );
75393       testcase( to_op==OP_ToInt );
75394       testcase( to_op==OP_ToReal );
75395       if( inReg!=target ){
75396         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
75397         inReg = target;
75398       }
75399       sqlite3VdbeAddOp1(v, to_op, inReg);
75400       testcase( usedAsColumnCache(pParse, inReg, inReg) );
75401       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
75402       break;
75403     }
75404 #endif /* SQLITE_OMIT_CAST */
75405     case TK_LT:
75406     case TK_LE:
75407     case TK_GT:
75408     case TK_GE:
75409     case TK_NE:
75410     case TK_EQ: {
75411       assert( TK_LT==OP_Lt );
75412       assert( TK_LE==OP_Le );
75413       assert( TK_GT==OP_Gt );
75414       assert( TK_GE==OP_Ge );
75415       assert( TK_EQ==OP_Eq );
75416       assert( TK_NE==OP_Ne );
75417       testcase( op==TK_LT );
75418       testcase( op==TK_LE );
75419       testcase( op==TK_GT );
75420       testcase( op==TK_GE );
75421       testcase( op==TK_EQ );
75422       testcase( op==TK_NE );
75423       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75424       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75425       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75426                   r1, r2, inReg, SQLITE_STOREP2);
75427       testcase( regFree1==0 );
75428       testcase( regFree2==0 );
75429       break;
75430     }
75431     case TK_IS:
75432     case TK_ISNOT: {
75433       testcase( op==TK_IS );
75434       testcase( op==TK_ISNOT );
75435       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75436       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75437       op = (op==TK_IS) ? TK_EQ : TK_NE;
75438       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
75439                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
75440       testcase( regFree1==0 );
75441       testcase( regFree2==0 );
75442       break;
75443     }
75444     case TK_AND:
75445     case TK_OR:
75446     case TK_PLUS:
75447     case TK_STAR:
75448     case TK_MINUS:
75449     case TK_REM:
75450     case TK_BITAND:
75451     case TK_BITOR:
75452     case TK_SLASH:
75453     case TK_LSHIFT:
75454     case TK_RSHIFT:
75455     case TK_CONCAT: {
75456       assert( TK_AND==OP_And );
75457       assert( TK_OR==OP_Or );
75458       assert( TK_PLUS==OP_Add );
75459       assert( TK_MINUS==OP_Subtract );
75460       assert( TK_REM==OP_Remainder );
75461       assert( TK_BITAND==OP_BitAnd );
75462       assert( TK_BITOR==OP_BitOr );
75463       assert( TK_SLASH==OP_Divide );
75464       assert( TK_LSHIFT==OP_ShiftLeft );
75465       assert( TK_RSHIFT==OP_ShiftRight );
75466       assert( TK_CONCAT==OP_Concat );
75467       testcase( op==TK_AND );
75468       testcase( op==TK_OR );
75469       testcase( op==TK_PLUS );
75470       testcase( op==TK_MINUS );
75471       testcase( op==TK_REM );
75472       testcase( op==TK_BITAND );
75473       testcase( op==TK_BITOR );
75474       testcase( op==TK_SLASH );
75475       testcase( op==TK_LSHIFT );
75476       testcase( op==TK_RSHIFT );
75477       testcase( op==TK_CONCAT );
75478       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75479       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
75480       sqlite3VdbeAddOp3(v, op, r2, r1, target);
75481       testcase( regFree1==0 );
75482       testcase( regFree2==0 );
75483       break;
75484     }
75485     case TK_UMINUS: {
75486       Expr *pLeft = pExpr->pLeft;
75487       assert( pLeft );
75488       if( pLeft->op==TK_INTEGER ){
75489         codeInteger(pParse, pLeft, 1, target);
75490 #ifndef SQLITE_OMIT_FLOATING_POINT
75491       }else if( pLeft->op==TK_FLOAT ){
75492         assert( !ExprHasProperty(pExpr, EP_IntValue) );
75493         codeReal(v, pLeft->u.zToken, 1, target);
75494 #endif
75495       }else{
75496         regFree1 = r1 = sqlite3GetTempReg(pParse);
75497         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
75498         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
75499         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
75500         testcase( regFree2==0 );
75501       }
75502       inReg = target;
75503       break;
75504     }
75505     case TK_BITNOT:
75506     case TK_NOT: {
75507       assert( TK_BITNOT==OP_BitNot );
75508       assert( TK_NOT==OP_Not );
75509       testcase( op==TK_BITNOT );
75510       testcase( op==TK_NOT );
75511       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75512       testcase( regFree1==0 );
75513       inReg = target;
75514       sqlite3VdbeAddOp2(v, op, r1, inReg);
75515       break;
75516     }
75517     case TK_ISNULL:
75518     case TK_NOTNULL: {
75519       int addr;
75520       assert( TK_ISNULL==OP_IsNull );
75521       assert( TK_NOTNULL==OP_NotNull );
75522       testcase( op==TK_ISNULL );
75523       testcase( op==TK_NOTNULL );
75524       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75525       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
75526       testcase( regFree1==0 );
75527       addr = sqlite3VdbeAddOp1(v, op, r1);
75528       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
75529       sqlite3VdbeJumpHere(v, addr);
75530       break;
75531     }
75532     case TK_AGG_FUNCTION: {
75533       AggInfo *pInfo = pExpr->pAggInfo;
75534       if( pInfo==0 ){
75535         assert( !ExprHasProperty(pExpr, EP_IntValue) );
75536         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
75537       }else{
75538         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
75539       }
75540       break;
75541     }
75542     case TK_CONST_FUNC:
75543     case TK_FUNCTION: {
75544       ExprList *pFarg;       /* List of function arguments */
75545       int nFarg;             /* Number of function arguments */
75546       FuncDef *pDef;         /* The function definition object */
75547       int nId;               /* Length of the function name in bytes */
75548       const char *zId;       /* The function name */
75549       int constMask = 0;     /* Mask of function arguments that are constant */
75550       int i;                 /* Loop counter */
75551       u8 enc = ENC(db);      /* The text encoding used by this database */
75552       CollSeq *pColl = 0;    /* A collating sequence */
75553 
75554       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
75555       testcase( op==TK_CONST_FUNC );
75556       testcase( op==TK_FUNCTION );
75557       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
75558         pFarg = 0;
75559       }else{
75560         pFarg = pExpr->x.pList;
75561       }
75562       nFarg = pFarg ? pFarg->nExpr : 0;
75563       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75564       zId = pExpr->u.zToken;
75565       nId = sqlite3Strlen30(zId);
75566       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
75567       if( pDef==0 ){
75568         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
75569         break;
75570       }
75571 
75572       /* Attempt a direct implementation of the built-in COALESCE() and
75573       ** IFNULL() functions.  This avoids unnecessary evalation of
75574       ** arguments past the first non-NULL argument.
75575       */
75576       if( pDef->flags & SQLITE_FUNC_COALESCE ){
75577         int endCoalesce = sqlite3VdbeMakeLabel(v);
75578         assert( nFarg>=2 );
75579         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
75580         for(i=1; i<nFarg; i++){
75581           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
75582           sqlite3ExprCacheRemove(pParse, target, 1);
75583           sqlite3ExprCachePush(pParse);
75584           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
75585           sqlite3ExprCachePop(pParse, 1);
75586         }
75587         sqlite3VdbeResolveLabel(v, endCoalesce);
75588         break;
75589       }
75590 
75591 
75592       if( pFarg ){
75593         r1 = sqlite3GetTempRange(pParse, nFarg);
75594         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
75595         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
75596         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
75597       }else{
75598         r1 = 0;
75599       }
75600 #ifndef SQLITE_OMIT_VIRTUALTABLE
75601       /* Possibly overload the function if the first argument is
75602       ** a virtual table column.
75603       **
75604       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
75605       ** second argument, not the first, as the argument to test to
75606       ** see if it is a column in a virtual table.  This is done because
75607       ** the left operand of infix functions (the operand we want to
75608       ** control overloading) ends up as the second argument to the
75609       ** function.  The expression "A glob B" is equivalent to
75610       ** "glob(B,A).  We want to use the A in "A glob B" to test
75611       ** for function overloading.  But we use the B term in "glob(B,A)".
75612       */
75613       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
75614         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
75615       }else if( nFarg>0 ){
75616         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
75617       }
75618 #endif
75619       for(i=0; i<nFarg; i++){
75620         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
75621           constMask |= (1<<i);
75622         }
75623         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
75624           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
75625         }
75626       }
75627       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
75628         if( !pColl ) pColl = db->pDfltColl;
75629         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
75630       }
75631       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
75632                         (char*)pDef, P4_FUNCDEF);
75633       sqlite3VdbeChangeP5(v, (u8)nFarg);
75634       if( nFarg ){
75635         sqlite3ReleaseTempRange(pParse, r1, nFarg);
75636       }
75637       break;
75638     }
75639 #ifndef SQLITE_OMIT_SUBQUERY
75640     case TK_EXISTS:
75641     case TK_SELECT: {
75642       testcase( op==TK_EXISTS );
75643       testcase( op==TK_SELECT );
75644       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
75645       break;
75646     }
75647     case TK_IN: {
75648       int destIfFalse = sqlite3VdbeMakeLabel(v);
75649       int destIfNull = sqlite3VdbeMakeLabel(v);
75650       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75651       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
75652       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
75653       sqlite3VdbeResolveLabel(v, destIfFalse);
75654       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
75655       sqlite3VdbeResolveLabel(v, destIfNull);
75656       break;
75657     }
75658 #endif /* SQLITE_OMIT_SUBQUERY */
75659 
75660 
75661     /*
75662     **    x BETWEEN y AND z
75663     **
75664     ** This is equivalent to
75665     **
75666     **    x>=y AND x<=z
75667     **
75668     ** X is stored in pExpr->pLeft.
75669     ** Y is stored in pExpr->pList->a[0].pExpr.
75670     ** Z is stored in pExpr->pList->a[1].pExpr.
75671     */
75672     case TK_BETWEEN: {
75673       Expr *pLeft = pExpr->pLeft;
75674       struct ExprList_item *pLItem = pExpr->x.pList->a;
75675       Expr *pRight = pLItem->pExpr;
75676 
75677       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
75678       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75679       testcase( regFree1==0 );
75680       testcase( regFree2==0 );
75681       r3 = sqlite3GetTempReg(pParse);
75682       r4 = sqlite3GetTempReg(pParse);
75683       codeCompare(pParse, pLeft, pRight, OP_Ge,
75684                   r1, r2, r3, SQLITE_STOREP2);
75685       pLItem++;
75686       pRight = pLItem->pExpr;
75687       sqlite3ReleaseTempReg(pParse, regFree2);
75688       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
75689       testcase( regFree2==0 );
75690       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
75691       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
75692       sqlite3ReleaseTempReg(pParse, r3);
75693       sqlite3ReleaseTempReg(pParse, r4);
75694       break;
75695     }
75696     case TK_UPLUS: {
75697       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
75698       break;
75699     }
75700 
75701     case TK_TRIGGER: {
75702       /* If the opcode is TK_TRIGGER, then the expression is a reference
75703       ** to a column in the new.* or old.* pseudo-tables available to
75704       ** trigger programs. In this case Expr.iTable is set to 1 for the
75705       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
75706       ** is set to the column of the pseudo-table to read, or to -1 to
75707       ** read the rowid field.
75708       **
75709       ** The expression is implemented using an OP_Param opcode. The p1
75710       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
75711       ** to reference another column of the old.* pseudo-table, where
75712       ** i is the index of the column. For a new.rowid reference, p1 is
75713       ** set to (n+1), where n is the number of columns in each pseudo-table.
75714       ** For a reference to any other column in the new.* pseudo-table, p1
75715       ** is set to (n+2+i), where n and i are as defined previously. For
75716       ** example, if the table on which triggers are being fired is
75717       ** declared as:
75718       **
75719       **   CREATE TABLE t1(a, b);
75720       **
75721       ** Then p1 is interpreted as follows:
75722       **
75723       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
75724       **   p1==1   ->    old.a         p1==4   ->    new.a
75725       **   p1==2   ->    old.b         p1==5   ->    new.b
75726       */
75727       Table *pTab = pExpr->pTab;
75728       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
75729 
75730       assert( pExpr->iTable==0 || pExpr->iTable==1 );
75731       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
75732       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
75733       assert( p1>=0 && p1<(pTab->nCol*2+2) );
75734 
75735       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
75736       VdbeComment((v, "%s.%s -> $%d",
75737         (pExpr->iTable ? "new" : "old"),
75738         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
75739         target
75740       ));
75741 
75742 #ifndef SQLITE_OMIT_FLOATING_POINT
75743       /* If the column has REAL affinity, it may currently be stored as an
75744       ** integer. Use OP_RealAffinity to make sure it is really real.  */
75745       if( pExpr->iColumn>=0
75746        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
75747       ){
75748         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
75749       }
75750 #endif
75751       break;
75752     }
75753 
75754 
75755     /*
75756     ** Form A:
75757     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
75758     **
75759     ** Form B:
75760     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
75761     **
75762     ** Form A is can be transformed into the equivalent form B as follows:
75763     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
75764     **        WHEN x=eN THEN rN ELSE y END
75765     **
75766     ** X (if it exists) is in pExpr->pLeft.
75767     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
75768     ** ELSE clause and no other term matches, then the result of the
75769     ** exprssion is NULL.
75770     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
75771     **
75772     ** The result of the expression is the Ri for the first matching Ei,
75773     ** or if there is no matching Ei, the ELSE term Y, or if there is
75774     ** no ELSE term, NULL.
75775     */
75776     default: assert( op==TK_CASE ); {
75777       int endLabel;                     /* GOTO label for end of CASE stmt */
75778       int nextCase;                     /* GOTO label for next WHEN clause */
75779       int nExpr;                        /* 2x number of WHEN terms */
75780       int i;                            /* Loop counter */
75781       ExprList *pEList;                 /* List of WHEN terms */
75782       struct ExprList_item *aListelem;  /* Array of WHEN terms */
75783       Expr opCompare;                   /* The X==Ei expression */
75784       Expr cacheX;                      /* Cached expression X */
75785       Expr *pX;                         /* The X expression */
75786       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
75787       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
75788 
75789       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
75790       assert((pExpr->x.pList->nExpr % 2) == 0);
75791       assert(pExpr->x.pList->nExpr > 0);
75792       pEList = pExpr->x.pList;
75793       aListelem = pEList->a;
75794       nExpr = pEList->nExpr;
75795       endLabel = sqlite3VdbeMakeLabel(v);
75796       if( (pX = pExpr->pLeft)!=0 ){
75797         cacheX = *pX;
75798         testcase( pX->op==TK_COLUMN );
75799         testcase( pX->op==TK_REGISTER );
75800         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
75801         testcase( regFree1==0 );
75802         cacheX.op = TK_REGISTER;
75803         opCompare.op = TK_EQ;
75804         opCompare.pLeft = &cacheX;
75805         pTest = &opCompare;
75806         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
75807         ** The value in regFree1 might get SCopy-ed into the file result.
75808         ** So make sure that the regFree1 register is not reused for other
75809         ** purposes and possibly overwritten.  */
75810         regFree1 = 0;
75811       }
75812       for(i=0; i<nExpr; i=i+2){
75813         sqlite3ExprCachePush(pParse);
75814         if( pX ){
75815           assert( pTest!=0 );
75816           opCompare.pRight = aListelem[i].pExpr;
75817         }else{
75818           pTest = aListelem[i].pExpr;
75819         }
75820         nextCase = sqlite3VdbeMakeLabel(v);
75821         testcase( pTest->op==TK_COLUMN );
75822         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
75823         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
75824         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
75825         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
75826         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
75827         sqlite3ExprCachePop(pParse, 1);
75828         sqlite3VdbeResolveLabel(v, nextCase);
75829       }
75830       if( pExpr->pRight ){
75831         sqlite3ExprCachePush(pParse);
75832         sqlite3ExprCode(pParse, pExpr->pRight, target);
75833         sqlite3ExprCachePop(pParse, 1);
75834       }else{
75835         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
75836       }
75837       assert( db->mallocFailed || pParse->nErr>0
75838            || pParse->iCacheLevel==iCacheLevel );
75839       sqlite3VdbeResolveLabel(v, endLabel);
75840       break;
75841     }
75842 #ifndef SQLITE_OMIT_TRIGGER
75843     case TK_RAISE: {
75844       assert( pExpr->affinity==OE_Rollback
75845            || pExpr->affinity==OE_Abort
75846            || pExpr->affinity==OE_Fail
75847            || pExpr->affinity==OE_Ignore
75848       );
75849       if( !pParse->pTriggerTab ){
75850         sqlite3ErrorMsg(pParse,
75851                        "RAISE() may only be used within a trigger-program");
75852         return 0;
75853       }
75854       if( pExpr->affinity==OE_Abort ){
75855         sqlite3MayAbort(pParse);
75856       }
75857       assert( !ExprHasProperty(pExpr, EP_IntValue) );
75858       if( pExpr->affinity==OE_Ignore ){
75859         sqlite3VdbeAddOp4(
75860             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
75861       }else{
75862         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
75863       }
75864 
75865       break;
75866     }
75867 #endif
75868   }
75869   sqlite3ReleaseTempReg(pParse, regFree1);
75870   sqlite3ReleaseTempReg(pParse, regFree2);
75871   return inReg;
75872 }
75873 
75874 /*
75875 ** Generate code to evaluate an expression and store the results
75876 ** into a register.  Return the register number where the results
75877 ** are stored.
75878 **
75879 ** If the register is a temporary register that can be deallocated,
75880 ** then write its number into *pReg.  If the result register is not
75881 ** a temporary, then set *pReg to zero.
75882 */
75883 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
75884   int r1 = sqlite3GetTempReg(pParse);
75885   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
75886   if( r2==r1 ){
75887     *pReg = r1;
75888   }else{
75889     sqlite3ReleaseTempReg(pParse, r1);
75890     *pReg = 0;
75891   }
75892   return r2;
75893 }
75894 
75895 /*
75896 ** Generate code that will evaluate expression pExpr and store the
75897 ** results in register target.  The results are guaranteed to appear
75898 ** in register target.
75899 */
75900 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
75901   int inReg;
75902 
75903   assert( target>0 && target<=pParse->nMem );
75904   if( pExpr && pExpr->op==TK_REGISTER ){
75905     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
75906   }else{
75907     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
75908     assert( pParse->pVdbe || pParse->db->mallocFailed );
75909     if( inReg!=target && pParse->pVdbe ){
75910       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
75911     }
75912   }
75913   return target;
75914 }
75915 
75916 /*
75917 ** Generate code that evalutes the given expression and puts the result
75918 ** in register target.
75919 **
75920 ** Also make a copy of the expression results into another "cache" register
75921 ** and modify the expression so that the next time it is evaluated,
75922 ** the result is a copy of the cache register.
75923 **
75924 ** This routine is used for expressions that are used multiple
75925 ** times.  They are evaluated once and the results of the expression
75926 ** are reused.
75927 */
75928 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
75929   Vdbe *v = pParse->pVdbe;
75930   int inReg;
75931   inReg = sqlite3ExprCode(pParse, pExpr, target);
75932   assert( target>0 );
75933   /* This routine is called for terms to INSERT or UPDATE.  And the only
75934   ** other place where expressions can be converted into TK_REGISTER is
75935   ** in WHERE clause processing.  So as currently implemented, there is
75936   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
75937   ** keep the ALWAYS() in case the conditions above change with future
75938   ** modifications or enhancements. */
75939   if( ALWAYS(pExpr->op!=TK_REGISTER) ){
75940     int iMem;
75941     iMem = ++pParse->nMem;
75942     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
75943     pExpr->iTable = iMem;
75944     pExpr->op2 = pExpr->op;
75945     pExpr->op = TK_REGISTER;
75946   }
75947   return inReg;
75948 }
75949 
75950 /*
75951 ** Return TRUE if pExpr is an constant expression that is appropriate
75952 ** for factoring out of a loop.  Appropriate expressions are:
75953 **
75954 **    *  Any expression that evaluates to two or more opcodes.
75955 **
75956 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
75957 **       or OP_Variable that does not need to be placed in a
75958 **       specific register.
75959 **
75960 ** There is no point in factoring out single-instruction constant
75961 ** expressions that need to be placed in a particular register.
75962 ** We could factor them out, but then we would end up adding an
75963 ** OP_SCopy instruction to move the value into the correct register
75964 ** later.  We might as well just use the original instruction and
75965 ** avoid the OP_SCopy.
75966 */
75967 static int isAppropriateForFactoring(Expr *p){
75968   if( !sqlite3ExprIsConstantNotJoin(p) ){
75969     return 0;  /* Only constant expressions are appropriate for factoring */
75970   }
75971   if( (p->flags & EP_FixedDest)==0 ){
75972     return 1;  /* Any constant without a fixed destination is appropriate */
75973   }
75974   while( p->op==TK_UPLUS ) p = p->pLeft;
75975   switch( p->op ){
75976 #ifndef SQLITE_OMIT_BLOB_LITERAL
75977     case TK_BLOB:
75978 #endif
75979     case TK_VARIABLE:
75980     case TK_INTEGER:
75981     case TK_FLOAT:
75982     case TK_NULL:
75983     case TK_STRING: {
75984       testcase( p->op==TK_BLOB );
75985       testcase( p->op==TK_VARIABLE );
75986       testcase( p->op==TK_INTEGER );
75987       testcase( p->op==TK_FLOAT );
75988       testcase( p->op==TK_NULL );
75989       testcase( p->op==TK_STRING );
75990       /* Single-instruction constants with a fixed destination are
75991       ** better done in-line.  If we factor them, they will just end
75992       ** up generating an OP_SCopy to move the value to the destination
75993       ** register. */
75994       return 0;
75995     }
75996     case TK_UMINUS: {
75997       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
75998         return 0;
75999       }
76000       break;
76001     }
76002     default: {
76003       break;
76004     }
76005   }
76006   return 1;
76007 }
76008 
76009 /*
76010 ** If pExpr is a constant expression that is appropriate for
76011 ** factoring out of a loop, then evaluate the expression
76012 ** into a register and convert the expression into a TK_REGISTER
76013 ** expression.
76014 */
76015 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
76016   Parse *pParse = pWalker->pParse;
76017   switch( pExpr->op ){
76018     case TK_IN:
76019     case TK_REGISTER: {
76020       return WRC_Prune;
76021     }
76022     case TK_FUNCTION:
76023     case TK_AGG_FUNCTION:
76024     case TK_CONST_FUNC: {
76025       /* The arguments to a function have a fixed destination.
76026       ** Mark them this way to avoid generated unneeded OP_SCopy
76027       ** instructions.
76028       */
76029       ExprList *pList = pExpr->x.pList;
76030       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76031       if( pList ){
76032         int i = pList->nExpr;
76033         struct ExprList_item *pItem = pList->a;
76034         for(; i>0; i--, pItem++){
76035           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
76036         }
76037       }
76038       break;
76039     }
76040   }
76041   if( isAppropriateForFactoring(pExpr) ){
76042     int r1 = ++pParse->nMem;
76043     int r2;
76044     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
76045     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
76046     pExpr->op2 = pExpr->op;
76047     pExpr->op = TK_REGISTER;
76048     pExpr->iTable = r2;
76049     return WRC_Prune;
76050   }
76051   return WRC_Continue;
76052 }
76053 
76054 /*
76055 ** Preevaluate constant subexpressions within pExpr and store the
76056 ** results in registers.  Modify pExpr so that the constant subexpresions
76057 ** are TK_REGISTER opcodes that refer to the precomputed values.
76058 **
76059 ** This routine is a no-op if the jump to the cookie-check code has
76060 ** already occur.  Since the cookie-check jump is generated prior to
76061 ** any other serious processing, this check ensures that there is no
76062 ** way to accidently bypass the constant initializations.
76063 **
76064 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
76065 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
76066 ** interface.  This allows test logic to verify that the same answer is
76067 ** obtained for queries regardless of whether or not constants are
76068 ** precomputed into registers or if they are inserted in-line.
76069 */
76070 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
76071   Walker w;
76072   if( pParse->cookieGoto ) return;
76073   if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
76074   w.xExprCallback = evalConstExpr;
76075   w.xSelectCallback = 0;
76076   w.pParse = pParse;
76077   sqlite3WalkExpr(&w, pExpr);
76078 }
76079 
76080 
76081 /*
76082 ** Generate code that pushes the value of every element of the given
76083 ** expression list into a sequence of registers beginning at target.
76084 **
76085 ** Return the number of elements evaluated.
76086 */
76087 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
76088   Parse *pParse,     /* Parsing context */
76089   ExprList *pList,   /* The expression list to be coded */
76090   int target,        /* Where to write results */
76091   int doHardCopy     /* Make a hard copy of every element */
76092 ){
76093   struct ExprList_item *pItem;
76094   int i, n;
76095   assert( pList!=0 );
76096   assert( target>0 );
76097   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
76098   n = pList->nExpr;
76099   for(pItem=pList->a, i=0; i<n; i++, pItem++){
76100     Expr *pExpr = pItem->pExpr;
76101     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
76102     if( inReg!=target+i ){
76103       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
76104                         inReg, target+i);
76105     }
76106   }
76107   return n;
76108 }
76109 
76110 /*
76111 ** Generate code for a BETWEEN operator.
76112 **
76113 **    x BETWEEN y AND z
76114 **
76115 ** The above is equivalent to
76116 **
76117 **    x>=y AND x<=z
76118 **
76119 ** Code it as such, taking care to do the common subexpression
76120 ** elementation of x.
76121 */
76122 static void exprCodeBetween(
76123   Parse *pParse,    /* Parsing and code generating context */
76124   Expr *pExpr,      /* The BETWEEN expression */
76125   int dest,         /* Jump here if the jump is taken */
76126   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
76127   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
76128 ){
76129   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
76130   Expr compLeft;    /* The  x>=y  term */
76131   Expr compRight;   /* The  x<=z  term */
76132   Expr exprX;       /* The  x  subexpression */
76133   int regFree1 = 0; /* Temporary use register */
76134 
76135   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76136   exprX = *pExpr->pLeft;
76137   exprAnd.op = TK_AND;
76138   exprAnd.pLeft = &compLeft;
76139   exprAnd.pRight = &compRight;
76140   compLeft.op = TK_GE;
76141   compLeft.pLeft = &exprX;
76142   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
76143   compRight.op = TK_LE;
76144   compRight.pLeft = &exprX;
76145   compRight.pRight = pExpr->x.pList->a[1].pExpr;
76146   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
76147   exprX.op = TK_REGISTER;
76148   if( jumpIfTrue ){
76149     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
76150   }else{
76151     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
76152   }
76153   sqlite3ReleaseTempReg(pParse, regFree1);
76154 
76155   /* Ensure adequate test coverage */
76156   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
76157   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
76158   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
76159   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
76160   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
76161   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
76162   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
76163   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
76164 }
76165 
76166 /*
76167 ** Generate code for a boolean expression such that a jump is made
76168 ** to the label "dest" if the expression is true but execution
76169 ** continues straight thru if the expression is false.
76170 **
76171 ** If the expression evaluates to NULL (neither true nor false), then
76172 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
76173 **
76174 ** This code depends on the fact that certain token values (ex: TK_EQ)
76175 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
76176 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
76177 ** the make process cause these values to align.  Assert()s in the code
76178 ** below verify that the numbers are aligned correctly.
76179 */
76180 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76181   Vdbe *v = pParse->pVdbe;
76182   int op = 0;
76183   int regFree1 = 0;
76184   int regFree2 = 0;
76185   int r1, r2;
76186 
76187   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76188   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
76189   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
76190   op = pExpr->op;
76191   switch( op ){
76192     case TK_AND: {
76193       int d2 = sqlite3VdbeMakeLabel(v);
76194       testcase( jumpIfNull==0 );
76195       sqlite3ExprCachePush(pParse);
76196       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
76197       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76198       sqlite3VdbeResolveLabel(v, d2);
76199       sqlite3ExprCachePop(pParse, 1);
76200       break;
76201     }
76202     case TK_OR: {
76203       testcase( jumpIfNull==0 );
76204       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76205       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
76206       break;
76207     }
76208     case TK_NOT: {
76209       testcase( jumpIfNull==0 );
76210       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76211       break;
76212     }
76213     case TK_LT:
76214     case TK_LE:
76215     case TK_GT:
76216     case TK_GE:
76217     case TK_NE:
76218     case TK_EQ: {
76219       assert( TK_LT==OP_Lt );
76220       assert( TK_LE==OP_Le );
76221       assert( TK_GT==OP_Gt );
76222       assert( TK_GE==OP_Ge );
76223       assert( TK_EQ==OP_Eq );
76224       assert( TK_NE==OP_Ne );
76225       testcase( op==TK_LT );
76226       testcase( op==TK_LE );
76227       testcase( op==TK_GT );
76228       testcase( op==TK_GE );
76229       testcase( op==TK_EQ );
76230       testcase( op==TK_NE );
76231       testcase( jumpIfNull==0 );
76232       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76233       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76234       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76235                   r1, r2, dest, jumpIfNull);
76236       testcase( regFree1==0 );
76237       testcase( regFree2==0 );
76238       break;
76239     }
76240     case TK_IS:
76241     case TK_ISNOT: {
76242       testcase( op==TK_IS );
76243       testcase( op==TK_ISNOT );
76244       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76245       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76246       op = (op==TK_IS) ? TK_EQ : TK_NE;
76247       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76248                   r1, r2, dest, SQLITE_NULLEQ);
76249       testcase( regFree1==0 );
76250       testcase( regFree2==0 );
76251       break;
76252     }
76253     case TK_ISNULL:
76254     case TK_NOTNULL: {
76255       assert( TK_ISNULL==OP_IsNull );
76256       assert( TK_NOTNULL==OP_NotNull );
76257       testcase( op==TK_ISNULL );
76258       testcase( op==TK_NOTNULL );
76259       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76260       sqlite3VdbeAddOp2(v, op, r1, dest);
76261       testcase( regFree1==0 );
76262       break;
76263     }
76264     case TK_BETWEEN: {
76265       testcase( jumpIfNull==0 );
76266       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
76267       break;
76268     }
76269 #ifndef SQLITE_OMIT_SUBQUERY
76270     case TK_IN: {
76271       int destIfFalse = sqlite3VdbeMakeLabel(v);
76272       int destIfNull = jumpIfNull ? dest : destIfFalse;
76273       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
76274       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
76275       sqlite3VdbeResolveLabel(v, destIfFalse);
76276       break;
76277     }
76278 #endif
76279     default: {
76280       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76281       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
76282       testcase( regFree1==0 );
76283       testcase( jumpIfNull==0 );
76284       break;
76285     }
76286   }
76287   sqlite3ReleaseTempReg(pParse, regFree1);
76288   sqlite3ReleaseTempReg(pParse, regFree2);
76289 }
76290 
76291 /*
76292 ** Generate code for a boolean expression such that a jump is made
76293 ** to the label "dest" if the expression is false but execution
76294 ** continues straight thru if the expression is true.
76295 **
76296 ** If the expression evaluates to NULL (neither true nor false) then
76297 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
76298 ** is 0.
76299 */
76300 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
76301   Vdbe *v = pParse->pVdbe;
76302   int op = 0;
76303   int regFree1 = 0;
76304   int regFree2 = 0;
76305   int r1, r2;
76306 
76307   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
76308   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
76309   if( pExpr==0 )    return;
76310 
76311   /* The value of pExpr->op and op are related as follows:
76312   **
76313   **       pExpr->op            op
76314   **       ---------          ----------
76315   **       TK_ISNULL          OP_NotNull
76316   **       TK_NOTNULL         OP_IsNull
76317   **       TK_NE              OP_Eq
76318   **       TK_EQ              OP_Ne
76319   **       TK_GT              OP_Le
76320   **       TK_LE              OP_Gt
76321   **       TK_GE              OP_Lt
76322   **       TK_LT              OP_Ge
76323   **
76324   ** For other values of pExpr->op, op is undefined and unused.
76325   ** The value of TK_ and OP_ constants are arranged such that we
76326   ** can compute the mapping above using the following expression.
76327   ** Assert()s verify that the computation is correct.
76328   */
76329   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
76330 
76331   /* Verify correct alignment of TK_ and OP_ constants
76332   */
76333   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
76334   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
76335   assert( pExpr->op!=TK_NE || op==OP_Eq );
76336   assert( pExpr->op!=TK_EQ || op==OP_Ne );
76337   assert( pExpr->op!=TK_LT || op==OP_Ge );
76338   assert( pExpr->op!=TK_LE || op==OP_Gt );
76339   assert( pExpr->op!=TK_GT || op==OP_Le );
76340   assert( pExpr->op!=TK_GE || op==OP_Lt );
76341 
76342   switch( pExpr->op ){
76343     case TK_AND: {
76344       testcase( jumpIfNull==0 );
76345       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
76346       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76347       break;
76348     }
76349     case TK_OR: {
76350       int d2 = sqlite3VdbeMakeLabel(v);
76351       testcase( jumpIfNull==0 );
76352       sqlite3ExprCachePush(pParse);
76353       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
76354       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
76355       sqlite3VdbeResolveLabel(v, d2);
76356       sqlite3ExprCachePop(pParse, 1);
76357       break;
76358     }
76359     case TK_NOT: {
76360       testcase( jumpIfNull==0 );
76361       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
76362       break;
76363     }
76364     case TK_LT:
76365     case TK_LE:
76366     case TK_GT:
76367     case TK_GE:
76368     case TK_NE:
76369     case TK_EQ: {
76370       testcase( op==TK_LT );
76371       testcase( op==TK_LE );
76372       testcase( op==TK_GT );
76373       testcase( op==TK_GE );
76374       testcase( op==TK_EQ );
76375       testcase( op==TK_NE );
76376       testcase( jumpIfNull==0 );
76377       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76378       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76379       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76380                   r1, r2, dest, jumpIfNull);
76381       testcase( regFree1==0 );
76382       testcase( regFree2==0 );
76383       break;
76384     }
76385     case TK_IS:
76386     case TK_ISNOT: {
76387       testcase( pExpr->op==TK_IS );
76388       testcase( pExpr->op==TK_ISNOT );
76389       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76390       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76391       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
76392       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76393                   r1, r2, dest, SQLITE_NULLEQ);
76394       testcase( regFree1==0 );
76395       testcase( regFree2==0 );
76396       break;
76397     }
76398     case TK_ISNULL:
76399     case TK_NOTNULL: {
76400       testcase( op==TK_ISNULL );
76401       testcase( op==TK_NOTNULL );
76402       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76403       sqlite3VdbeAddOp2(v, op, r1, dest);
76404       testcase( regFree1==0 );
76405       break;
76406     }
76407     case TK_BETWEEN: {
76408       testcase( jumpIfNull==0 );
76409       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
76410       break;
76411     }
76412 #ifndef SQLITE_OMIT_SUBQUERY
76413     case TK_IN: {
76414       if( jumpIfNull ){
76415         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
76416       }else{
76417         int destIfNull = sqlite3VdbeMakeLabel(v);
76418         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
76419         sqlite3VdbeResolveLabel(v, destIfNull);
76420       }
76421       break;
76422     }
76423 #endif
76424     default: {
76425       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
76426       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
76427       testcase( regFree1==0 );
76428       testcase( jumpIfNull==0 );
76429       break;
76430     }
76431   }
76432   sqlite3ReleaseTempReg(pParse, regFree1);
76433   sqlite3ReleaseTempReg(pParse, regFree2);
76434 }
76435 
76436 /*
76437 ** Do a deep comparison of two expression trees.  Return 0 if the two
76438 ** expressions are completely identical.  Return 1 if they differ only
76439 ** by a COLLATE operator at the top level.  Return 2 if there are differences
76440 ** other than the top-level COLLATE operator.
76441 **
76442 ** Sometimes this routine will return 2 even if the two expressions
76443 ** really are equivalent.  If we cannot prove that the expressions are
76444 ** identical, we return 2 just to be safe.  So if this routine
76445 ** returns 2, then you do not really know for certain if the two
76446 ** expressions are the same.  But if you get a 0 or 1 return, then you
76447 ** can be sure the expressions are the same.  In the places where
76448 ** this routine is used, it does not hurt to get an extra 2 - that
76449 ** just might result in some slightly slower code.  But returning
76450 ** an incorrect 0 or 1 could lead to a malfunction.
76451 */
76452 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
76453   if( pA==0||pB==0 ){
76454     return pB==pA ? 0 : 2;
76455   }
76456   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
76457   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
76458   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
76459     return 2;
76460   }
76461   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
76462   if( pA->op!=pB->op ) return 2;
76463   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
76464   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
76465   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
76466   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
76467   if( ExprHasProperty(pA, EP_IntValue) ){
76468     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
76469       return 2;
76470     }
76471   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
76472     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
76473     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
76474       return 2;
76475     }
76476   }
76477   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
76478   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
76479   return 0;
76480 }
76481 
76482 /*
76483 ** Compare two ExprList objects.  Return 0 if they are identical and
76484 ** non-zero if they differ in any way.
76485 **
76486 ** This routine might return non-zero for equivalent ExprLists.  The
76487 ** only consequence will be disabled optimizations.  But this routine
76488 ** must never return 0 if the two ExprList objects are different, or
76489 ** a malfunction will result.
76490 **
76491 ** Two NULL pointers are considered to be the same.  But a NULL pointer
76492 ** always differs from a non-NULL pointer.
76493 */
76494 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
76495   int i;
76496   if( pA==0 && pB==0 ) return 0;
76497   if( pA==0 || pB==0 ) return 1;
76498   if( pA->nExpr!=pB->nExpr ) return 1;
76499   for(i=0; i<pA->nExpr; i++){
76500     Expr *pExprA = pA->a[i].pExpr;
76501     Expr *pExprB = pB->a[i].pExpr;
76502     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
76503     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
76504   }
76505   return 0;
76506 }
76507 
76508 /*
76509 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
76510 ** the new element.  Return a negative number if malloc fails.
76511 */
76512 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
76513   int i;
76514   pInfo->aCol = sqlite3ArrayAllocate(
76515        db,
76516        pInfo->aCol,
76517        sizeof(pInfo->aCol[0]),
76518        3,
76519        &pInfo->nColumn,
76520        &pInfo->nColumnAlloc,
76521        &i
76522   );
76523   return i;
76524 }
76525 
76526 /*
76527 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
76528 ** the new element.  Return a negative number if malloc fails.
76529 */
76530 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
76531   int i;
76532   pInfo->aFunc = sqlite3ArrayAllocate(
76533        db,
76534        pInfo->aFunc,
76535        sizeof(pInfo->aFunc[0]),
76536        3,
76537        &pInfo->nFunc,
76538        &pInfo->nFuncAlloc,
76539        &i
76540   );
76541   return i;
76542 }
76543 
76544 /*
76545 ** This is the xExprCallback for a tree walker.  It is used to
76546 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
76547 ** for additional information.
76548 */
76549 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
76550   int i;
76551   NameContext *pNC = pWalker->u.pNC;
76552   Parse *pParse = pNC->pParse;
76553   SrcList *pSrcList = pNC->pSrcList;
76554   AggInfo *pAggInfo = pNC->pAggInfo;
76555 
76556   switch( pExpr->op ){
76557     case TK_AGG_COLUMN:
76558     case TK_COLUMN: {
76559       testcase( pExpr->op==TK_AGG_COLUMN );
76560       testcase( pExpr->op==TK_COLUMN );
76561       /* Check to see if the column is in one of the tables in the FROM
76562       ** clause of the aggregate query */
76563       if( ALWAYS(pSrcList!=0) ){
76564         struct SrcList_item *pItem = pSrcList->a;
76565         for(i=0; i<pSrcList->nSrc; i++, pItem++){
76566           struct AggInfo_col *pCol;
76567           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
76568           if( pExpr->iTable==pItem->iCursor ){
76569             /* If we reach this point, it means that pExpr refers to a table
76570             ** that is in the FROM clause of the aggregate query.
76571             **
76572             ** Make an entry for the column in pAggInfo->aCol[] if there
76573             ** is not an entry there already.
76574             */
76575             int k;
76576             pCol = pAggInfo->aCol;
76577             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
76578               if( pCol->iTable==pExpr->iTable &&
76579                   pCol->iColumn==pExpr->iColumn ){
76580                 break;
76581               }
76582             }
76583             if( (k>=pAggInfo->nColumn)
76584              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
76585             ){
76586               pCol = &pAggInfo->aCol[k];
76587               pCol->pTab = pExpr->pTab;
76588               pCol->iTable = pExpr->iTable;
76589               pCol->iColumn = pExpr->iColumn;
76590               pCol->iMem = ++pParse->nMem;
76591               pCol->iSorterColumn = -1;
76592               pCol->pExpr = pExpr;
76593               if( pAggInfo->pGroupBy ){
76594                 int j, n;
76595                 ExprList *pGB = pAggInfo->pGroupBy;
76596                 struct ExprList_item *pTerm = pGB->a;
76597                 n = pGB->nExpr;
76598                 for(j=0; j<n; j++, pTerm++){
76599                   Expr *pE = pTerm->pExpr;
76600                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
76601                       pE->iColumn==pExpr->iColumn ){
76602                     pCol->iSorterColumn = j;
76603                     break;
76604                   }
76605                 }
76606               }
76607               if( pCol->iSorterColumn<0 ){
76608                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
76609               }
76610             }
76611             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
76612             ** because it was there before or because we just created it).
76613             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
76614             ** pAggInfo->aCol[] entry.
76615             */
76616             ExprSetIrreducible(pExpr);
76617             pExpr->pAggInfo = pAggInfo;
76618             pExpr->op = TK_AGG_COLUMN;
76619             pExpr->iAgg = (i16)k;
76620             break;
76621           } /* endif pExpr->iTable==pItem->iCursor */
76622         } /* end loop over pSrcList */
76623       }
76624       return WRC_Prune;
76625     }
76626     case TK_AGG_FUNCTION: {
76627       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
76628       ** to be ignored */
76629       if( pNC->nDepth==0 ){
76630         /* Check to see if pExpr is a duplicate of another aggregate
76631         ** function that is already in the pAggInfo structure
76632         */
76633         struct AggInfo_func *pItem = pAggInfo->aFunc;
76634         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
76635           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
76636             break;
76637           }
76638         }
76639         if( i>=pAggInfo->nFunc ){
76640           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
76641           */
76642           u8 enc = ENC(pParse->db);
76643           i = addAggInfoFunc(pParse->db, pAggInfo);
76644           if( i>=0 ){
76645             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76646             pItem = &pAggInfo->aFunc[i];
76647             pItem->pExpr = pExpr;
76648             pItem->iMem = ++pParse->nMem;
76649             assert( !ExprHasProperty(pExpr, EP_IntValue) );
76650             pItem->pFunc = sqlite3FindFunction(pParse->db,
76651                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
76652                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
76653             if( pExpr->flags & EP_Distinct ){
76654               pItem->iDistinct = pParse->nTab++;
76655             }else{
76656               pItem->iDistinct = -1;
76657             }
76658           }
76659         }
76660         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
76661         */
76662         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
76663         ExprSetIrreducible(pExpr);
76664         pExpr->iAgg = (i16)i;
76665         pExpr->pAggInfo = pAggInfo;
76666         return WRC_Prune;
76667       }
76668     }
76669   }
76670   return WRC_Continue;
76671 }
76672 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
76673   NameContext *pNC = pWalker->u.pNC;
76674   if( pNC->nDepth==0 ){
76675     pNC->nDepth++;
76676     sqlite3WalkSelect(pWalker, pSelect);
76677     pNC->nDepth--;
76678     return WRC_Prune;
76679   }else{
76680     return WRC_Continue;
76681   }
76682 }
76683 
76684 /*
76685 ** Analyze the given expression looking for aggregate functions and
76686 ** for variables that need to be added to the pParse->aAgg[] array.
76687 ** Make additional entries to the pParse->aAgg[] array as necessary.
76688 **
76689 ** This routine should only be called after the expression has been
76690 ** analyzed by sqlite3ResolveExprNames().
76691 */
76692 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
76693   Walker w;
76694   w.xExprCallback = analyzeAggregate;
76695   w.xSelectCallback = analyzeAggregatesInSelect;
76696   w.u.pNC = pNC;
76697   assert( pNC->pSrcList!=0 );
76698   sqlite3WalkExpr(&w, pExpr);
76699 }
76700 
76701 /*
76702 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
76703 ** expression list.  Return the number of errors.
76704 **
76705 ** If an error is found, the analysis is cut short.
76706 */
76707 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
76708   struct ExprList_item *pItem;
76709   int i;
76710   if( pList ){
76711     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76712       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
76713     }
76714   }
76715 }
76716 
76717 /*
76718 ** Allocate a single new register for use to hold some intermediate result.
76719 */
76720 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
76721   if( pParse->nTempReg==0 ){
76722     return ++pParse->nMem;
76723   }
76724   return pParse->aTempReg[--pParse->nTempReg];
76725 }
76726 
76727 /*
76728 ** Deallocate a register, making available for reuse for some other
76729 ** purpose.
76730 **
76731 ** If a register is currently being used by the column cache, then
76732 ** the dallocation is deferred until the column cache line that uses
76733 ** the register becomes stale.
76734 */
76735 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
76736   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76737     int i;
76738     struct yColCache *p;
76739     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76740       if( p->iReg==iReg ){
76741         p->tempReg = 1;
76742         return;
76743       }
76744     }
76745     pParse->aTempReg[pParse->nTempReg++] = iReg;
76746   }
76747 }
76748 
76749 /*
76750 ** Allocate or deallocate a block of nReg consecutive registers
76751 */
76752 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
76753   int i, n;
76754   i = pParse->iRangeReg;
76755   n = pParse->nRangeReg;
76756   if( nReg<=n ){
76757     assert( !usedAsColumnCache(pParse, i, i+n-1) );
76758     pParse->iRangeReg += nReg;
76759     pParse->nRangeReg -= nReg;
76760   }else{
76761     i = pParse->nMem+1;
76762     pParse->nMem += nReg;
76763   }
76764   return i;
76765 }
76766 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
76767   sqlite3ExprCacheRemove(pParse, iReg, nReg);
76768   if( nReg>pParse->nRangeReg ){
76769     pParse->nRangeReg = nReg;
76770     pParse->iRangeReg = iReg;
76771   }
76772 }
76773 
76774 /************** End of expr.c ************************************************/
76775 /************** Begin file alter.c *******************************************/
76776 /*
76777 ** 2005 February 15
76778 **
76779 ** The author disclaims copyright to this source code.  In place of
76780 ** a legal notice, here is a blessing:
76781 **
76782 **    May you do good and not evil.
76783 **    May you find forgiveness for yourself and forgive others.
76784 **    May you share freely, never taking more than you give.
76785 **
76786 *************************************************************************
76787 ** This file contains C code routines that used to generate VDBE code
76788 ** that implements the ALTER TABLE command.
76789 */
76790 
76791 /*
76792 ** The code in this file only exists if we are not omitting the
76793 ** ALTER TABLE logic from the build.
76794 */
76795 #ifndef SQLITE_OMIT_ALTERTABLE
76796 
76797 
76798 /*
76799 ** This function is used by SQL generated to implement the
76800 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
76801 ** CREATE INDEX command. The second is a table name. The table name in
76802 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
76803 ** argument and the result returned. Examples:
76804 **
76805 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
76806 **     -> 'CREATE TABLE def(a, b, c)'
76807 **
76808 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
76809 **     -> 'CREATE INDEX i ON def(a, b, c)'
76810 */
76811 static void renameTableFunc(
76812   sqlite3_context *context,
76813   int NotUsed,
76814   sqlite3_value **argv
76815 ){
76816   unsigned char const *zSql = sqlite3_value_text(argv[0]);
76817   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
76818 
76819   int token;
76820   Token tname;
76821   unsigned char const *zCsr = zSql;
76822   int len = 0;
76823   char *zRet;
76824 
76825   sqlite3 *db = sqlite3_context_db_handle(context);
76826 
76827   UNUSED_PARAMETER(NotUsed);
76828 
76829   /* The principle used to locate the table name in the CREATE TABLE
76830   ** statement is that the table name is the first non-space token that
76831   ** is immediately followed by a TK_LP or TK_USING token.
76832   */
76833   if( zSql ){
76834     do {
76835       if( !*zCsr ){
76836         /* Ran out of input before finding an opening bracket. Return NULL. */
76837         return;
76838       }
76839 
76840       /* Store the token that zCsr points to in tname. */
76841       tname.z = (char*)zCsr;
76842       tname.n = len;
76843 
76844       /* Advance zCsr to the next token. Store that token type in 'token',
76845       ** and its length in 'len' (to be used next iteration of this loop).
76846       */
76847       do {
76848         zCsr += len;
76849         len = sqlite3GetToken(zCsr, &token);
76850       } while( token==TK_SPACE );
76851       assert( len>0 );
76852     } while( token!=TK_LP && token!=TK_USING );
76853 
76854     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
76855        zTableName, tname.z+tname.n);
76856     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
76857   }
76858 }
76859 
76860 /*
76861 ** This C function implements an SQL user function that is used by SQL code
76862 ** generated by the ALTER TABLE ... RENAME command to modify the definition
76863 ** of any foreign key constraints that use the table being renamed as the
76864 ** parent table. It is passed three arguments:
76865 **
76866 **   1) The complete text of the CREATE TABLE statement being modified,
76867 **   2) The old name of the table being renamed, and
76868 **   3) The new name of the table being renamed.
76869 **
76870 ** It returns the new CREATE TABLE statement. For example:
76871 **
76872 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
76873 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
76874 */
76875 #ifndef SQLITE_OMIT_FOREIGN_KEY
76876 static void renameParentFunc(
76877   sqlite3_context *context,
76878   int NotUsed,
76879   sqlite3_value **argv
76880 ){
76881   sqlite3 *db = sqlite3_context_db_handle(context);
76882   char *zOutput = 0;
76883   char *zResult;
76884   unsigned char const *zInput = sqlite3_value_text(argv[0]);
76885   unsigned char const *zOld = sqlite3_value_text(argv[1]);
76886   unsigned char const *zNew = sqlite3_value_text(argv[2]);
76887 
76888   unsigned const char *z;         /* Pointer to token */
76889   int n;                          /* Length of token z */
76890   int token;                      /* Type of token */
76891 
76892   UNUSED_PARAMETER(NotUsed);
76893   for(z=zInput; *z; z=z+n){
76894     n = sqlite3GetToken(z, &token);
76895     if( token==TK_REFERENCES ){
76896       char *zParent;
76897       do {
76898         z += n;
76899         n = sqlite3GetToken(z, &token);
76900       }while( token==TK_SPACE );
76901 
76902       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
76903       if( zParent==0 ) break;
76904       sqlite3Dequote(zParent);
76905       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
76906         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
76907             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
76908         );
76909         sqlite3DbFree(db, zOutput);
76910         zOutput = zOut;
76911         zInput = &z[n];
76912       }
76913       sqlite3DbFree(db, zParent);
76914     }
76915   }
76916 
76917   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
76918   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
76919   sqlite3DbFree(db, zOutput);
76920 }
76921 #endif
76922 
76923 #ifndef SQLITE_OMIT_TRIGGER
76924 /* This function is used by SQL generated to implement the
76925 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
76926 ** statement. The second is a table name. The table name in the CREATE
76927 ** TRIGGER statement is replaced with the third argument and the result
76928 ** returned. This is analagous to renameTableFunc() above, except for CREATE
76929 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
76930 */
76931 static void renameTriggerFunc(
76932   sqlite3_context *context,
76933   int NotUsed,
76934   sqlite3_value **argv
76935 ){
76936   unsigned char const *zSql = sqlite3_value_text(argv[0]);
76937   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
76938 
76939   int token;
76940   Token tname;
76941   int dist = 3;
76942   unsigned char const *zCsr = zSql;
76943   int len = 0;
76944   char *zRet;
76945   sqlite3 *db = sqlite3_context_db_handle(context);
76946 
76947   UNUSED_PARAMETER(NotUsed);
76948 
76949   /* The principle used to locate the table name in the CREATE TRIGGER
76950   ** statement is that the table name is the first token that is immediatedly
76951   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
76952   ** of TK_WHEN, TK_BEGIN or TK_FOR.
76953   */
76954   if( zSql ){
76955     do {
76956 
76957       if( !*zCsr ){
76958         /* Ran out of input before finding the table name. Return NULL. */
76959         return;
76960       }
76961 
76962       /* Store the token that zCsr points to in tname. */
76963       tname.z = (char*)zCsr;
76964       tname.n = len;
76965 
76966       /* Advance zCsr to the next token. Store that token type in 'token',
76967       ** and its length in 'len' (to be used next iteration of this loop).
76968       */
76969       do {
76970         zCsr += len;
76971         len = sqlite3GetToken(zCsr, &token);
76972       }while( token==TK_SPACE );
76973       assert( len>0 );
76974 
76975       /* Variable 'dist' stores the number of tokens read since the most
76976       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
76977       ** token is read and 'dist' equals 2, the condition stated above
76978       ** to be met.
76979       **
76980       ** Note that ON cannot be a database, table or column name, so
76981       ** there is no need to worry about syntax like
76982       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
76983       */
76984       dist++;
76985       if( token==TK_DOT || token==TK_ON ){
76986         dist = 0;
76987       }
76988     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
76989 
76990     /* Variable tname now contains the token that is the old table-name
76991     ** in the CREATE TRIGGER statement.
76992     */
76993     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
76994        zTableName, tname.z+tname.n);
76995     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
76996   }
76997 }
76998 #endif   /* !SQLITE_OMIT_TRIGGER */
76999 
77000 /*
77001 ** Register built-in functions used to help implement ALTER TABLE
77002 */
77003 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
77004   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
77005     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
77006 #ifndef SQLITE_OMIT_TRIGGER
77007     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
77008 #endif
77009 #ifndef SQLITE_OMIT_FOREIGN_KEY
77010     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
77011 #endif
77012   };
77013   int i;
77014   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
77015   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
77016 
77017   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
77018     sqlite3FuncDefInsert(pHash, &aFunc[i]);
77019   }
77020 }
77021 
77022 /*
77023 ** This function is used to create the text of expressions of the form:
77024 **
77025 **   name=<constant1> OR name=<constant2> OR ...
77026 **
77027 ** If argument zWhere is NULL, then a pointer string containing the text
77028 ** "name=<constant>" is returned, where <constant> is the quoted version
77029 ** of the string passed as argument zConstant. The returned buffer is
77030 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
77031 ** caller to ensure that it is eventually freed.
77032 **
77033 ** If argument zWhere is not NULL, then the string returned is
77034 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
77035 ** In this case zWhere is passed to sqlite3DbFree() before returning.
77036 **
77037 */
77038 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
77039   char *zNew;
77040   if( !zWhere ){
77041     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
77042   }else{
77043     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
77044     sqlite3DbFree(db, zWhere);
77045   }
77046   return zNew;
77047 }
77048 
77049 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77050 /*
77051 ** Generate the text of a WHERE expression which can be used to select all
77052 ** tables that have foreign key constraints that refer to table pTab (i.e.
77053 ** constraints for which pTab is the parent table) from the sqlite_master
77054 ** table.
77055 */
77056 static char *whereForeignKeys(Parse *pParse, Table *pTab){
77057   FKey *p;
77058   char *zWhere = 0;
77059   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
77060     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
77061   }
77062   return zWhere;
77063 }
77064 #endif
77065 
77066 /*
77067 ** Generate the text of a WHERE expression which can be used to select all
77068 ** temporary triggers on table pTab from the sqlite_temp_master table. If
77069 ** table pTab has no temporary triggers, or is itself stored in the
77070 ** temporary database, NULL is returned.
77071 */
77072 static char *whereTempTriggers(Parse *pParse, Table *pTab){
77073   Trigger *pTrig;
77074   char *zWhere = 0;
77075   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
77076 
77077   /* If the table is not located in the temp-db (in which case NULL is
77078   ** returned, loop through the tables list of triggers. For each trigger
77079   ** that is not part of the temp-db schema, add a clause to the WHERE
77080   ** expression being built up in zWhere.
77081   */
77082   if( pTab->pSchema!=pTempSchema ){
77083     sqlite3 *db = pParse->db;
77084     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
77085       if( pTrig->pSchema==pTempSchema ){
77086         zWhere = whereOrName(db, zWhere, pTrig->zName);
77087       }
77088     }
77089   }
77090   if( zWhere ){
77091     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
77092     sqlite3DbFree(pParse->db, zWhere);
77093     zWhere = zNew;
77094   }
77095   return zWhere;
77096 }
77097 
77098 /*
77099 ** Generate code to drop and reload the internal representation of table
77100 ** pTab from the database, including triggers and temporary triggers.
77101 ** Argument zName is the name of the table in the database schema at
77102 ** the time the generated code is executed. This can be different from
77103 ** pTab->zName if this function is being called to code part of an
77104 ** "ALTER TABLE RENAME TO" statement.
77105 */
77106 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
77107   Vdbe *v;
77108   char *zWhere;
77109   int iDb;                   /* Index of database containing pTab */
77110 #ifndef SQLITE_OMIT_TRIGGER
77111   Trigger *pTrig;
77112 #endif
77113 
77114   v = sqlite3GetVdbe(pParse);
77115   if( NEVER(v==0) ) return;
77116   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77117   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77118   assert( iDb>=0 );
77119 
77120 #ifndef SQLITE_OMIT_TRIGGER
77121   /* Drop any table triggers from the internal schema. */
77122   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
77123     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
77124     assert( iTrigDb==iDb || iTrigDb==1 );
77125     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
77126   }
77127 #endif
77128 
77129   /* Drop the table and index from the internal schema.  */
77130   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
77131 
77132   /* Reload the table, index and permanent trigger schemas. */
77133   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
77134   if( !zWhere ) return;
77135   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
77136 
77137 #ifndef SQLITE_OMIT_TRIGGER
77138   /* Now, if the table is not stored in the temp database, reload any temp
77139   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
77140   */
77141   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77142     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
77143   }
77144 #endif
77145 }
77146 
77147 /*
77148 ** Parameter zName is the name of a table that is about to be altered
77149 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
77150 ** If the table is a system table, this function leaves an error message
77151 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
77152 **
77153 ** Or, if zName is not a system table, zero is returned.
77154 */
77155 static int isSystemTable(Parse *pParse, const char *zName){
77156   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
77157     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
77158     return 1;
77159   }
77160   return 0;
77161 }
77162 
77163 /*
77164 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
77165 ** command.
77166 */
77167 SQLITE_PRIVATE void sqlite3AlterRenameTable(
77168   Parse *pParse,            /* Parser context. */
77169   SrcList *pSrc,            /* The table to rename. */
77170   Token *pName              /* The new table name. */
77171 ){
77172   int iDb;                  /* Database that contains the table */
77173   char *zDb;                /* Name of database iDb */
77174   Table *pTab;              /* Table being renamed */
77175   char *zName = 0;          /* NULL-terminated version of pName */
77176   sqlite3 *db = pParse->db; /* Database connection */
77177   int nTabName;             /* Number of UTF-8 characters in zTabName */
77178   const char *zTabName;     /* Original name of the table */
77179   Vdbe *v;
77180 #ifndef SQLITE_OMIT_TRIGGER
77181   char *zWhere = 0;         /* Where clause to locate temp triggers */
77182 #endif
77183   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
77184   int savedDbFlags;         /* Saved value of db->flags */
77185 
77186   savedDbFlags = db->flags;
77187   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
77188   assert( pSrc->nSrc==1 );
77189   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
77190 
77191   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
77192   if( !pTab ) goto exit_rename_table;
77193   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
77194   zDb = db->aDb[iDb].zName;
77195   db->flags |= SQLITE_PreferBuiltin;
77196 
77197   /* Get a NULL terminated version of the new table name. */
77198   zName = sqlite3NameFromToken(db, pName);
77199   if( !zName ) goto exit_rename_table;
77200 
77201   /* Check that a table or index named 'zName' does not already exist
77202   ** in database iDb. If so, this is an error.
77203   */
77204   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
77205     sqlite3ErrorMsg(pParse,
77206         "there is already another table or index with this name: %s", zName);
77207     goto exit_rename_table;
77208   }
77209 
77210   /* Make sure it is not a system table being altered, or a reserved name
77211   ** that the table is being renamed to.
77212   */
77213   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
77214     goto exit_rename_table;
77215   }
77216   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
77217     exit_rename_table;
77218   }
77219 
77220 #ifndef SQLITE_OMIT_VIEW
77221   if( pTab->pSelect ){
77222     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
77223     goto exit_rename_table;
77224   }
77225 #endif
77226 
77227 #ifndef SQLITE_OMIT_AUTHORIZATION
77228   /* Invoke the authorization callback. */
77229   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
77230     goto exit_rename_table;
77231   }
77232 #endif
77233 
77234 #ifndef SQLITE_OMIT_VIRTUALTABLE
77235   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
77236     goto exit_rename_table;
77237   }
77238   if( IsVirtual(pTab) ){
77239     pVTab = sqlite3GetVTable(db, pTab);
77240     if( pVTab->pVtab->pModule->xRename==0 ){
77241       pVTab = 0;
77242     }
77243   }
77244 #endif
77245 
77246   /* Begin a transaction and code the VerifyCookie for database iDb.
77247   ** Then modify the schema cookie (since the ALTER TABLE modifies the
77248   ** schema). Open a statement transaction if the table is a virtual
77249   ** table.
77250   */
77251   v = sqlite3GetVdbe(pParse);
77252   if( v==0 ){
77253     goto exit_rename_table;
77254   }
77255   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
77256   sqlite3ChangeCookie(pParse, iDb);
77257 
77258   /* If this is a virtual table, invoke the xRename() function if
77259   ** one is defined. The xRename() callback will modify the names
77260   ** of any resources used by the v-table implementation (including other
77261   ** SQLite tables) that are identified by the name of the virtual table.
77262   */
77263 #ifndef SQLITE_OMIT_VIRTUALTABLE
77264   if( pVTab ){
77265     int i = ++pParse->nMem;
77266     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
77267     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
77268     sqlite3MayAbort(pParse);
77269   }
77270 #endif
77271 
77272   /* figure out how many UTF-8 characters are in zName */
77273   zTabName = pTab->zName;
77274   nTabName = sqlite3Utf8CharLen(zTabName, -1);
77275 
77276 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77277   if( db->flags&SQLITE_ForeignKeys ){
77278     /* If foreign-key support is enabled, rewrite the CREATE TABLE
77279     ** statements corresponding to all child tables of foreign key constraints
77280     ** for which the renamed table is the parent table.  */
77281     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
77282       sqlite3NestedParse(pParse,
77283           "UPDATE \"%w\".%s SET "
77284               "sql = sqlite_rename_parent(sql, %Q, %Q) "
77285               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
77286       sqlite3DbFree(db, zWhere);
77287     }
77288   }
77289 #endif
77290 
77291   /* Modify the sqlite_master table to use the new table name. */
77292   sqlite3NestedParse(pParse,
77293       "UPDATE %Q.%s SET "
77294 #ifdef SQLITE_OMIT_TRIGGER
77295           "sql = sqlite_rename_table(sql, %Q), "
77296 #else
77297           "sql = CASE "
77298             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
77299             "ELSE sqlite_rename_table(sql, %Q) END, "
77300 #endif
77301           "tbl_name = %Q, "
77302           "name = CASE "
77303             "WHEN type='table' THEN %Q "
77304             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
77305              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
77306             "ELSE name END "
77307       "WHERE tbl_name=%Q AND "
77308           "(type='table' OR type='index' OR type='trigger');",
77309       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
77310 #ifndef SQLITE_OMIT_TRIGGER
77311       zName,
77312 #endif
77313       zName, nTabName, zTabName
77314   );
77315 
77316 #ifndef SQLITE_OMIT_AUTOINCREMENT
77317   /* If the sqlite_sequence table exists in this database, then update
77318   ** it with the new table name.
77319   */
77320   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
77321     sqlite3NestedParse(pParse,
77322         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
77323         zDb, zName, pTab->zName);
77324   }
77325 #endif
77326 
77327 #ifndef SQLITE_OMIT_TRIGGER
77328   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
77329   ** table. Don't do this if the table being ALTERed is itself located in
77330   ** the temp database.
77331   */
77332   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
77333     sqlite3NestedParse(pParse,
77334         "UPDATE sqlite_temp_master SET "
77335             "sql = sqlite_rename_trigger(sql, %Q), "
77336             "tbl_name = %Q "
77337             "WHERE %s;", zName, zName, zWhere);
77338     sqlite3DbFree(db, zWhere);
77339   }
77340 #endif
77341 
77342 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
77343   if( db->flags&SQLITE_ForeignKeys ){
77344     FKey *p;
77345     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
77346       Table *pFrom = p->pFrom;
77347       if( pFrom!=pTab ){
77348         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
77349       }
77350     }
77351   }
77352 #endif
77353 
77354   /* Drop and reload the internal table schema. */
77355   reloadTableSchema(pParse, pTab, zName);
77356 
77357 exit_rename_table:
77358   sqlite3SrcListDelete(db, pSrc);
77359   sqlite3DbFree(db, zName);
77360   db->flags = savedDbFlags;
77361 }
77362 
77363 
77364 /*
77365 ** Generate code to make sure the file format number is at least minFormat.
77366 ** The generated code will increase the file format number if necessary.
77367 */
77368 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
77369   Vdbe *v;
77370   v = sqlite3GetVdbe(pParse);
77371   /* The VDBE should have been allocated before this routine is called.
77372   ** If that allocation failed, we would have quit before reaching this
77373   ** point */
77374   if( ALWAYS(v) ){
77375     int r1 = sqlite3GetTempReg(pParse);
77376     int r2 = sqlite3GetTempReg(pParse);
77377     int j1;
77378     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
77379     sqlite3VdbeUsesBtree(v, iDb);
77380     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
77381     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
77382     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
77383     sqlite3VdbeJumpHere(v, j1);
77384     sqlite3ReleaseTempReg(pParse, r1);
77385     sqlite3ReleaseTempReg(pParse, r2);
77386   }
77387 }
77388 
77389 /*
77390 ** This function is called after an "ALTER TABLE ... ADD" statement
77391 ** has been parsed. Argument pColDef contains the text of the new
77392 ** column definition.
77393 **
77394 ** The Table structure pParse->pNewTable was extended to include
77395 ** the new column during parsing.
77396 */
77397 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
77398   Table *pNew;              /* Copy of pParse->pNewTable */
77399   Table *pTab;              /* Table being altered */
77400   int iDb;                  /* Database number */
77401   const char *zDb;          /* Database name */
77402   const char *zTab;         /* Table name */
77403   char *zCol;               /* Null-terminated column definition */
77404   Column *pCol;             /* The new column */
77405   Expr *pDflt;              /* Default value for the new column */
77406   sqlite3 *db;              /* The database connection; */
77407 
77408   db = pParse->db;
77409   if( pParse->nErr || db->mallocFailed ) return;
77410   pNew = pParse->pNewTable;
77411   assert( pNew );
77412 
77413   assert( sqlite3BtreeHoldsAllMutexes(db) );
77414   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
77415   zDb = db->aDb[iDb].zName;
77416   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
77417   pCol = &pNew->aCol[pNew->nCol-1];
77418   pDflt = pCol->pDflt;
77419   pTab = sqlite3FindTable(db, zTab, zDb);
77420   assert( pTab );
77421 
77422 #ifndef SQLITE_OMIT_AUTHORIZATION
77423   /* Invoke the authorization callback. */
77424   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
77425     return;
77426   }
77427 #endif
77428 
77429   /* If the default value for the new column was specified with a
77430   ** literal NULL, then set pDflt to 0. This simplifies checking
77431   ** for an SQL NULL default below.
77432   */
77433   if( pDflt && pDflt->op==TK_NULL ){
77434     pDflt = 0;
77435   }
77436 
77437   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
77438   ** If there is a NOT NULL constraint, then the default value for the
77439   ** column must not be NULL.
77440   */
77441   if( pCol->isPrimKey ){
77442     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
77443     return;
77444   }
77445   if( pNew->pIndex ){
77446     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
77447     return;
77448   }
77449   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
77450     sqlite3ErrorMsg(pParse,
77451         "Cannot add a REFERENCES column with non-NULL default value");
77452     return;
77453   }
77454   if( pCol->notNull && !pDflt ){
77455     sqlite3ErrorMsg(pParse,
77456         "Cannot add a NOT NULL column with default value NULL");
77457     return;
77458   }
77459 
77460   /* Ensure the default expression is something that sqlite3ValueFromExpr()
77461   ** can handle (i.e. not CURRENT_TIME etc.)
77462   */
77463   if( pDflt ){
77464     sqlite3_value *pVal;
77465     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
77466       db->mallocFailed = 1;
77467       return;
77468     }
77469     if( !pVal ){
77470       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
77471       return;
77472     }
77473     sqlite3ValueFree(pVal);
77474   }
77475 
77476   /* Modify the CREATE TABLE statement. */
77477   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
77478   if( zCol ){
77479     char *zEnd = &zCol[pColDef->n-1];
77480     int savedDbFlags = db->flags;
77481     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
77482       *zEnd-- = '\0';
77483     }
77484     db->flags |= SQLITE_PreferBuiltin;
77485     sqlite3NestedParse(pParse,
77486         "UPDATE \"%w\".%s SET "
77487           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
77488         "WHERE type = 'table' AND name = %Q",
77489       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
77490       zTab
77491     );
77492     sqlite3DbFree(db, zCol);
77493     db->flags = savedDbFlags;
77494   }
77495 
77496   /* If the default value of the new column is NULL, then set the file
77497   ** format to 2. If the default value of the new column is not NULL,
77498   ** the file format becomes 3.
77499   */
77500   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
77501 
77502   /* Reload the schema of the modified table. */
77503   reloadTableSchema(pParse, pTab, pTab->zName);
77504 }
77505 
77506 /*
77507 ** This function is called by the parser after the table-name in
77508 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
77509 ** pSrc is the full-name of the table being altered.
77510 **
77511 ** This routine makes a (partial) copy of the Table structure
77512 ** for the table being altered and sets Parse.pNewTable to point
77513 ** to it. Routines called by the parser as the column definition
77514 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
77515 ** the copy. The copy of the Table structure is deleted by tokenize.c
77516 ** after parsing is finished.
77517 **
77518 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
77519 ** coding the "ALTER TABLE ... ADD" statement.
77520 */
77521 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
77522   Table *pNew;
77523   Table *pTab;
77524   Vdbe *v;
77525   int iDb;
77526   int i;
77527   int nAlloc;
77528   sqlite3 *db = pParse->db;
77529 
77530   /* Look up the table being altered. */
77531   assert( pParse->pNewTable==0 );
77532   assert( sqlite3BtreeHoldsAllMutexes(db) );
77533   if( db->mallocFailed ) goto exit_begin_add_column;
77534   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
77535   if( !pTab ) goto exit_begin_add_column;
77536 
77537 #ifndef SQLITE_OMIT_VIRTUALTABLE
77538   if( IsVirtual(pTab) ){
77539     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
77540     goto exit_begin_add_column;
77541   }
77542 #endif
77543 
77544   /* Make sure this is not an attempt to ALTER a view. */
77545   if( pTab->pSelect ){
77546     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
77547     goto exit_begin_add_column;
77548   }
77549   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
77550     goto exit_begin_add_column;
77551   }
77552 
77553   assert( pTab->addColOffset>0 );
77554   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77555 
77556   /* Put a copy of the Table struct in Parse.pNewTable for the
77557   ** sqlite3AddColumn() function and friends to modify.  But modify
77558   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
77559   ** prefix, we insure that the name will not collide with an existing
77560   ** table because user table are not allowed to have the "sqlite_"
77561   ** prefix on their name.
77562   */
77563   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
77564   if( !pNew ) goto exit_begin_add_column;
77565   pParse->pNewTable = pNew;
77566   pNew->nRef = 1;
77567   pNew->nCol = pTab->nCol;
77568   assert( pNew->nCol>0 );
77569   nAlloc = (((pNew->nCol-1)/8)*8)+8;
77570   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
77571   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
77572   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
77573   if( !pNew->aCol || !pNew->zName ){
77574     db->mallocFailed = 1;
77575     goto exit_begin_add_column;
77576   }
77577   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
77578   for(i=0; i<pNew->nCol; i++){
77579     Column *pCol = &pNew->aCol[i];
77580     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
77581     pCol->zColl = 0;
77582     pCol->zType = 0;
77583     pCol->pDflt = 0;
77584     pCol->zDflt = 0;
77585   }
77586   pNew->pSchema = db->aDb[iDb].pSchema;
77587   pNew->addColOffset = pTab->addColOffset;
77588   pNew->nRef = 1;
77589 
77590   /* Begin a transaction and increment the schema cookie.  */
77591   sqlite3BeginWriteOperation(pParse, 0, iDb);
77592   v = sqlite3GetVdbe(pParse);
77593   if( !v ) goto exit_begin_add_column;
77594   sqlite3ChangeCookie(pParse, iDb);
77595 
77596 exit_begin_add_column:
77597   sqlite3SrcListDelete(db, pSrc);
77598   return;
77599 }
77600 #endif  /* SQLITE_ALTER_TABLE */
77601 
77602 /************** End of alter.c ***********************************************/
77603 /************** Begin file analyze.c *****************************************/
77604 /*
77605 ** 2005 July 8
77606 **
77607 ** The author disclaims copyright to this source code.  In place of
77608 ** a legal notice, here is a blessing:
77609 **
77610 **    May you do good and not evil.
77611 **    May you find forgiveness for yourself and forgive others.
77612 **    May you share freely, never taking more than you give.
77613 **
77614 *************************************************************************
77615 ** This file contains code associated with the ANALYZE command.
77616 */
77617 #ifndef SQLITE_OMIT_ANALYZE
77618 
77619 /*
77620 ** This routine generates code that opens the sqlite_stat1 table for
77621 ** writing with cursor iStatCur. If the library was built with the
77622 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
77623 ** opened for writing using cursor (iStatCur+1)
77624 **
77625 ** If the sqlite_stat1 tables does not previously exist, it is created.
77626 ** Similarly, if the sqlite_stat2 table does not exist and the library
77627 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
77628 **
77629 ** Argument zWhere may be a pointer to a buffer containing a table name,
77630 ** or it may be a NULL pointer. If it is not NULL, then all entries in
77631 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
77632 ** with the named table are deleted. If zWhere==0, then code is generated
77633 ** to delete all stat table entries.
77634 */
77635 static void openStatTable(
77636   Parse *pParse,          /* Parsing context */
77637   int iDb,                /* The database we are looking in */
77638   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
77639   const char *zWhere,     /* Delete entries for this table or index */
77640   const char *zWhereType  /* Either "tbl" or "idx" */
77641 ){
77642   static const struct {
77643     const char *zName;
77644     const char *zCols;
77645   } aTable[] = {
77646     { "sqlite_stat1", "tbl,idx,stat" },
77647 #ifdef SQLITE_ENABLE_STAT2
77648     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
77649 #endif
77650   };
77651 
77652   int aRoot[] = {0, 0};
77653   u8 aCreateTbl[] = {0, 0};
77654 
77655   int i;
77656   sqlite3 *db = pParse->db;
77657   Db *pDb;
77658   Vdbe *v = sqlite3GetVdbe(pParse);
77659   if( v==0 ) return;
77660   assert( sqlite3BtreeHoldsAllMutexes(db) );
77661   assert( sqlite3VdbeDb(v)==db );
77662   pDb = &db->aDb[iDb];
77663 
77664   for(i=0; i<ArraySize(aTable); i++){
77665     const char *zTab = aTable[i].zName;
77666     Table *pStat;
77667     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
77668       /* The sqlite_stat[12] table does not exist. Create it. Note that a
77669       ** side-effect of the CREATE TABLE statement is to leave the rootpage
77670       ** of the new table in register pParse->regRoot. This is important
77671       ** because the OpenWrite opcode below will be needing it. */
77672       sqlite3NestedParse(pParse,
77673           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
77674       );
77675       aRoot[i] = pParse->regRoot;
77676       aCreateTbl[i] = 1;
77677     }else{
77678       /* The table already exists. If zWhere is not NULL, delete all entries
77679       ** associated with the table zWhere. If zWhere is NULL, delete the
77680       ** entire contents of the table. */
77681       aRoot[i] = pStat->tnum;
77682       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
77683       if( zWhere ){
77684         sqlite3NestedParse(pParse,
77685            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
77686         );
77687       }else{
77688         /* The sqlite_stat[12] table already exists.  Delete all rows. */
77689         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
77690       }
77691     }
77692   }
77693 
77694   /* Open the sqlite_stat[12] tables for writing. */
77695   for(i=0; i<ArraySize(aTable); i++){
77696     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
77697     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
77698     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
77699   }
77700 }
77701 
77702 /*
77703 ** Generate code to do an analysis of all indices associated with
77704 ** a single table.
77705 */
77706 static void analyzeOneTable(
77707   Parse *pParse,   /* Parser context */
77708   Table *pTab,     /* Table whose indices are to be analyzed */
77709   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
77710   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
77711   int iMem         /* Available memory locations begin here */
77712 ){
77713   sqlite3 *db = pParse->db;    /* Database handle */
77714   Index *pIdx;                 /* An index to being analyzed */
77715   int iIdxCur;                 /* Cursor open on index being analyzed */
77716   Vdbe *v;                     /* The virtual machine being built up */
77717   int i;                       /* Loop counter */
77718   int topOfLoop;               /* The top of the loop */
77719   int endOfLoop;               /* The end of the loop */
77720   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
77721   int iDb;                     /* Index of database containing pTab */
77722   int regTabname = iMem++;     /* Register containing table name */
77723   int regIdxname = iMem++;     /* Register containing index name */
77724   int regSampleno = iMem++;    /* Register containing next sample number */
77725   int regCol = iMem++;         /* Content of a column analyzed table */
77726   int regRec = iMem++;         /* Register holding completed record */
77727   int regTemp = iMem++;        /* Temporary use register */
77728   int regRowid = iMem++;       /* Rowid for the inserted record */
77729 
77730 #ifdef SQLITE_ENABLE_STAT2
77731   int addr = 0;                /* Instruction address */
77732   int regTemp2 = iMem++;       /* Temporary use register */
77733   int regSamplerecno = iMem++; /* Index of next sample to record */
77734   int regRecno = iMem++;       /* Current sample index */
77735   int regLast = iMem++;        /* Index of last sample to record */
77736   int regFirst = iMem++;       /* Index of first sample to record */
77737 #endif
77738 
77739   v = sqlite3GetVdbe(pParse);
77740   if( v==0 || NEVER(pTab==0) ){
77741     return;
77742   }
77743   if( pTab->tnum==0 ){
77744     /* Do not gather statistics on views or virtual tables */
77745     return;
77746   }
77747   if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
77748     /* Do not gather statistics on system tables */
77749     return;
77750   }
77751   assert( sqlite3BtreeHoldsAllMutexes(db) );
77752   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77753   assert( iDb>=0 );
77754   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77755 #ifndef SQLITE_OMIT_AUTHORIZATION
77756   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
77757       db->aDb[iDb].zName ) ){
77758     return;
77759   }
77760 #endif
77761 
77762   /* Establish a read-lock on the table at the shared-cache level. */
77763   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
77764 
77765   iIdxCur = pParse->nTab++;
77766   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
77767   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77768     int nCol;
77769     KeyInfo *pKey;
77770 
77771     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
77772     nCol = pIdx->nColumn;
77773     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
77774     if( iMem+1+(nCol*2)>pParse->nMem ){
77775       pParse->nMem = iMem+1+(nCol*2);
77776     }
77777 
77778     /* Open a cursor to the index to be analyzed. */
77779     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
77780     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
77781         (char *)pKey, P4_KEYINFO_HANDOFF);
77782     VdbeComment((v, "%s", pIdx->zName));
77783 
77784     /* Populate the register containing the index name. */
77785     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
77786 
77787 #ifdef SQLITE_ENABLE_STAT2
77788 
77789     /* If this iteration of the loop is generating code to analyze the
77790     ** first index in the pTab->pIndex list, then register regLast has
77791     ** not been populated. In this case populate it now.  */
77792     if( pTab->pIndex==pIdx ){
77793       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
77794       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
77795       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
77796 
77797       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
77798       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
77799       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
77800       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
77801       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
77802       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
77803       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
77804       sqlite3VdbeJumpHere(v, addr);
77805     }
77806 
77807     /* Zero the regSampleno and regRecno registers. */
77808     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
77809     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
77810     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
77811 #endif
77812 
77813     /* The block of memory cells initialized here is used as follows.
77814     **
77815     **    iMem:
77816     **        The total number of rows in the table.
77817     **
77818     **    iMem+1 .. iMem+nCol:
77819     **        Number of distinct entries in index considering the
77820     **        left-most N columns only, where N is between 1 and nCol,
77821     **        inclusive.
77822     **
77823     **    iMem+nCol+1 .. Mem+2*nCol:
77824     **        Previous value of indexed columns, from left to right.
77825     **
77826     ** Cells iMem through iMem+nCol are initialized to 0. The others are
77827     ** initialized to contain an SQL NULL.
77828     */
77829     for(i=0; i<=nCol; i++){
77830       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
77831     }
77832     for(i=0; i<nCol; i++){
77833       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
77834     }
77835 
77836     /* Start the analysis loop. This loop runs through all the entries in
77837     ** the index b-tree.  */
77838     endOfLoop = sqlite3VdbeMakeLabel(v);
77839     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
77840     topOfLoop = sqlite3VdbeCurrentAddr(v);
77841     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
77842 
77843     for(i=0; i<nCol; i++){
77844       CollSeq *pColl;
77845       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
77846       if( i==0 ){
77847 #ifdef SQLITE_ENABLE_STAT2
77848         /* Check if the record that cursor iIdxCur points to contains a
77849         ** value that should be stored in the sqlite_stat2 table. If so,
77850         ** store it.  */
77851         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
77852         assert( regTabname+1==regIdxname
77853              && regTabname+2==regSampleno
77854              && regTabname+3==regCol
77855         );
77856         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
77857         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
77858         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
77859         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
77860 
77861         /* Calculate new values for regSamplerecno and regSampleno.
77862         **
77863         **   sampleno = sampleno + 1
77864         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
77865         */
77866         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
77867         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
77868         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
77869         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
77870         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
77871         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
77872         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
77873 
77874         sqlite3VdbeJumpHere(v, ne);
77875         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
77876 #endif
77877 
77878         /* Always record the very first row */
77879         sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
77880       }
77881       assert( pIdx->azColl!=0 );
77882       assert( pIdx->azColl[i]!=0 );
77883       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
77884       sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
77885                        (char*)pColl, P4_COLLSEQ);
77886       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
77887     }
77888     if( db->mallocFailed ){
77889       /* If a malloc failure has occurred, then the result of the expression
77890       ** passed as the second argument to the call to sqlite3VdbeJumpHere()
77891       ** below may be negative. Which causes an assert() to fail (or an
77892       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
77893       return;
77894     }
77895     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
77896     for(i=0; i<nCol; i++){
77897       int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol*2);
77898       if( i==0 ){
77899         sqlite3VdbeJumpHere(v, addr2-1);  /* Set jump dest for the OP_IfNot */
77900       }
77901       sqlite3VdbeJumpHere(v, addr2);      /* Set jump dest for the OP_Ne */
77902       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
77903       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
77904     }
77905 
77906     /* End of the analysis loop. */
77907     sqlite3VdbeResolveLabel(v, endOfLoop);
77908     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
77909     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
77910 
77911     /* Store the results in sqlite_stat1.
77912     **
77913     ** The result is a single row of the sqlite_stat1 table.  The first
77914     ** two columns are the names of the table and index.  The third column
77915     ** is a string composed of a list of integer statistics about the
77916     ** index.  The first integer in the list is the total number of entries
77917     ** in the index.  There is one additional integer in the list for each
77918     ** column of the table.  This additional integer is a guess of how many
77919     ** rows of the table the index will select.  If D is the count of distinct
77920     ** values and K is the total number of rows, then the integer is computed
77921     ** as:
77922     **
77923     **        I = (K+D-1)/D
77924     **
77925     ** If K==0 then no entry is made into the sqlite_stat1 table.
77926     ** If K>0 then it is always the case the D>0 so division by zero
77927     ** is never possible.
77928     */
77929     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
77930     if( jZeroRows<0 ){
77931       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
77932     }
77933     for(i=0; i<nCol; i++){
77934       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
77935       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
77936       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
77937       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
77938       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
77939       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
77940       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
77941     }
77942     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
77943     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
77944     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
77945     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77946   }
77947 
77948   /* If the table has no indices, create a single sqlite_stat1 entry
77949   ** containing NULL as the index name and the row count as the content.
77950   */
77951   if( pTab->pIndex==0 ){
77952     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
77953     VdbeComment((v, "%s", pTab->zName));
77954     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
77955     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
77956     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
77957   }else{
77958     sqlite3VdbeJumpHere(v, jZeroRows);
77959     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
77960   }
77961   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
77962   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
77963   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
77964   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
77965   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
77966   if( pParse->nMem<regRec ) pParse->nMem = regRec;
77967   sqlite3VdbeJumpHere(v, jZeroRows);
77968 }
77969 
77970 /*
77971 ** Generate code that will cause the most recent index analysis to
77972 ** be loaded into internal hash tables where is can be used.
77973 */
77974 static void loadAnalysis(Parse *pParse, int iDb){
77975   Vdbe *v = sqlite3GetVdbe(pParse);
77976   if( v ){
77977     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
77978   }
77979 }
77980 
77981 /*
77982 ** Generate code that will do an analysis of an entire database
77983 */
77984 static void analyzeDatabase(Parse *pParse, int iDb){
77985   sqlite3 *db = pParse->db;
77986   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
77987   HashElem *k;
77988   int iStatCur;
77989   int iMem;
77990 
77991   sqlite3BeginWriteOperation(pParse, 0, iDb);
77992   iStatCur = pParse->nTab;
77993   pParse->nTab += 2;
77994   openStatTable(pParse, iDb, iStatCur, 0, 0);
77995   iMem = pParse->nMem+1;
77996   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
77997   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
77998     Table *pTab = (Table*)sqliteHashData(k);
77999     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
78000   }
78001   loadAnalysis(pParse, iDb);
78002 }
78003 
78004 /*
78005 ** Generate code that will do an analysis of a single table in
78006 ** a database.  If pOnlyIdx is not NULL then it is a single index
78007 ** in pTab that should be analyzed.
78008 */
78009 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
78010   int iDb;
78011   int iStatCur;
78012 
78013   assert( pTab!=0 );
78014   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78015   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78016   sqlite3BeginWriteOperation(pParse, 0, iDb);
78017   iStatCur = pParse->nTab;
78018   pParse->nTab += 2;
78019   if( pOnlyIdx ){
78020     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
78021   }else{
78022     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
78023   }
78024   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
78025   loadAnalysis(pParse, iDb);
78026 }
78027 
78028 /*
78029 ** Generate code for the ANALYZE command.  The parser calls this routine
78030 ** when it recognizes an ANALYZE command.
78031 **
78032 **        ANALYZE                            -- 1
78033 **        ANALYZE  <database>                -- 2
78034 **        ANALYZE  ?<database>.?<tablename>  -- 3
78035 **
78036 ** Form 1 causes all indices in all attached databases to be analyzed.
78037 ** Form 2 analyzes all indices the single database named.
78038 ** Form 3 analyzes all indices associated with the named table.
78039 */
78040 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
78041   sqlite3 *db = pParse->db;
78042   int iDb;
78043   int i;
78044   char *z, *zDb;
78045   Table *pTab;
78046   Index *pIdx;
78047   Token *pTableName;
78048 
78049   /* Read the database schema. If an error occurs, leave an error message
78050   ** and code in pParse and return NULL. */
78051   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78052   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
78053     return;
78054   }
78055 
78056   assert( pName2!=0 || pName1==0 );
78057   if( pName1==0 ){
78058     /* Form 1:  Analyze everything */
78059     for(i=0; i<db->nDb; i++){
78060       if( i==1 ) continue;  /* Do not analyze the TEMP database */
78061       analyzeDatabase(pParse, i);
78062     }
78063   }else if( pName2->n==0 ){
78064     /* Form 2:  Analyze the database or table named */
78065     iDb = sqlite3FindDb(db, pName1);
78066     if( iDb>=0 ){
78067       analyzeDatabase(pParse, iDb);
78068     }else{
78069       z = sqlite3NameFromToken(db, pName1);
78070       if( z ){
78071         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
78072           analyzeTable(pParse, pIdx->pTable, pIdx);
78073         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
78074           analyzeTable(pParse, pTab, 0);
78075         }
78076         sqlite3DbFree(db, z);
78077       }
78078     }
78079   }else{
78080     /* Form 3: Analyze the fully qualified table name */
78081     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
78082     if( iDb>=0 ){
78083       zDb = db->aDb[iDb].zName;
78084       z = sqlite3NameFromToken(db, pTableName);
78085       if( z ){
78086         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
78087           analyzeTable(pParse, pIdx->pTable, pIdx);
78088         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
78089           analyzeTable(pParse, pTab, 0);
78090         }
78091         sqlite3DbFree(db, z);
78092       }
78093     }
78094   }
78095 }
78096 
78097 /*
78098 ** Used to pass information from the analyzer reader through to the
78099 ** callback routine.
78100 */
78101 typedef struct analysisInfo analysisInfo;
78102 struct analysisInfo {
78103   sqlite3 *db;
78104   const char *zDatabase;
78105 };
78106 
78107 /*
78108 ** This callback is invoked once for each index when reading the
78109 ** sqlite_stat1 table.
78110 **
78111 **     argv[0] = name of the table
78112 **     argv[1] = name of the index (might be NULL)
78113 **     argv[2] = results of analysis - on integer for each column
78114 **
78115 ** Entries for which argv[1]==NULL simply record the number of rows in
78116 ** the table.
78117 */
78118 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
78119   analysisInfo *pInfo = (analysisInfo*)pData;
78120   Index *pIndex;
78121   Table *pTable;
78122   int i, c, n;
78123   unsigned int v;
78124   const char *z;
78125 
78126   assert( argc==3 );
78127   UNUSED_PARAMETER2(NotUsed, argc);
78128 
78129   if( argv==0 || argv[0]==0 || argv[2]==0 ){
78130     return 0;
78131   }
78132   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
78133   if( pTable==0 ){
78134     return 0;
78135   }
78136   if( argv[1] ){
78137     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
78138   }else{
78139     pIndex = 0;
78140   }
78141   n = pIndex ? pIndex->nColumn : 0;
78142   z = argv[2];
78143   for(i=0; *z && i<=n; i++){
78144     v = 0;
78145     while( (c=z[0])>='0' && c<='9' ){
78146       v = v*10 + c - '0';
78147       z++;
78148     }
78149     if( i==0 ) pTable->nRowEst = v;
78150     if( pIndex==0 ) break;
78151     pIndex->aiRowEst[i] = v;
78152     if( *z==' ' ) z++;
78153     if( memcmp(z, "unordered", 10)==0 ){
78154       pIndex->bUnordered = 1;
78155       break;
78156     }
78157   }
78158   return 0;
78159 }
78160 
78161 /*
78162 ** If the Index.aSample variable is not NULL, delete the aSample[] array
78163 ** and its contents.
78164 */
78165 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
78166 #ifdef SQLITE_ENABLE_STAT2
78167   if( pIdx->aSample ){
78168     int j;
78169     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
78170       IndexSample *p = &pIdx->aSample[j];
78171       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
78172         sqlite3DbFree(db, p->u.z);
78173       }
78174     }
78175     sqlite3DbFree(db, pIdx->aSample);
78176   }
78177 #else
78178   UNUSED_PARAMETER(db);
78179   UNUSED_PARAMETER(pIdx);
78180 #endif
78181 }
78182 
78183 /*
78184 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
78185 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
78186 ** arrays. The contents of sqlite_stat2 are used to populate the
78187 ** Index.aSample[] arrays.
78188 **
78189 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
78190 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
78191 ** during compilation and the sqlite_stat2 table is present, no data is
78192 ** read from it.
78193 **
78194 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
78195 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
78196 ** returned. However, in this case, data is read from the sqlite_stat1
78197 ** table (if it is present) before returning.
78198 **
78199 ** If an OOM error occurs, this function always sets db->mallocFailed.
78200 ** This means if the caller does not care about other errors, the return
78201 ** code may be ignored.
78202 */
78203 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
78204   analysisInfo sInfo;
78205   HashElem *i;
78206   char *zSql;
78207   int rc;
78208 
78209   assert( iDb>=0 && iDb<db->nDb );
78210   assert( db->aDb[iDb].pBt!=0 );
78211 
78212   /* Clear any prior statistics */
78213   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
78214   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
78215     Index *pIdx = sqliteHashData(i);
78216     sqlite3DefaultRowEst(pIdx);
78217     sqlite3DeleteIndexSamples(db, pIdx);
78218     pIdx->aSample = 0;
78219   }
78220 
78221   /* Check to make sure the sqlite_stat1 table exists */
78222   sInfo.db = db;
78223   sInfo.zDatabase = db->aDb[iDb].zName;
78224   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
78225     return SQLITE_ERROR;
78226   }
78227 
78228   /* Load new statistics out of the sqlite_stat1 table */
78229   zSql = sqlite3MPrintf(db,
78230       "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
78231   if( zSql==0 ){
78232     rc = SQLITE_NOMEM;
78233   }else{
78234     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
78235     sqlite3DbFree(db, zSql);
78236   }
78237 
78238 
78239   /* Load the statistics from the sqlite_stat2 table. */
78240 #ifdef SQLITE_ENABLE_STAT2
78241   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
78242     rc = SQLITE_ERROR;
78243   }
78244   if( rc==SQLITE_OK ){
78245     sqlite3_stmt *pStmt = 0;
78246 
78247     zSql = sqlite3MPrintf(db,
78248         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
78249     if( !zSql ){
78250       rc = SQLITE_NOMEM;
78251     }else{
78252       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
78253       sqlite3DbFree(db, zSql);
78254     }
78255 
78256     if( rc==SQLITE_OK ){
78257       while( sqlite3_step(pStmt)==SQLITE_ROW ){
78258         char *zIndex;   /* Index name */
78259         Index *pIdx;    /* Pointer to the index object */
78260 
78261         zIndex = (char *)sqlite3_column_text(pStmt, 0);
78262         pIdx = zIndex ? sqlite3FindIndex(db, zIndex, sInfo.zDatabase) : 0;
78263         if( pIdx ){
78264           int iSample = sqlite3_column_int(pStmt, 1);
78265           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
78266             int eType = sqlite3_column_type(pStmt, 2);
78267 
78268             if( pIdx->aSample==0 ){
78269               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
78270               pIdx->aSample = (IndexSample *)sqlite3DbMallocRaw(0, sz);
78271               if( pIdx->aSample==0 ){
78272                 db->mallocFailed = 1;
78273                 break;
78274               }
78275 	      memset(pIdx->aSample, 0, sz);
78276             }
78277 
78278             assert( pIdx->aSample );
78279             {
78280               IndexSample *pSample = &pIdx->aSample[iSample];
78281               pSample->eType = (u8)eType;
78282               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
78283                 pSample->u.r = sqlite3_column_double(pStmt, 2);
78284               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
78285                 const char *z = (const char *)(
78286                     (eType==SQLITE_BLOB) ?
78287                     sqlite3_column_blob(pStmt, 2):
78288                     sqlite3_column_text(pStmt, 2)
78289                 );
78290                 int n = sqlite3_column_bytes(pStmt, 2);
78291                 if( n>24 ){
78292                   n = 24;
78293                 }
78294                 pSample->nByte = (u8)n;
78295                 if( n < 1){
78296                   pSample->u.z = 0;
78297                 }else{
78298                   pSample->u.z = sqlite3DbStrNDup(0, z, n);
78299                   if( pSample->u.z==0 ){
78300                     db->mallocFailed = 1;
78301                     break;
78302                   }
78303                 }
78304               }
78305             }
78306           }
78307         }
78308       }
78309       rc = sqlite3_finalize(pStmt);
78310     }
78311   }
78312 #endif
78313 
78314   if( rc==SQLITE_NOMEM ){
78315     db->mallocFailed = 1;
78316   }
78317   return rc;
78318 }
78319 
78320 
78321 #endif /* SQLITE_OMIT_ANALYZE */
78322 
78323 /************** End of analyze.c *********************************************/
78324 /************** Begin file attach.c ******************************************/
78325 /*
78326 ** 2003 April 6
78327 **
78328 ** The author disclaims copyright to this source code.  In place of
78329 ** a legal notice, here is a blessing:
78330 **
78331 **    May you do good and not evil.
78332 **    May you find forgiveness for yourself and forgive others.
78333 **    May you share freely, never taking more than you give.
78334 **
78335 *************************************************************************
78336 ** This file contains code used to implement the ATTACH and DETACH commands.
78337 */
78338 
78339 #ifndef SQLITE_OMIT_ATTACH
78340 /*
78341 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
78342 ** is slightly different from resolving a normal SQL expression, because simple
78343 ** identifiers are treated as strings, not possible column names or aliases.
78344 **
78345 ** i.e. if the parser sees:
78346 **
78347 **     ATTACH DATABASE abc AS def
78348 **
78349 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
78350 ** looking for columns of the same name.
78351 **
78352 ** This only applies to the root node of pExpr, so the statement:
78353 **
78354 **     ATTACH DATABASE abc||def AS 'db2'
78355 **
78356 ** will fail because neither abc or def can be resolved.
78357 */
78358 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
78359 {
78360   int rc = SQLITE_OK;
78361   if( pExpr ){
78362     if( pExpr->op!=TK_ID ){
78363       rc = sqlite3ResolveExprNames(pName, pExpr);
78364       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
78365         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
78366         return SQLITE_ERROR;
78367       }
78368     }else{
78369       pExpr->op = TK_STRING;
78370     }
78371   }
78372   return rc;
78373 }
78374 
78375 /*
78376 ** An SQL user-function registered to do the work of an ATTACH statement. The
78377 ** three arguments to the function come directly from an attach statement:
78378 **
78379 **     ATTACH DATABASE x AS y KEY z
78380 **
78381 **     SELECT sqlite_attach(x, y, z)
78382 **
78383 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
78384 ** third argument.
78385 */
78386 static void attachFunc(
78387   sqlite3_context *context,
78388   int NotUsed,
78389   sqlite3_value **argv
78390 ){
78391   int i;
78392   int rc = 0;
78393   sqlite3 *db = sqlite3_context_db_handle(context);
78394   const char *zName;
78395   const char *zFile;
78396   char *zPath = 0;
78397   char *zErr = 0;
78398   unsigned int flags;
78399   Db *aNew;
78400   char *zErrDyn = 0;
78401   sqlite3_vfs *pVfs;
78402 
78403   UNUSED_PARAMETER(NotUsed);
78404 
78405   zFile = (const char *)sqlite3_value_text(argv[0]);
78406   zName = (const char *)sqlite3_value_text(argv[1]);
78407   if( zFile==0 ) zFile = "";
78408   if( zName==0 ) zName = "";
78409 
78410   /* Check for the following errors:
78411   **
78412   **     * Too many attached databases,
78413   **     * Transaction currently open
78414   **     * Specified database name already being used.
78415   */
78416   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
78417     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
78418       db->aLimit[SQLITE_LIMIT_ATTACHED]
78419     );
78420     goto attach_error;
78421   }
78422   if( !db->autoCommit ){
78423     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
78424     goto attach_error;
78425   }
78426   for(i=0; i<db->nDb; i++){
78427     char *z = db->aDb[i].zName;
78428     assert( z && zName );
78429     if( sqlite3StrICmp(z, zName)==0 ){
78430       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
78431       goto attach_error;
78432     }
78433   }
78434 
78435   /* Allocate the new entry in the db->aDb[] array and initialise the schema
78436   ** hash tables.
78437   */
78438   if( db->aDb==db->aDbStatic ){
78439     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
78440     if( aNew==0 ) return;
78441     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
78442   }else{
78443     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
78444     if( aNew==0 ) return;
78445   }
78446   db->aDb = aNew;
78447   aNew = &db->aDb[db->nDb];
78448   memset(aNew, 0, sizeof(*aNew));
78449 
78450   /* Open the database file. If the btree is successfully opened, use
78451   ** it to obtain the database schema. At this point the schema may
78452   ** or may not be initialised.
78453   */
78454   flags = db->openFlags;
78455   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
78456   if( rc!=SQLITE_OK ){
78457     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
78458     sqlite3_result_error(context, zErr, -1);
78459     sqlite3_free(zErr);
78460     return;
78461   }
78462   assert( pVfs );
78463   flags |= SQLITE_OPEN_MAIN_DB;
78464   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
78465   sqlite3_free( zPath );
78466   db->nDb++;
78467   if( rc==SQLITE_CONSTRAINT ){
78468     rc = SQLITE_ERROR;
78469     zErrDyn = sqlite3MPrintf(db, "database is already attached");
78470   }else if( rc==SQLITE_OK ){
78471     Pager *pPager;
78472     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
78473     if( !aNew->pSchema ){
78474       rc = SQLITE_NOMEM;
78475     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
78476       zErrDyn = sqlite3MPrintf(db,
78477         "attached databases must use the same text encoding as main database");
78478       rc = SQLITE_ERROR;
78479     }
78480     pPager = sqlite3BtreePager(aNew->pBt);
78481     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
78482     sqlite3BtreeSecureDelete(aNew->pBt,
78483                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
78484   }
78485   aNew->safety_level = 3;
78486   aNew->zName = sqlite3DbStrDup(db, zName);
78487   if( rc==SQLITE_OK && aNew->zName==0 ){
78488     rc = SQLITE_NOMEM;
78489   }
78490 
78491 
78492 #ifdef SQLITE_HAS_CODEC
78493   if( rc==SQLITE_OK ){
78494     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
78495     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
78496     int nKey;
78497     char *zKey;
78498     int t = sqlite3_value_type(argv[2]);
78499     switch( t ){
78500       case SQLITE_INTEGER:
78501       case SQLITE_FLOAT:
78502         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
78503         rc = SQLITE_ERROR;
78504         break;
78505 
78506       case SQLITE_TEXT:
78507       case SQLITE_BLOB:
78508         nKey = sqlite3_value_bytes(argv[2]);
78509         zKey = (char *)sqlite3_value_blob(argv[2]);
78510         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
78511         break;
78512 
78513       case SQLITE_NULL:
78514         /* No key specified.  Use the key from the main database */
78515         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
78516         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
78517           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
78518         }
78519         break;
78520     }
78521   }
78522 #endif
78523 
78524   /* If the file was opened successfully, read the schema for the new database.
78525   ** If this fails, or if opening the file failed, then close the file and
78526   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
78527   ** we found it.
78528   */
78529   if( rc==SQLITE_OK ){
78530     sqlite3BtreeEnterAll(db);
78531     rc = sqlite3Init(db, &zErrDyn);
78532     sqlite3BtreeLeaveAll(db);
78533   }
78534   if( rc ){
78535     int iDb = db->nDb - 1;
78536     assert( iDb>=2 );
78537     if( db->aDb[iDb].pBt ){
78538       sqlite3BtreeClose(db->aDb[iDb].pBt);
78539       db->aDb[iDb].pBt = 0;
78540       db->aDb[iDb].pSchema = 0;
78541     }
78542     sqlite3ResetInternalSchema(db, -1);
78543     db->nDb = iDb;
78544     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78545       db->mallocFailed = 1;
78546       sqlite3DbFree(db, zErrDyn);
78547       zErrDyn = sqlite3MPrintf(db, "out of memory");
78548     }else if( zErrDyn==0 ){
78549       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
78550     }
78551     goto attach_error;
78552   }
78553 
78554   return;
78555 
78556 attach_error:
78557   /* Return an error if we get here */
78558   if( zErrDyn ){
78559     sqlite3_result_error(context, zErrDyn, -1);
78560     sqlite3DbFree(db, zErrDyn);
78561   }
78562   if( rc ) sqlite3_result_error_code(context, rc);
78563 }
78564 
78565 /*
78566 ** An SQL user-function registered to do the work of an DETACH statement. The
78567 ** three arguments to the function come directly from a detach statement:
78568 **
78569 **     DETACH DATABASE x
78570 **
78571 **     SELECT sqlite_detach(x)
78572 */
78573 static void detachFunc(
78574   sqlite3_context *context,
78575   int NotUsed,
78576   sqlite3_value **argv
78577 ){
78578   const char *zName = (const char *)sqlite3_value_text(argv[0]);
78579   sqlite3 *db = sqlite3_context_db_handle(context);
78580   int i;
78581   Db *pDb = 0;
78582   char zErr[128];
78583 
78584   UNUSED_PARAMETER(NotUsed);
78585 
78586   if( zName==0 ) zName = "";
78587   for(i=0; i<db->nDb; i++){
78588     pDb = &db->aDb[i];
78589     if( pDb->pBt==0 ) continue;
78590     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
78591   }
78592 
78593   if( i>=db->nDb ){
78594     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
78595     goto detach_error;
78596   }
78597   if( i<2 ){
78598     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
78599     goto detach_error;
78600   }
78601   if( !db->autoCommit ){
78602     sqlite3_snprintf(sizeof(zErr), zErr,
78603                      "cannot DETACH database within transaction");
78604     goto detach_error;
78605   }
78606   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
78607     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
78608     goto detach_error;
78609   }
78610 
78611   sqlite3BtreeClose(pDb->pBt);
78612   pDb->pBt = 0;
78613   pDb->pSchema = 0;
78614   sqlite3ResetInternalSchema(db, -1);
78615   return;
78616 
78617 detach_error:
78618   sqlite3_result_error(context, zErr, -1);
78619 }
78620 
78621 /*
78622 ** This procedure generates VDBE code for a single invocation of either the
78623 ** sqlite_detach() or sqlite_attach() SQL user functions.
78624 */
78625 static void codeAttach(
78626   Parse *pParse,       /* The parser context */
78627   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
78628   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
78629   Expr *pAuthArg,      /* Expression to pass to authorization callback */
78630   Expr *pFilename,     /* Name of database file */
78631   Expr *pDbname,       /* Name of the database to use internally */
78632   Expr *pKey           /* Database key for encryption extension */
78633 ){
78634   int rc;
78635   NameContext sName;
78636   Vdbe *v;
78637   sqlite3* db = pParse->db;
78638   int regArgs;
78639 
78640   memset(&sName, 0, sizeof(NameContext));
78641   sName.pParse = pParse;
78642 
78643   if(
78644       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
78645       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
78646       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
78647   ){
78648     pParse->nErr++;
78649     goto attach_end;
78650   }
78651 
78652 #ifndef SQLITE_OMIT_AUTHORIZATION
78653   if( pAuthArg ){
78654     char *zAuthArg;
78655     if( pAuthArg->op==TK_STRING ){
78656       zAuthArg = pAuthArg->u.zToken;
78657     }else{
78658       zAuthArg = 0;
78659     }
78660     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
78661     if(rc!=SQLITE_OK ){
78662       goto attach_end;
78663     }
78664   }
78665 #endif /* SQLITE_OMIT_AUTHORIZATION */
78666 
78667 
78668   v = sqlite3GetVdbe(pParse);
78669   regArgs = sqlite3GetTempRange(pParse, 4);
78670   sqlite3ExprCode(pParse, pFilename, regArgs);
78671   sqlite3ExprCode(pParse, pDbname, regArgs+1);
78672   sqlite3ExprCode(pParse, pKey, regArgs+2);
78673 
78674   assert( v || db->mallocFailed );
78675   if( v ){
78676     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
78677     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
78678     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
78679     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
78680 
78681     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
78682     ** statement only). For DETACH, set it to false (expire all existing
78683     ** statements).
78684     */
78685     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
78686   }
78687 
78688 attach_end:
78689   sqlite3ExprDelete(db, pFilename);
78690   sqlite3ExprDelete(db, pDbname);
78691   sqlite3ExprDelete(db, pKey);
78692 }
78693 
78694 /*
78695 ** Called by the parser to compile a DETACH statement.
78696 **
78697 **     DETACH pDbname
78698 */
78699 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
78700   static const FuncDef detach_func = {
78701     1,                /* nArg */
78702     SQLITE_UTF8,      /* iPrefEnc */
78703     0,                /* flags */
78704     0,                /* pUserData */
78705     0,                /* pNext */
78706     detachFunc,       /* xFunc */
78707     0,                /* xStep */
78708     0,                /* xFinalize */
78709     "sqlite_detach",  /* zName */
78710     0,                /* pHash */
78711     0                 /* pDestructor */
78712   };
78713   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
78714 }
78715 
78716 /*
78717 ** Called by the parser to compile an ATTACH statement.
78718 **
78719 **     ATTACH p AS pDbname KEY pKey
78720 */
78721 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
78722   static const FuncDef attach_func = {
78723     3,                /* nArg */
78724     SQLITE_UTF8,      /* iPrefEnc */
78725     0,                /* flags */
78726     0,                /* pUserData */
78727     0,                /* pNext */
78728     attachFunc,       /* xFunc */
78729     0,                /* xStep */
78730     0,                /* xFinalize */
78731     "sqlite_attach",  /* zName */
78732     0,                /* pHash */
78733     0                 /* pDestructor */
78734   };
78735   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
78736 }
78737 #endif /* SQLITE_OMIT_ATTACH */
78738 
78739 /*
78740 ** Initialize a DbFixer structure.  This routine must be called prior
78741 ** to passing the structure to one of the sqliteFixAAAA() routines below.
78742 **
78743 ** The return value indicates whether or not fixation is required.  TRUE
78744 ** means we do need to fix the database references, FALSE means we do not.
78745 */
78746 SQLITE_PRIVATE int sqlite3FixInit(
78747   DbFixer *pFix,      /* The fixer to be initialized */
78748   Parse *pParse,      /* Error messages will be written here */
78749   int iDb,            /* This is the database that must be used */
78750   const char *zType,  /* "view", "trigger", or "index" */
78751   const Token *pName  /* Name of the view, trigger, or index */
78752 ){
78753   sqlite3 *db;
78754 
78755   if( NEVER(iDb<0) || iDb==1 ) return 0;
78756   db = pParse->db;
78757   assert( db->nDb>iDb );
78758   pFix->pParse = pParse;
78759   pFix->zDb = db->aDb[iDb].zName;
78760   pFix->zType = zType;
78761   pFix->pName = pName;
78762   return 1;
78763 }
78764 
78765 /*
78766 ** The following set of routines walk through the parse tree and assign
78767 ** a specific database to all table references where the database name
78768 ** was left unspecified in the original SQL statement.  The pFix structure
78769 ** must have been initialized by a prior call to sqlite3FixInit().
78770 **
78771 ** These routines are used to make sure that an index, trigger, or
78772 ** view in one database does not refer to objects in a different database.
78773 ** (Exception: indices, triggers, and views in the TEMP database are
78774 ** allowed to refer to anything.)  If a reference is explicitly made
78775 ** to an object in a different database, an error message is added to
78776 ** pParse->zErrMsg and these routines return non-zero.  If everything
78777 ** checks out, these routines return 0.
78778 */
78779 SQLITE_PRIVATE int sqlite3FixSrcList(
78780   DbFixer *pFix,       /* Context of the fixation */
78781   SrcList *pList       /* The Source list to check and modify */
78782 ){
78783   int i;
78784   const char *zDb;
78785   struct SrcList_item *pItem;
78786 
78787   if( NEVER(pList==0) ) return 0;
78788   zDb = pFix->zDb;
78789   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
78790     if( pItem->zDatabase==0 ){
78791       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
78792     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
78793       sqlite3ErrorMsg(pFix->pParse,
78794          "%s %T cannot reference objects in database %s",
78795          pFix->zType, pFix->pName, pItem->zDatabase);
78796       return 1;
78797     }
78798 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
78799     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
78800     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
78801 #endif
78802   }
78803   return 0;
78804 }
78805 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
78806 SQLITE_PRIVATE int sqlite3FixSelect(
78807   DbFixer *pFix,       /* Context of the fixation */
78808   Select *pSelect      /* The SELECT statement to be fixed to one database */
78809 ){
78810   while( pSelect ){
78811     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
78812       return 1;
78813     }
78814     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
78815       return 1;
78816     }
78817     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
78818       return 1;
78819     }
78820     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
78821       return 1;
78822     }
78823     pSelect = pSelect->pPrior;
78824   }
78825   return 0;
78826 }
78827 SQLITE_PRIVATE int sqlite3FixExpr(
78828   DbFixer *pFix,     /* Context of the fixation */
78829   Expr *pExpr        /* The expression to be fixed to one database */
78830 ){
78831   while( pExpr ){
78832     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
78833     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78834       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
78835     }else{
78836       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
78837     }
78838     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
78839       return 1;
78840     }
78841     pExpr = pExpr->pLeft;
78842   }
78843   return 0;
78844 }
78845 SQLITE_PRIVATE int sqlite3FixExprList(
78846   DbFixer *pFix,     /* Context of the fixation */
78847   ExprList *pList    /* The expression to be fixed to one database */
78848 ){
78849   int i;
78850   struct ExprList_item *pItem;
78851   if( pList==0 ) return 0;
78852   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
78853     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
78854       return 1;
78855     }
78856   }
78857   return 0;
78858 }
78859 #endif
78860 
78861 #ifndef SQLITE_OMIT_TRIGGER
78862 SQLITE_PRIVATE int sqlite3FixTriggerStep(
78863   DbFixer *pFix,     /* Context of the fixation */
78864   TriggerStep *pStep /* The trigger step be fixed to one database */
78865 ){
78866   while( pStep ){
78867     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
78868       return 1;
78869     }
78870     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
78871       return 1;
78872     }
78873     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
78874       return 1;
78875     }
78876     pStep = pStep->pNext;
78877   }
78878   return 0;
78879 }
78880 #endif
78881 
78882 /************** End of attach.c **********************************************/
78883 /************** Begin file auth.c ********************************************/
78884 /*
78885 ** 2003 January 11
78886 **
78887 ** The author disclaims copyright to this source code.  In place of
78888 ** a legal notice, here is a blessing:
78889 **
78890 **    May you do good and not evil.
78891 **    May you find forgiveness for yourself and forgive others.
78892 **    May you share freely, never taking more than you give.
78893 **
78894 *************************************************************************
78895 ** This file contains code used to implement the sqlite3_set_authorizer()
78896 ** API.  This facility is an optional feature of the library.  Embedded
78897 ** systems that do not need this facility may omit it by recompiling
78898 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
78899 */
78900 
78901 /*
78902 ** All of the code in this file may be omitted by defining a single
78903 ** macro.
78904 */
78905 #ifndef SQLITE_OMIT_AUTHORIZATION
78906 
78907 /*
78908 ** Set or clear the access authorization function.
78909 **
78910 ** The access authorization function is be called during the compilation
78911 ** phase to verify that the user has read and/or write access permission on
78912 ** various fields of the database.  The first argument to the auth function
78913 ** is a copy of the 3rd argument to this routine.  The second argument
78914 ** to the auth function is one of these constants:
78915 **
78916 **       SQLITE_CREATE_INDEX
78917 **       SQLITE_CREATE_TABLE
78918 **       SQLITE_CREATE_TEMP_INDEX
78919 **       SQLITE_CREATE_TEMP_TABLE
78920 **       SQLITE_CREATE_TEMP_TRIGGER
78921 **       SQLITE_CREATE_TEMP_VIEW
78922 **       SQLITE_CREATE_TRIGGER
78923 **       SQLITE_CREATE_VIEW
78924 **       SQLITE_DELETE
78925 **       SQLITE_DROP_INDEX
78926 **       SQLITE_DROP_TABLE
78927 **       SQLITE_DROP_TEMP_INDEX
78928 **       SQLITE_DROP_TEMP_TABLE
78929 **       SQLITE_DROP_TEMP_TRIGGER
78930 **       SQLITE_DROP_TEMP_VIEW
78931 **       SQLITE_DROP_TRIGGER
78932 **       SQLITE_DROP_VIEW
78933 **       SQLITE_INSERT
78934 **       SQLITE_PRAGMA
78935 **       SQLITE_READ
78936 **       SQLITE_SELECT
78937 **       SQLITE_TRANSACTION
78938 **       SQLITE_UPDATE
78939 **
78940 ** The third and fourth arguments to the auth function are the name of
78941 ** the table and the column that are being accessed.  The auth function
78942 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
78943 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
78944 ** means that the SQL statement will never-run - the sqlite3_exec() call
78945 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
78946 ** should run but attempts to read the specified column will return NULL
78947 ** and attempts to write the column will be ignored.
78948 **
78949 ** Setting the auth function to NULL disables this hook.  The default
78950 ** setting of the auth function is NULL.
78951 */
78952 SQLITE_API int sqlite3_set_authorizer(
78953   sqlite3 *db,
78954   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
78955   void *pArg
78956 ){
78957   sqlite3_mutex_enter(db->mutex);
78958   db->xAuth = xAuth;
78959   db->pAuthArg = pArg;
78960   sqlite3ExpirePreparedStatements(db);
78961   sqlite3_mutex_leave(db->mutex);
78962   return SQLITE_OK;
78963 }
78964 
78965 /*
78966 ** Write an error message into pParse->zErrMsg that explains that the
78967 ** user-supplied authorization function returned an illegal value.
78968 */
78969 static void sqliteAuthBadReturnCode(Parse *pParse){
78970   sqlite3ErrorMsg(pParse, "authorizer malfunction");
78971   pParse->rc = SQLITE_ERROR;
78972 }
78973 
78974 /*
78975 ** Invoke the authorization callback for permission to read column zCol from
78976 ** table zTab in database zDb. This function assumes that an authorization
78977 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
78978 **
78979 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
78980 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
78981 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
78982 */
78983 SQLITE_PRIVATE int sqlite3AuthReadCol(
78984   Parse *pParse,                  /* The parser context */
78985   const char *zTab,               /* Table name */
78986   const char *zCol,               /* Column name */
78987   int iDb                         /* Index of containing database. */
78988 ){
78989   sqlite3 *db = pParse->db;       /* Database handle */
78990   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
78991   int rc;                         /* Auth callback return code */
78992 
78993   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
78994   if( rc==SQLITE_DENY ){
78995     if( db->nDb>2 || iDb!=0 ){
78996       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
78997     }else{
78998       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
78999     }
79000     pParse->rc = SQLITE_AUTH;
79001   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
79002     sqliteAuthBadReturnCode(pParse);
79003   }
79004   return rc;
79005 }
79006 
79007 /*
79008 ** The pExpr should be a TK_COLUMN expression.  The table referred to
79009 ** is in pTabList or else it is the NEW or OLD table of a trigger.
79010 ** Check to see if it is OK to read this particular column.
79011 **
79012 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
79013 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
79014 ** then generate an error.
79015 */
79016 SQLITE_PRIVATE void sqlite3AuthRead(
79017   Parse *pParse,        /* The parser context */
79018   Expr *pExpr,          /* The expression to check authorization on */
79019   Schema *pSchema,      /* The schema of the expression */
79020   SrcList *pTabList     /* All table that pExpr might refer to */
79021 ){
79022   sqlite3 *db = pParse->db;
79023   Table *pTab = 0;      /* The table being read */
79024   const char *zCol;     /* Name of the column of the table */
79025   int iSrc;             /* Index in pTabList->a[] of table being read */
79026   int iDb;              /* The index of the database the expression refers to */
79027   int iCol;             /* Index of column in table */
79028 
79029   if( db->xAuth==0 ) return;
79030   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
79031   if( iDb<0 ){
79032     /* An attempt to read a column out of a subquery or other
79033     ** temporary table. */
79034     return;
79035   }
79036 
79037   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
79038   if( pExpr->op==TK_TRIGGER ){
79039     pTab = pParse->pTriggerTab;
79040   }else{
79041     assert( pTabList );
79042     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
79043       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
79044         pTab = pTabList->a[iSrc].pTab;
79045         break;
79046       }
79047     }
79048   }
79049   iCol = pExpr->iColumn;
79050   if( NEVER(pTab==0) ) return;
79051 
79052   if( iCol>=0 ){
79053     assert( iCol<pTab->nCol );
79054     zCol = pTab->aCol[iCol].zName;
79055   }else if( pTab->iPKey>=0 ){
79056     assert( pTab->iPKey<pTab->nCol );
79057     zCol = pTab->aCol[pTab->iPKey].zName;
79058   }else{
79059     zCol = "ROWID";
79060   }
79061   assert( iDb>=0 && iDb<db->nDb );
79062   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
79063     pExpr->op = TK_NULL;
79064   }
79065 }
79066 
79067 /*
79068 ** Do an authorization check using the code and arguments given.  Return
79069 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
79070 ** is returned, then the error count and error message in pParse are
79071 ** modified appropriately.
79072 */
79073 SQLITE_PRIVATE int sqlite3AuthCheck(
79074   Parse *pParse,
79075   int code,
79076   const char *zArg1,
79077   const char *zArg2,
79078   const char *zArg3
79079 ){
79080   sqlite3 *db = pParse->db;
79081   int rc;
79082 
79083   /* Don't do any authorization checks if the database is initialising
79084   ** or if the parser is being invoked from within sqlite3_declare_vtab.
79085   */
79086   if( db->init.busy || IN_DECLARE_VTAB ){
79087     return SQLITE_OK;
79088   }
79089 
79090   if( db->xAuth==0 ){
79091     return SQLITE_OK;
79092   }
79093   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
79094   if( rc==SQLITE_DENY ){
79095     sqlite3ErrorMsg(pParse, "not authorized");
79096     pParse->rc = SQLITE_AUTH;
79097   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
79098     rc = SQLITE_DENY;
79099     sqliteAuthBadReturnCode(pParse);
79100   }
79101   return rc;
79102 }
79103 
79104 /*
79105 ** Push an authorization context.  After this routine is called, the
79106 ** zArg3 argument to authorization callbacks will be zContext until
79107 ** popped.  Or if pParse==0, this routine is a no-op.
79108 */
79109 SQLITE_PRIVATE void sqlite3AuthContextPush(
79110   Parse *pParse,
79111   AuthContext *pContext,
79112   const char *zContext
79113 ){
79114   assert( pParse );
79115   pContext->pParse = pParse;
79116   pContext->zAuthContext = pParse->zAuthContext;
79117   pParse->zAuthContext = zContext;
79118 }
79119 
79120 /*
79121 ** Pop an authorization context that was previously pushed
79122 ** by sqlite3AuthContextPush
79123 */
79124 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
79125   if( pContext->pParse ){
79126     pContext->pParse->zAuthContext = pContext->zAuthContext;
79127     pContext->pParse = 0;
79128   }
79129 }
79130 
79131 #endif /* SQLITE_OMIT_AUTHORIZATION */
79132 
79133 /************** End of auth.c ************************************************/
79134 /************** Begin file build.c *******************************************/
79135 /*
79136 ** 2001 September 15
79137 **
79138 ** The author disclaims copyright to this source code.  In place of
79139 ** a legal notice, here is a blessing:
79140 **
79141 **    May you do good and not evil.
79142 **    May you find forgiveness for yourself and forgive others.
79143 **    May you share freely, never taking more than you give.
79144 **
79145 *************************************************************************
79146 ** This file contains C code routines that are called by the SQLite parser
79147 ** when syntax rules are reduced.  The routines in this file handle the
79148 ** following kinds of SQL syntax:
79149 **
79150 **     CREATE TABLE
79151 **     DROP TABLE
79152 **     CREATE INDEX
79153 **     DROP INDEX
79154 **     creating ID lists
79155 **     BEGIN TRANSACTION
79156 **     COMMIT
79157 **     ROLLBACK
79158 */
79159 
79160 /*
79161 ** This routine is called when a new SQL statement is beginning to
79162 ** be parsed.  Initialize the pParse structure as needed.
79163 */
79164 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
79165   pParse->explain = (u8)explainFlag;
79166   pParse->nVar = 0;
79167 }
79168 
79169 #ifndef SQLITE_OMIT_SHARED_CACHE
79170 /*
79171 ** The TableLock structure is only used by the sqlite3TableLock() and
79172 ** codeTableLocks() functions.
79173 */
79174 struct TableLock {
79175   int iDb;             /* The database containing the table to be locked */
79176   int iTab;            /* The root page of the table to be locked */
79177   u8 isWriteLock;      /* True for write lock.  False for a read lock */
79178   const char *zName;   /* Name of the table */
79179 };
79180 
79181 /*
79182 ** Record the fact that we want to lock a table at run-time.
79183 **
79184 ** The table to be locked has root page iTab and is found in database iDb.
79185 ** A read or a write lock can be taken depending on isWritelock.
79186 **
79187 ** This routine just records the fact that the lock is desired.  The
79188 ** code to make the lock occur is generated by a later call to
79189 ** codeTableLocks() which occurs during sqlite3FinishCoding().
79190 */
79191 SQLITE_PRIVATE void sqlite3TableLock(
79192   Parse *pParse,     /* Parsing context */
79193   int iDb,           /* Index of the database containing the table to lock */
79194   int iTab,          /* Root page number of the table to be locked */
79195   u8 isWriteLock,    /* True for a write lock */
79196   const char *zName  /* Name of the table to be locked */
79197 ){
79198   Parse *pToplevel = sqlite3ParseToplevel(pParse);
79199   int i;
79200   int nBytes;
79201   TableLock *p;
79202   assert( iDb>=0 );
79203 
79204   for(i=0; i<pToplevel->nTableLock; i++){
79205     p = &pToplevel->aTableLock[i];
79206     if( p->iDb==iDb && p->iTab==iTab ){
79207       p->isWriteLock = (p->isWriteLock || isWriteLock);
79208       return;
79209     }
79210   }
79211 
79212   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
79213   pToplevel->aTableLock =
79214       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
79215   if( pToplevel->aTableLock ){
79216     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
79217     p->iDb = iDb;
79218     p->iTab = iTab;
79219     p->isWriteLock = isWriteLock;
79220     p->zName = zName;
79221   }else{
79222     pToplevel->nTableLock = 0;
79223     pToplevel->db->mallocFailed = 1;
79224   }
79225 }
79226 
79227 /*
79228 ** Code an OP_TableLock instruction for each table locked by the
79229 ** statement (configured by calls to sqlite3TableLock()).
79230 */
79231 static void codeTableLocks(Parse *pParse){
79232   int i;
79233   Vdbe *pVdbe;
79234 
79235   pVdbe = sqlite3GetVdbe(pParse);
79236   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
79237 
79238   for(i=0; i<pParse->nTableLock; i++){
79239     TableLock *p = &pParse->aTableLock[i];
79240     int p1 = p->iDb;
79241     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
79242                       p->zName, P4_STATIC);
79243   }
79244 }
79245 #else
79246   #define codeTableLocks(x)
79247 #endif
79248 
79249 /*
79250 ** This routine is called after a single SQL statement has been
79251 ** parsed and a VDBE program to execute that statement has been
79252 ** prepared.  This routine puts the finishing touches on the
79253 ** VDBE program and resets the pParse structure for the next
79254 ** parse.
79255 **
79256 ** Note that if an error occurred, it might be the case that
79257 ** no VDBE code was generated.
79258 */
79259 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
79260   sqlite3 *db;
79261   Vdbe *v;
79262 
79263   db = pParse->db;
79264   if( db->mallocFailed ) return;
79265   if( pParse->nested ) return;
79266   if( pParse->nErr ) return;
79267 
79268   /* Begin by generating some termination code at the end of the
79269   ** vdbe program
79270   */
79271   v = sqlite3GetVdbe(pParse);
79272   assert( !pParse->isMultiWrite
79273        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
79274   if( v ){
79275     sqlite3VdbeAddOp0(v, OP_Halt);
79276 
79277     /* The cookie mask contains one bit for each database file open.
79278     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
79279     ** set for each database that is used.  Generate code to start a
79280     ** transaction on each used database and to verify the schema cookie
79281     ** on each used database.
79282     */
79283     if( pParse->cookieGoto>0 ){
79284       yDbMask mask;
79285       int iDb;
79286       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
79287       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
79288         if( (mask & pParse->cookieMask)==0 ) continue;
79289         sqlite3VdbeUsesBtree(v, iDb);
79290         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
79291         if( db->init.busy==0 ){
79292           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79293           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
79294                             iDb, pParse->cookieValue[iDb],
79295                             db->aDb[iDb].pSchema->iGeneration);
79296         }
79297       }
79298 #ifndef SQLITE_OMIT_VIRTUALTABLE
79299       {
79300         int i;
79301         for(i=0; i<pParse->nVtabLock; i++){
79302           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
79303           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
79304         }
79305         pParse->nVtabLock = 0;
79306       }
79307 #endif
79308 
79309       /* Once all the cookies have been verified and transactions opened,
79310       ** obtain the required table-locks. This is a no-op unless the
79311       ** shared-cache feature is enabled.
79312       */
79313       codeTableLocks(pParse);
79314 
79315       /* Initialize any AUTOINCREMENT data structures required.
79316       */
79317       sqlite3AutoincrementBegin(pParse);
79318 
79319       /* Finally, jump back to the beginning of the executable code. */
79320       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
79321     }
79322   }
79323 
79324 
79325   /* Get the VDBE program ready for execution
79326   */
79327   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
79328 #ifdef SQLITE_DEBUG
79329     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
79330     sqlite3VdbeTrace(v, trace);
79331 #endif
79332     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
79333     /* A minimum of one cursor is required if autoincrement is used
79334     *  See ticket [a696379c1f08866] */
79335     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
79336     sqlite3VdbeMakeReady(v, pParse);
79337     pParse->rc = SQLITE_DONE;
79338     pParse->colNamesSet = 0;
79339   }else{
79340     pParse->rc = SQLITE_ERROR;
79341   }
79342   pParse->nTab = 0;
79343   pParse->nMem = 0;
79344   pParse->nSet = 0;
79345   pParse->nVar = 0;
79346   pParse->cookieMask = 0;
79347   pParse->cookieGoto = 0;
79348 }
79349 
79350 /*
79351 ** Run the parser and code generator recursively in order to generate
79352 ** code for the SQL statement given onto the end of the pParse context
79353 ** currently under construction.  When the parser is run recursively
79354 ** this way, the final OP_Halt is not appended and other initialization
79355 ** and finalization steps are omitted because those are handling by the
79356 ** outermost parser.
79357 **
79358 ** Not everything is nestable.  This facility is designed to permit
79359 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
79360 ** care if you decide to try to use this routine for some other purposes.
79361 */
79362 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
79363   va_list ap;
79364   char *zSql;
79365   char *zErrMsg = 0;
79366   sqlite3 *db = pParse->db;
79367 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
79368   char saveBuf[SAVE_SZ];
79369 
79370   if( pParse->nErr ) return;
79371   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
79372   va_start(ap, zFormat);
79373   zSql = sqlite3VMPrintf(db, zFormat, ap);
79374   va_end(ap);
79375   if( zSql==0 ){
79376     return;   /* A malloc must have failed */
79377   }
79378   pParse->nested++;
79379   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
79380   memset(&pParse->nVar, 0, SAVE_SZ);
79381   sqlite3RunParser(pParse, zSql, &zErrMsg);
79382   sqlite3DbFree(db, zErrMsg);
79383   sqlite3DbFree(db, zSql);
79384   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
79385   pParse->nested--;
79386 }
79387 
79388 /*
79389 ** Locate the in-memory structure that describes a particular database
79390 ** table given the name of that table and (optionally) the name of the
79391 ** database containing the table.  Return NULL if not found.
79392 **
79393 ** If zDatabase is 0, all databases are searched for the table and the
79394 ** first matching table is returned.  (No checking for duplicate table
79395 ** names is done.)  The search order is TEMP first, then MAIN, then any
79396 ** auxiliary databases added using the ATTACH command.
79397 **
79398 ** See also sqlite3LocateTable().
79399 */
79400 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
79401   Table *p = 0;
79402   int i;
79403   int nName;
79404   assert( zName!=0 );
79405   nName = sqlite3Strlen30(zName);
79406   /* All mutexes are required for schema access.  Make sure we hold them. */
79407   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
79408   for(i=OMIT_TEMPDB; i<db->nDb; i++){
79409     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
79410     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
79411     assert( sqlite3SchemaMutexHeld(db, j, 0) );
79412     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
79413     if( p ) break;
79414   }
79415   return p;
79416 }
79417 
79418 /*
79419 ** Locate the in-memory structure that describes a particular database
79420 ** table given the name of that table and (optionally) the name of the
79421 ** database containing the table.  Return NULL if not found.  Also leave an
79422 ** error message in pParse->zErrMsg.
79423 **
79424 ** The difference between this routine and sqlite3FindTable() is that this
79425 ** routine leaves an error message in pParse->zErrMsg where
79426 ** sqlite3FindTable() does not.
79427 */
79428 SQLITE_PRIVATE Table *sqlite3LocateTable(
79429   Parse *pParse,         /* context in which to report errors */
79430   int isView,            /* True if looking for a VIEW rather than a TABLE */
79431   const char *zName,     /* Name of the table we are looking for */
79432   const char *zDbase     /* Name of the database.  Might be NULL */
79433 ){
79434   Table *p;
79435 
79436   /* Read the database schema. If an error occurs, leave an error message
79437   ** and code in pParse and return NULL. */
79438   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79439     return 0;
79440   }
79441 
79442   p = sqlite3FindTable(pParse->db, zName, zDbase);
79443   if( p==0 ){
79444     const char *zMsg = isView ? "no such view" : "no such table";
79445     if( zDbase ){
79446       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
79447     }else{
79448       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
79449     }
79450     pParse->checkSchema = 1;
79451   }
79452   return p;
79453 }
79454 
79455 /*
79456 ** Locate the in-memory structure that describes
79457 ** a particular index given the name of that index
79458 ** and the name of the database that contains the index.
79459 ** Return NULL if not found.
79460 **
79461 ** If zDatabase is 0, all databases are searched for the
79462 ** table and the first matching index is returned.  (No checking
79463 ** for duplicate index names is done.)  The search order is
79464 ** TEMP first, then MAIN, then any auxiliary databases added
79465 ** using the ATTACH command.
79466 */
79467 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
79468   Index *p = 0;
79469   int i;
79470   int nName = sqlite3Strlen30(zName);
79471   /* All mutexes are required for schema access.  Make sure we hold them. */
79472   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
79473   for(i=OMIT_TEMPDB; i<db->nDb; i++){
79474     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
79475     Schema *pSchema = db->aDb[j].pSchema;
79476     assert( pSchema );
79477     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
79478     assert( sqlite3SchemaMutexHeld(db, j, 0) );
79479     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
79480     if( p ) break;
79481   }
79482   return p;
79483 }
79484 
79485 /*
79486 ** Reclaim the memory used by an index
79487 */
79488 static void freeIndex(sqlite3 *db, Index *p){
79489 #ifndef SQLITE_OMIT_ANALYZE
79490   sqlite3DeleteIndexSamples(db, p);
79491 #endif
79492   sqlite3DbFree(db, p->zColAff);
79493   sqlite3DbFree(db, p);
79494 }
79495 
79496 /*
79497 ** For the index called zIdxName which is found in the database iDb,
79498 ** unlike that index from its Table then remove the index from
79499 ** the index hash table and free all memory structures associated
79500 ** with the index.
79501 */
79502 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
79503   Index *pIndex;
79504   int len;
79505   Hash *pHash;
79506 
79507   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79508   pHash = &db->aDb[iDb].pSchema->idxHash;
79509   len = sqlite3Strlen30(zIdxName);
79510   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
79511   if( ALWAYS(pIndex) ){
79512     if( pIndex->pTable->pIndex==pIndex ){
79513       pIndex->pTable->pIndex = pIndex->pNext;
79514     }else{
79515       Index *p;
79516       /* Justification of ALWAYS();  The index must be on the list of
79517       ** indices. */
79518       p = pIndex->pTable->pIndex;
79519       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
79520       if( ALWAYS(p && p->pNext==pIndex) ){
79521         p->pNext = pIndex->pNext;
79522       }
79523     }
79524     freeIndex(db, pIndex);
79525   }
79526   db->flags |= SQLITE_InternChanges;
79527 }
79528 
79529 /*
79530 ** Erase all schema information from the in-memory hash tables of
79531 ** a single database.  This routine is called to reclaim memory
79532 ** before the database closes.  It is also called during a rollback
79533 ** if there were schema changes during the transaction or if a
79534 ** schema-cookie mismatch occurs.
79535 **
79536 ** If iDb<0 then reset the internal schema tables for all database
79537 ** files.  If iDb>=0 then reset the internal schema for only the
79538 ** single file indicated.
79539 */
79540 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
79541   int i, j;
79542   assert( iDb<db->nDb );
79543 
79544   if( iDb>=0 ){
79545     /* Case 1:  Reset the single schema identified by iDb */
79546     Db *pDb = &db->aDb[iDb];
79547     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79548     assert( pDb->pSchema!=0 );
79549     sqlite3SchemaClear(pDb->pSchema);
79550 
79551     /* If any database other than TEMP is reset, then also reset TEMP
79552     ** since TEMP might be holding triggers that reference tables in the
79553     ** other database.
79554     */
79555     if( iDb!=1 ){
79556       pDb = &db->aDb[1];
79557       assert( pDb->pSchema!=0 );
79558       sqlite3SchemaClear(pDb->pSchema);
79559     }
79560     return;
79561   }
79562   /* Case 2 (from here to the end): Reset all schemas for all attached
79563   ** databases. */
79564   assert( iDb<0 );
79565   sqlite3BtreeEnterAll(db);
79566   for(i=0; i<db->nDb; i++){
79567     Db *pDb = &db->aDb[i];
79568     if( pDb->pSchema ){
79569       sqlite3SchemaClear(pDb->pSchema);
79570     }
79571   }
79572   db->flags &= ~SQLITE_InternChanges;
79573   sqlite3VtabUnlockList(db);
79574   sqlite3BtreeLeaveAll(db);
79575 
79576   /* If one or more of the auxiliary database files has been closed,
79577   ** then remove them from the auxiliary database list.  We take the
79578   ** opportunity to do this here since we have just deleted all of the
79579   ** schema hash tables and therefore do not have to make any changes
79580   ** to any of those tables.
79581   */
79582   for(i=j=2; i<db->nDb; i++){
79583     struct Db *pDb = &db->aDb[i];
79584     if( pDb->pBt==0 ){
79585       sqlite3DbFree(db, pDb->zName);
79586       pDb->zName = 0;
79587       continue;
79588     }
79589     if( j<i ){
79590       db->aDb[j] = db->aDb[i];
79591     }
79592     j++;
79593   }
79594   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
79595   db->nDb = j;
79596   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
79597     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
79598     sqlite3DbFree(db, db->aDb);
79599     db->aDb = db->aDbStatic;
79600   }
79601 }
79602 
79603 /*
79604 ** This routine is called when a commit occurs.
79605 */
79606 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
79607   db->flags &= ~SQLITE_InternChanges;
79608 }
79609 
79610 /*
79611 ** Delete memory allocated for the column names of a table or view (the
79612 ** Table.aCol[] array).
79613 */
79614 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
79615   int i;
79616   Column *pCol;
79617   assert( pTable!=0 );
79618   if( (pCol = pTable->aCol)!=0 ){
79619     for(i=0; i<pTable->nCol; i++, pCol++){
79620       sqlite3DbFree(db, pCol->zName);
79621       sqlite3ExprDelete(db, pCol->pDflt);
79622       sqlite3DbFree(db, pCol->zDflt);
79623       sqlite3DbFree(db, pCol->zType);
79624       sqlite3DbFree(db, pCol->zColl);
79625     }
79626     sqlite3DbFree(db, pTable->aCol);
79627   }
79628 }
79629 
79630 /*
79631 ** Remove the memory data structures associated with the given
79632 ** Table.  No changes are made to disk by this routine.
79633 **
79634 ** This routine just deletes the data structure.  It does not unlink
79635 ** the table data structure from the hash table.  But it does destroy
79636 ** memory structures of the indices and foreign keys associated with
79637 ** the table.
79638 */
79639 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
79640   Index *pIndex, *pNext;
79641 
79642   assert( !pTable || pTable->nRef>0 );
79643 
79644   /* Do not delete the table until the reference count reaches zero. */
79645   if( !pTable ) return;
79646   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
79647 
79648   /* Delete all indices associated with this table. */
79649   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
79650     pNext = pIndex->pNext;
79651     assert( pIndex->pSchema==pTable->pSchema );
79652     if( !db || db->pnBytesFreed==0 ){
79653       char *zName = pIndex->zName;
79654       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
79655 	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
79656       );
79657       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
79658       assert( pOld==pIndex || pOld==0 );
79659     }
79660     freeIndex(db, pIndex);
79661   }
79662 
79663   /* Delete any foreign keys attached to this table. */
79664   sqlite3FkDelete(db, pTable);
79665 
79666   /* Delete the Table structure itself.
79667   */
79668   sqliteDeleteColumnNames(db, pTable);
79669   sqlite3DbFree(db, pTable->zName);
79670   sqlite3DbFree(db, pTable->zColAff);
79671   sqlite3SelectDelete(db, pTable->pSelect);
79672 #ifndef SQLITE_OMIT_CHECK
79673   sqlite3ExprDelete(db, pTable->pCheck);
79674 #endif
79675 #ifndef SQLITE_OMIT_VIRTUALTABLE
79676   sqlite3VtabClear(db, pTable);
79677 #endif
79678   sqlite3DbFree(db, pTable);
79679 }
79680 
79681 /*
79682 ** Unlink the given table from the hash tables and the delete the
79683 ** table structure with all its indices and foreign keys.
79684 */
79685 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
79686   Table *p;
79687   Db *pDb;
79688 
79689   assert( db!=0 );
79690   assert( iDb>=0 && iDb<db->nDb );
79691   assert( zTabName );
79692   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79693   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
79694   pDb = &db->aDb[iDb];
79695   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
79696                         sqlite3Strlen30(zTabName),0);
79697   sqlite3DeleteTable(db, p);
79698   db->flags |= SQLITE_InternChanges;
79699 }
79700 
79701 /*
79702 ** Given a token, return a string that consists of the text of that
79703 ** token.  Space to hold the returned string
79704 ** is obtained from sqliteMalloc() and must be freed by the calling
79705 ** function.
79706 **
79707 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
79708 ** surround the body of the token are removed.
79709 **
79710 ** Tokens are often just pointers into the original SQL text and so
79711 ** are not \000 terminated and are not persistent.  The returned string
79712 ** is \000 terminated and is persistent.
79713 */
79714 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
79715   char *zName;
79716   if( pName ){
79717     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
79718     sqlite3Dequote(zName);
79719   }else{
79720     zName = 0;
79721   }
79722   return zName;
79723 }
79724 
79725 /*
79726 ** Open the sqlite_master table stored in database number iDb for
79727 ** writing. The table is opened using cursor 0.
79728 */
79729 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
79730   Vdbe *v = sqlite3GetVdbe(p);
79731   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
79732   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
79733   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
79734   if( p->nTab==0 ){
79735     p->nTab = 1;
79736   }
79737 }
79738 
79739 /*
79740 ** Parameter zName points to a nul-terminated buffer containing the name
79741 ** of a database ("main", "temp" or the name of an attached db). This
79742 ** function returns the index of the named database in db->aDb[], or
79743 ** -1 if the named db cannot be found.
79744 */
79745 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
79746   int i = -1;         /* Database number */
79747   if( zName ){
79748     Db *pDb;
79749     int n = sqlite3Strlen30(zName);
79750     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
79751       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
79752           0==sqlite3StrICmp(pDb->zName, zName) ){
79753         break;
79754       }
79755     }
79756   }
79757   return i;
79758 }
79759 
79760 /*
79761 ** The token *pName contains the name of a database (either "main" or
79762 ** "temp" or the name of an attached db). This routine returns the
79763 ** index of the named database in db->aDb[], or -1 if the named db
79764 ** does not exist.
79765 */
79766 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
79767   int i;                               /* Database number */
79768   char *zName;                         /* Name we are searching for */
79769   zName = sqlite3NameFromToken(db, pName);
79770   i = sqlite3FindDbName(db, zName);
79771   sqlite3DbFree(db, zName);
79772   return i;
79773 }
79774 
79775 /* The table or view or trigger name is passed to this routine via tokens
79776 ** pName1 and pName2. If the table name was fully qualified, for example:
79777 **
79778 ** CREATE TABLE xxx.yyy (...);
79779 **
79780 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
79781 ** the table name is not fully qualified, i.e.:
79782 **
79783 ** CREATE TABLE yyy(...);
79784 **
79785 ** Then pName1 is set to "yyy" and pName2 is "".
79786 **
79787 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
79788 ** pName2) that stores the unqualified table name.  The index of the
79789 ** database "xxx" is returned.
79790 */
79791 SQLITE_PRIVATE int sqlite3TwoPartName(
79792   Parse *pParse,      /* Parsing and code generating context */
79793   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
79794   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
79795   Token **pUnqual     /* Write the unqualified object name here */
79796 ){
79797   int iDb;                    /* Database holding the object */
79798   sqlite3 *db = pParse->db;
79799 
79800   if( ALWAYS(pName2!=0) && pName2->n>0 ){
79801     if( db->init.busy ) {
79802       sqlite3ErrorMsg(pParse, "corrupt database");
79803       pParse->nErr++;
79804       return -1;
79805     }
79806     *pUnqual = pName2;
79807     iDb = sqlite3FindDb(db, pName1);
79808     if( iDb<0 ){
79809       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
79810       pParse->nErr++;
79811       return -1;
79812     }
79813   }else{
79814     assert( db->init.iDb==0 || db->init.busy );
79815     iDb = db->init.iDb;
79816     *pUnqual = pName1;
79817   }
79818   return iDb;
79819 }
79820 
79821 /*
79822 ** This routine is used to check if the UTF-8 string zName is a legal
79823 ** unqualified name for a new schema object (table, index, view or
79824 ** trigger). All names are legal except those that begin with the string
79825 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
79826 ** is reserved for internal use.
79827 */
79828 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
79829   if( !pParse->db->init.busy && pParse->nested==0
79830           && (pParse->db->flags & SQLITE_WriteSchema)==0
79831           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
79832     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
79833     return SQLITE_ERROR;
79834   }
79835   return SQLITE_OK;
79836 }
79837 
79838 /*
79839 ** Begin constructing a new table representation in memory.  This is
79840 ** the first of several action routines that get called in response
79841 ** to a CREATE TABLE statement.  In particular, this routine is called
79842 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
79843 ** flag is true if the table should be stored in the auxiliary database
79844 ** file instead of in the main database file.  This is normally the case
79845 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
79846 ** CREATE and TABLE.
79847 **
79848 ** The new table record is initialized and put in pParse->pNewTable.
79849 ** As more of the CREATE TABLE statement is parsed, additional action
79850 ** routines will be called to add more information to this record.
79851 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
79852 ** is called to complete the construction of the new table record.
79853 */
79854 SQLITE_PRIVATE void sqlite3StartTable(
79855   Parse *pParse,   /* Parser context */
79856   Token *pName1,   /* First part of the name of the table or view */
79857   Token *pName2,   /* Second part of the name of the table or view */
79858   int isTemp,      /* True if this is a TEMP table */
79859   int isView,      /* True if this is a VIEW */
79860   int isVirtual,   /* True if this is a VIRTUAL table */
79861   int noErr        /* Do nothing if table already exists */
79862 ){
79863   Table *pTable;
79864   char *zName = 0; /* The name of the new table */
79865   sqlite3 *db = pParse->db;
79866   Vdbe *v;
79867   int iDb;         /* Database number to create the table in */
79868   Token *pName;    /* Unqualified name of the table to create */
79869 
79870   /* The table or view name to create is passed to this routine via tokens
79871   ** pName1 and pName2. If the table name was fully qualified, for example:
79872   **
79873   ** CREATE TABLE xxx.yyy (...);
79874   **
79875   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
79876   ** the table name is not fully qualified, i.e.:
79877   **
79878   ** CREATE TABLE yyy(...);
79879   **
79880   ** Then pName1 is set to "yyy" and pName2 is "".
79881   **
79882   ** The call below sets the pName pointer to point at the token (pName1 or
79883   ** pName2) that stores the unqualified table name. The variable iDb is
79884   ** set to the index of the database that the table or view is to be
79885   ** created in.
79886   */
79887   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
79888   if( iDb<0 ) return;
79889   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
79890     /* If creating a temp table, the name may not be qualified. Unless
79891     ** the database name is "temp" anyway.  */
79892     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
79893     return;
79894   }
79895   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
79896 
79897   pParse->sNameToken = *pName;
79898   zName = sqlite3NameFromToken(db, pName);
79899   if( zName==0 ) return;
79900   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
79901     goto begin_table_error;
79902   }
79903   if( db->init.iDb==1 ) isTemp = 1;
79904 #ifndef SQLITE_OMIT_AUTHORIZATION
79905   assert( (isTemp & 1)==isTemp );
79906   {
79907     int code;
79908     char *zDb = db->aDb[iDb].zName;
79909     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
79910       goto begin_table_error;
79911     }
79912     if( isView ){
79913       if( !OMIT_TEMPDB && isTemp ){
79914         code = SQLITE_CREATE_TEMP_VIEW;
79915       }else{
79916         code = SQLITE_CREATE_VIEW;
79917       }
79918     }else{
79919       if( !OMIT_TEMPDB && isTemp ){
79920         code = SQLITE_CREATE_TEMP_TABLE;
79921       }else{
79922         code = SQLITE_CREATE_TABLE;
79923       }
79924     }
79925     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
79926       goto begin_table_error;
79927     }
79928   }
79929 #endif
79930 
79931   /* Make sure the new table name does not collide with an existing
79932   ** index or table name in the same database.  Issue an error message if
79933   ** it does. The exception is if the statement being parsed was passed
79934   ** to an sqlite3_declare_vtab() call. In that case only the column names
79935   ** and types will be used, so there is no need to test for namespace
79936   ** collisions.
79937   */
79938   if( !IN_DECLARE_VTAB ){
79939     char *zDb = db->aDb[iDb].zName;
79940     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
79941       goto begin_table_error;
79942     }
79943     pTable = sqlite3FindTable(db, zName, zDb);
79944     if( pTable ){
79945       if( !noErr ){
79946         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
79947       }else{
79948         assert( !db->init.busy );
79949         sqlite3CodeVerifySchema(pParse, iDb);
79950       }
79951       goto begin_table_error;
79952     }
79953     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
79954       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
79955       goto begin_table_error;
79956     }
79957   }
79958 
79959   pTable = sqlite3DbMallocZero(db, sizeof(Table));
79960   if( pTable==0 ){
79961     db->mallocFailed = 1;
79962     pParse->rc = SQLITE_NOMEM;
79963     pParse->nErr++;
79964     goto begin_table_error;
79965   }
79966   pTable->zName = zName;
79967   pTable->iPKey = -1;
79968   pTable->pSchema = db->aDb[iDb].pSchema;
79969   pTable->nRef = 1;
79970   pTable->nRowEst = 1000000;
79971   assert( pParse->pNewTable==0 );
79972   pParse->pNewTable = pTable;
79973 
79974   /* If this is the magic sqlite_sequence table used by autoincrement,
79975   ** then record a pointer to this table in the main database structure
79976   ** so that INSERT can find the table easily.
79977   */
79978 #ifndef SQLITE_OMIT_AUTOINCREMENT
79979   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
79980     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79981     pTable->pSchema->pSeqTab = pTable;
79982   }
79983 #endif
79984 
79985   /* Begin generating the code that will insert the table record into
79986   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
79987   ** and allocate the record number for the table entry now.  Before any
79988   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
79989   ** indices to be created and the table record must come before the
79990   ** indices.  Hence, the record number for the table must be allocated
79991   ** now.
79992   */
79993   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
79994     int j1;
79995     int fileFormat;
79996     int reg1, reg2, reg3;
79997     sqlite3BeginWriteOperation(pParse, 0, iDb);
79998 
79999 #ifndef SQLITE_OMIT_VIRTUALTABLE
80000     if( isVirtual ){
80001       sqlite3VdbeAddOp0(v, OP_VBegin);
80002     }
80003 #endif
80004 
80005     /* If the file format and encoding in the database have not been set,
80006     ** set them now.
80007     */
80008     reg1 = pParse->regRowid = ++pParse->nMem;
80009     reg2 = pParse->regRoot = ++pParse->nMem;
80010     reg3 = ++pParse->nMem;
80011     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
80012     sqlite3VdbeUsesBtree(v, iDb);
80013     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
80014     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
80015                   1 : SQLITE_MAX_FILE_FORMAT;
80016     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
80017     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
80018     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
80019     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
80020     sqlite3VdbeJumpHere(v, j1);
80021 
80022     /* This just creates a place-holder record in the sqlite_master table.
80023     ** The record created does not contain anything yet.  It will be replaced
80024     ** by the real entry in code generated at sqlite3EndTable().
80025     **
80026     ** The rowid for the new entry is left in register pParse->regRowid.
80027     ** The root page number of the new table is left in reg pParse->regRoot.
80028     ** The rowid and root page number values are needed by the code that
80029     ** sqlite3EndTable will generate.
80030     */
80031 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
80032     if( isView || isVirtual ){
80033       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
80034     }else
80035 #endif
80036     {
80037       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
80038     }
80039     sqlite3OpenMasterTable(pParse, iDb);
80040     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
80041     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
80042     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
80043     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80044     sqlite3VdbeAddOp0(v, OP_Close);
80045   }
80046 
80047   /* Normal (non-error) return. */
80048   return;
80049 
80050   /* If an error occurs, we jump here */
80051 begin_table_error:
80052   sqlite3DbFree(db, zName);
80053   return;
80054 }
80055 
80056 /*
80057 ** This macro is used to compare two strings in a case-insensitive manner.
80058 ** It is slightly faster than calling sqlite3StrICmp() directly, but
80059 ** produces larger code.
80060 **
80061 ** WARNING: This macro is not compatible with the strcmp() family. It
80062 ** returns true if the two strings are equal, otherwise false.
80063 */
80064 #define STRICMP(x, y) (\
80065 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
80066 sqlite3UpperToLower[*(unsigned char *)(y)]     \
80067 && sqlite3StrICmp((x)+1,(y)+1)==0 )
80068 
80069 /*
80070 ** Add a new column to the table currently being constructed.
80071 **
80072 ** The parser calls this routine once for each column declaration
80073 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
80074 ** first to get things going.  Then this routine is called for each
80075 ** column.
80076 */
80077 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
80078   Table *p;
80079   int i;
80080   char *z;
80081   Column *pCol;
80082   sqlite3 *db = pParse->db;
80083   if( (p = pParse->pNewTable)==0 ) return;
80084 #if SQLITE_MAX_COLUMN
80085   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
80086     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
80087     return;
80088   }
80089 #endif
80090   z = sqlite3NameFromToken(db, pName);
80091   if( z==0 ) return;
80092   for(i=0; i<p->nCol; i++){
80093     if( STRICMP(z, p->aCol[i].zName) ){
80094       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
80095       sqlite3DbFree(db, z);
80096       return;
80097     }
80098   }
80099   if( (p->nCol & 0x7)==0 ){
80100     Column *aNew;
80101     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
80102     if( aNew==0 ){
80103       sqlite3DbFree(db, z);
80104       return;
80105     }
80106     p->aCol = aNew;
80107   }
80108   pCol = &p->aCol[p->nCol];
80109   memset(pCol, 0, sizeof(p->aCol[0]));
80110   pCol->zName = z;
80111 
80112   /* If there is no type specified, columns have the default affinity
80113   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
80114   ** be called next to set pCol->affinity correctly.
80115   */
80116   pCol->affinity = SQLITE_AFF_NONE;
80117   p->nCol++;
80118 }
80119 
80120 /*
80121 ** This routine is called by the parser while in the middle of
80122 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
80123 ** been seen on a column.  This routine sets the notNull flag on
80124 ** the column currently under construction.
80125 */
80126 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
80127   Table *p;
80128   p = pParse->pNewTable;
80129   if( p==0 || NEVER(p->nCol<1) ) return;
80130   p->aCol[p->nCol-1].notNull = (u8)onError;
80131 }
80132 
80133 /*
80134 ** Scan the column type name zType (length nType) and return the
80135 ** associated affinity type.
80136 **
80137 ** This routine does a case-independent search of zType for the
80138 ** substrings in the following table. If one of the substrings is
80139 ** found, the corresponding affinity is returned. If zType contains
80140 ** more than one of the substrings, entries toward the top of
80141 ** the table take priority. For example, if zType is 'BLOBINT',
80142 ** SQLITE_AFF_INTEGER is returned.
80143 **
80144 ** Substring     | Affinity
80145 ** --------------------------------
80146 ** 'INT'         | SQLITE_AFF_INTEGER
80147 ** 'CHAR'        | SQLITE_AFF_TEXT
80148 ** 'CLOB'        | SQLITE_AFF_TEXT
80149 ** 'TEXT'        | SQLITE_AFF_TEXT
80150 ** 'BLOB'        | SQLITE_AFF_NONE
80151 ** 'REAL'        | SQLITE_AFF_REAL
80152 ** 'FLOA'        | SQLITE_AFF_REAL
80153 ** 'DOUB'        | SQLITE_AFF_REAL
80154 **
80155 ** If none of the substrings in the above table are found,
80156 ** SQLITE_AFF_NUMERIC is returned.
80157 */
80158 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
80159   u32 h = 0;
80160   char aff = SQLITE_AFF_NUMERIC;
80161 
80162   if( zIn ) while( zIn[0] ){
80163     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
80164     zIn++;
80165     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
80166       aff = SQLITE_AFF_TEXT;
80167     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
80168       aff = SQLITE_AFF_TEXT;
80169     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
80170       aff = SQLITE_AFF_TEXT;
80171     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
80172         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
80173       aff = SQLITE_AFF_NONE;
80174 #ifndef SQLITE_OMIT_FLOATING_POINT
80175     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
80176         && aff==SQLITE_AFF_NUMERIC ){
80177       aff = SQLITE_AFF_REAL;
80178     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
80179         && aff==SQLITE_AFF_NUMERIC ){
80180       aff = SQLITE_AFF_REAL;
80181     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
80182         && aff==SQLITE_AFF_NUMERIC ){
80183       aff = SQLITE_AFF_REAL;
80184 #endif
80185     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
80186       aff = SQLITE_AFF_INTEGER;
80187       break;
80188     }
80189   }
80190 
80191   return aff;
80192 }
80193 
80194 /*
80195 ** This routine is called by the parser while in the middle of
80196 ** parsing a CREATE TABLE statement.  The pFirst token is the first
80197 ** token in the sequence of tokens that describe the type of the
80198 ** column currently under construction.   pLast is the last token
80199 ** in the sequence.  Use this information to construct a string
80200 ** that contains the typename of the column and store that string
80201 ** in zType.
80202 */
80203 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
80204   Table *p;
80205   Column *pCol;
80206 
80207   p = pParse->pNewTable;
80208   if( p==0 || NEVER(p->nCol<1) ) return;
80209   pCol = &p->aCol[p->nCol-1];
80210   assert( pCol->zType==0 );
80211   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
80212   pCol->affinity = sqlite3AffinityType(pCol->zType);
80213 }
80214 
80215 /*
80216 ** The expression is the default value for the most recently added column
80217 ** of the table currently under construction.
80218 **
80219 ** Default value expressions must be constant.  Raise an exception if this
80220 ** is not the case.
80221 **
80222 ** This routine is called by the parser while in the middle of
80223 ** parsing a CREATE TABLE statement.
80224 */
80225 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
80226   Table *p;
80227   Column *pCol;
80228   sqlite3 *db = pParse->db;
80229   p = pParse->pNewTable;
80230   if( p!=0 ){
80231     pCol = &(p->aCol[p->nCol-1]);
80232     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
80233       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
80234           pCol->zName);
80235     }else{
80236       /* A copy of pExpr is used instead of the original, as pExpr contains
80237       ** tokens that point to volatile memory. The 'span' of the expression
80238       ** is required by pragma table_info.
80239       */
80240       sqlite3ExprDelete(db, pCol->pDflt);
80241       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
80242       sqlite3DbFree(db, pCol->zDflt);
80243       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
80244                                      (int)(pSpan->zEnd - pSpan->zStart));
80245     }
80246   }
80247   sqlite3ExprDelete(db, pSpan->pExpr);
80248 }
80249 
80250 /*
80251 ** Designate the PRIMARY KEY for the table.  pList is a list of names
80252 ** of columns that form the primary key.  If pList is NULL, then the
80253 ** most recently added column of the table is the primary key.
80254 **
80255 ** A table can have at most one primary key.  If the table already has
80256 ** a primary key (and this is the second primary key) then create an
80257 ** error.
80258 **
80259 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
80260 ** then we will try to use that column as the rowid.  Set the Table.iPKey
80261 ** field of the table under construction to be the index of the
80262 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
80263 ** no INTEGER PRIMARY KEY.
80264 **
80265 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
80266 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
80267 */
80268 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
80269   Parse *pParse,    /* Parsing context */
80270   ExprList *pList,  /* List of field names to be indexed */
80271   int onError,      /* What to do with a uniqueness conflict */
80272   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
80273   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
80274 ){
80275   Table *pTab = pParse->pNewTable;
80276   char *zType = 0;
80277   int iCol = -1, i;
80278   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
80279   if( pTab->tabFlags & TF_HasPrimaryKey ){
80280     sqlite3ErrorMsg(pParse,
80281       "table \"%s\" has more than one primary key", pTab->zName);
80282     goto primary_key_exit;
80283   }
80284   pTab->tabFlags |= TF_HasPrimaryKey;
80285   if( pList==0 ){
80286     iCol = pTab->nCol - 1;
80287     pTab->aCol[iCol].isPrimKey = 1;
80288   }else{
80289     for(i=0; i<pList->nExpr; i++){
80290       for(iCol=0; iCol<pTab->nCol; iCol++){
80291         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
80292           break;
80293         }
80294       }
80295       if( iCol<pTab->nCol ){
80296         pTab->aCol[iCol].isPrimKey = 1;
80297       }
80298     }
80299     if( pList->nExpr>1 ) iCol = -1;
80300   }
80301   if( iCol>=0 && iCol<pTab->nCol ){
80302     zType = pTab->aCol[iCol].zType;
80303   }
80304   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
80305         && sortOrder==SQLITE_SO_ASC ){
80306     pTab->iPKey = iCol;
80307     pTab->keyConf = (u8)onError;
80308     assert( autoInc==0 || autoInc==1 );
80309     pTab->tabFlags |= autoInc*TF_Autoincrement;
80310   }else if( autoInc ){
80311 #ifndef SQLITE_OMIT_AUTOINCREMENT
80312     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
80313        "INTEGER PRIMARY KEY");
80314 #endif
80315   }else{
80316     Index *p;
80317     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
80318     if( p ){
80319       p->autoIndex = 2;
80320     }
80321     pList = 0;
80322   }
80323 
80324 primary_key_exit:
80325   sqlite3ExprListDelete(pParse->db, pList);
80326   return;
80327 }
80328 
80329 /*
80330 ** Add a new CHECK constraint to the table currently under construction.
80331 */
80332 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
80333   Parse *pParse,    /* Parsing context */
80334   Expr *pCheckExpr  /* The check expression */
80335 ){
80336   sqlite3 *db = pParse->db;
80337 #ifndef SQLITE_OMIT_CHECK
80338   Table *pTab = pParse->pNewTable;
80339   if( pTab && !IN_DECLARE_VTAB ){
80340     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
80341   }else
80342 #endif
80343   {
80344     sqlite3ExprDelete(db, pCheckExpr);
80345   }
80346 }
80347 
80348 /*
80349 ** Set the collation function of the most recently parsed table column
80350 ** to the CollSeq given.
80351 */
80352 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
80353   Table *p;
80354   int i;
80355   char *zColl;              /* Dequoted name of collation sequence */
80356   sqlite3 *db;
80357 
80358   if( (p = pParse->pNewTable)==0 ) return;
80359   i = p->nCol-1;
80360   db = pParse->db;
80361   zColl = sqlite3NameFromToken(db, pToken);
80362   if( !zColl ) return;
80363 
80364   if( sqlite3LocateCollSeq(pParse, zColl) ){
80365     Index *pIdx;
80366     p->aCol[i].zColl = zColl;
80367 
80368     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
80369     ** then an index may have been created on this column before the
80370     ** collation type was added. Correct this if it is the case.
80371     */
80372     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
80373       assert( pIdx->nColumn==1 );
80374       if( pIdx->aiColumn[0]==i ){
80375         pIdx->azColl[0] = p->aCol[i].zColl;
80376       }
80377     }
80378   }else{
80379     sqlite3DbFree(db, zColl);
80380   }
80381 }
80382 
80383 /*
80384 ** This function returns the collation sequence for database native text
80385 ** encoding identified by the string zName, length nName.
80386 **
80387 ** If the requested collation sequence is not available, or not available
80388 ** in the database native encoding, the collation factory is invoked to
80389 ** request it. If the collation factory does not supply such a sequence,
80390 ** and the sequence is available in another text encoding, then that is
80391 ** returned instead.
80392 **
80393 ** If no versions of the requested collations sequence are available, or
80394 ** another error occurs, NULL is returned and an error message written into
80395 ** pParse.
80396 **
80397 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
80398 ** invokes the collation factory if the named collation cannot be found
80399 ** and generates an error message.
80400 **
80401 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
80402 */
80403 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
80404   sqlite3 *db = pParse->db;
80405   u8 enc = ENC(db);
80406   u8 initbusy = db->init.busy;
80407   CollSeq *pColl;
80408 
80409   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
80410   if( !initbusy && (!pColl || !pColl->xCmp) ){
80411     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
80412     if( !pColl ){
80413       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
80414     }
80415   }
80416 
80417   return pColl;
80418 }
80419 
80420 
80421 /*
80422 ** Generate code that will increment the schema cookie.
80423 **
80424 ** The schema cookie is used to determine when the schema for the
80425 ** database changes.  After each schema change, the cookie value
80426 ** changes.  When a process first reads the schema it records the
80427 ** cookie.  Thereafter, whenever it goes to access the database,
80428 ** it checks the cookie to make sure the schema has not changed
80429 ** since it was last read.
80430 **
80431 ** This plan is not completely bullet-proof.  It is possible for
80432 ** the schema to change multiple times and for the cookie to be
80433 ** set back to prior value.  But schema changes are infrequent
80434 ** and the probability of hitting the same cookie value is only
80435 ** 1 chance in 2^32.  So we're safe enough.
80436 */
80437 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
80438   int r1 = sqlite3GetTempReg(pParse);
80439   sqlite3 *db = pParse->db;
80440   Vdbe *v = pParse->pVdbe;
80441   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80442   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
80443   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
80444   sqlite3ReleaseTempReg(pParse, r1);
80445 }
80446 
80447 /*
80448 ** Measure the number of characters needed to output the given
80449 ** identifier.  The number returned includes any quotes used
80450 ** but does not include the null terminator.
80451 **
80452 ** The estimate is conservative.  It might be larger that what is
80453 ** really needed.
80454 */
80455 static int identLength(const char *z){
80456   int n;
80457   for(n=0; *z; n++, z++){
80458     if( *z=='"' ){ n++; }
80459   }
80460   return n + 2;
80461 }
80462 
80463 /*
80464 ** The first parameter is a pointer to an output buffer. The second
80465 ** parameter is a pointer to an integer that contains the offset at
80466 ** which to write into the output buffer. This function copies the
80467 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
80468 ** to the specified offset in the buffer and updates *pIdx to refer
80469 ** to the first byte after the last byte written before returning.
80470 **
80471 ** If the string zSignedIdent consists entirely of alpha-numeric
80472 ** characters, does not begin with a digit and is not an SQL keyword,
80473 ** then it is copied to the output buffer exactly as it is. Otherwise,
80474 ** it is quoted using double-quotes.
80475 */
80476 static void identPut(char *z, int *pIdx, char *zSignedIdent){
80477   unsigned char *zIdent = (unsigned char*)zSignedIdent;
80478   int i, j, needQuote;
80479   i = *pIdx;
80480 
80481   for(j=0; zIdent[j]; j++){
80482     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
80483   }
80484   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
80485   if( !needQuote ){
80486     needQuote = zIdent[j];
80487   }
80488 
80489   if( needQuote ) z[i++] = '"';
80490   for(j=0; zIdent[j]; j++){
80491     z[i++] = zIdent[j];
80492     if( zIdent[j]=='"' ) z[i++] = '"';
80493   }
80494   if( needQuote ) z[i++] = '"';
80495   z[i] = 0;
80496   *pIdx = i;
80497 }
80498 
80499 /*
80500 ** Generate a CREATE TABLE statement appropriate for the given
80501 ** table.  Memory to hold the text of the statement is obtained
80502 ** from sqliteMalloc() and must be freed by the calling function.
80503 */
80504 static char *createTableStmt(sqlite3 *db, Table *p){
80505   int i, k, n;
80506   char *zStmt;
80507   char *zSep, *zSep2, *zEnd;
80508   Column *pCol;
80509   n = 0;
80510   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
80511     n += identLength(pCol->zName) + 5;
80512   }
80513   n += identLength(p->zName);
80514   if( n<50 ){
80515     zSep = "";
80516     zSep2 = ",";
80517     zEnd = ")";
80518   }else{
80519     zSep = "\n  ";
80520     zSep2 = ",\n  ";
80521     zEnd = "\n)";
80522   }
80523   n += 35 + 6*p->nCol;
80524   zStmt = sqlite3DbMallocRaw(0, n);
80525   if( zStmt==0 ){
80526     db->mallocFailed = 1;
80527     return 0;
80528   }
80529   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
80530   k = sqlite3Strlen30(zStmt);
80531   identPut(zStmt, &k, p->zName);
80532   zStmt[k++] = '(';
80533   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
80534     static const char * const azType[] = {
80535         /* SQLITE_AFF_TEXT    */ " TEXT",
80536         /* SQLITE_AFF_NONE    */ "",
80537         /* SQLITE_AFF_NUMERIC */ " NUM",
80538         /* SQLITE_AFF_INTEGER */ " INT",
80539         /* SQLITE_AFF_REAL    */ " REAL"
80540     };
80541     int len;
80542     const char *zType;
80543 
80544     sqlite3_snprintf(n-k, &zStmt[k], zSep);
80545     k += sqlite3Strlen30(&zStmt[k]);
80546     zSep = zSep2;
80547     identPut(zStmt, &k, pCol->zName);
80548     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
80549     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
80550     testcase( pCol->affinity==SQLITE_AFF_TEXT );
80551     testcase( pCol->affinity==SQLITE_AFF_NONE );
80552     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
80553     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
80554     testcase( pCol->affinity==SQLITE_AFF_REAL );
80555 
80556     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
80557     len = sqlite3Strlen30(zType);
80558     assert( pCol->affinity==SQLITE_AFF_NONE
80559             || pCol->affinity==sqlite3AffinityType(zType) );
80560     memcpy(&zStmt[k], zType, len);
80561     k += len;
80562     assert( k<=n );
80563   }
80564   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
80565   return zStmt;
80566 }
80567 
80568 /*
80569 ** This routine is called to report the final ")" that terminates
80570 ** a CREATE TABLE statement.
80571 **
80572 ** The table structure that other action routines have been building
80573 ** is added to the internal hash tables, assuming no errors have
80574 ** occurred.
80575 **
80576 ** An entry for the table is made in the master table on disk, unless
80577 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
80578 ** it means we are reading the sqlite_master table because we just
80579 ** connected to the database or because the sqlite_master table has
80580 ** recently changed, so the entry for this table already exists in
80581 ** the sqlite_master table.  We do not want to create it again.
80582 **
80583 ** If the pSelect argument is not NULL, it means that this routine
80584 ** was called to create a table generated from a
80585 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
80586 ** the new table will match the result set of the SELECT.
80587 */
80588 SQLITE_PRIVATE void sqlite3EndTable(
80589   Parse *pParse,          /* Parse context */
80590   Token *pCons,           /* The ',' token after the last column defn. */
80591   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
80592   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
80593 ){
80594   Table *p;
80595   sqlite3 *db = pParse->db;
80596   int iDb;
80597 
80598   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
80599     return;
80600   }
80601   p = pParse->pNewTable;
80602   if( p==0 ) return;
80603 
80604   assert( !db->init.busy || !pSelect );
80605 
80606   iDb = sqlite3SchemaToIndex(db, p->pSchema);
80607 
80608 #ifndef SQLITE_OMIT_CHECK
80609   /* Resolve names in all CHECK constraint expressions.
80610   */
80611   if( p->pCheck ){
80612     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
80613     NameContext sNC;                /* Name context for pParse->pNewTable */
80614 
80615     memset(&sNC, 0, sizeof(sNC));
80616     memset(&sSrc, 0, sizeof(sSrc));
80617     sSrc.nSrc = 1;
80618     sSrc.a[0].zName = p->zName;
80619     sSrc.a[0].pTab = p;
80620     sSrc.a[0].iCursor = -1;
80621     sNC.pParse = pParse;
80622     sNC.pSrcList = &sSrc;
80623     sNC.isCheck = 1;
80624     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
80625       return;
80626     }
80627   }
80628 #endif /* !defined(SQLITE_OMIT_CHECK) */
80629 
80630   /* If the db->init.busy is 1 it means we are reading the SQL off the
80631   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
80632   ** So do not write to the disk again.  Extract the root page number
80633   ** for the table from the db->init.newTnum field.  (The page number
80634   ** should have been put there by the sqliteOpenCb routine.)
80635   */
80636   if( db->init.busy ){
80637     p->tnum = db->init.newTnum;
80638   }
80639 
80640   /* If not initializing, then create a record for the new table
80641   ** in the SQLITE_MASTER table of the database.
80642   **
80643   ** If this is a TEMPORARY table, write the entry into the auxiliary
80644   ** file instead of into the main database file.
80645   */
80646   if( !db->init.busy ){
80647     int n;
80648     Vdbe *v;
80649     char *zType;    /* "view" or "table" */
80650     char *zType2;   /* "VIEW" or "TABLE" */
80651     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
80652 
80653     v = sqlite3GetVdbe(pParse);
80654     if( NEVER(v==0) ) return;
80655 
80656     sqlite3VdbeAddOp1(v, OP_Close, 0);
80657 
80658     /*
80659     ** Initialize zType for the new view or table.
80660     */
80661     if( p->pSelect==0 ){
80662       /* A regular table */
80663       zType = "table";
80664       zType2 = "TABLE";
80665 #ifndef SQLITE_OMIT_VIEW
80666     }else{
80667       /* A view */
80668       zType = "view";
80669       zType2 = "VIEW";
80670 #endif
80671     }
80672 
80673     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
80674     ** statement to populate the new table. The root-page number for the
80675     ** new table is in register pParse->regRoot.
80676     **
80677     ** Once the SELECT has been coded by sqlite3Select(), it is in a
80678     ** suitable state to query for the column names and types to be used
80679     ** by the new table.
80680     **
80681     ** A shared-cache write-lock is not required to write to the new table,
80682     ** as a schema-lock must have already been obtained to create it. Since
80683     ** a schema-lock excludes all other database users, the write-lock would
80684     ** be redundant.
80685     */
80686     if( pSelect ){
80687       SelectDest dest;
80688       Table *pSelTab;
80689 
80690       assert(pParse->nTab==1);
80691       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
80692       sqlite3VdbeChangeP5(v, 1);
80693       pParse->nTab = 2;
80694       sqlite3SelectDestInit(&dest, SRT_Table, 1);
80695       sqlite3Select(pParse, pSelect, &dest);
80696       sqlite3VdbeAddOp1(v, OP_Close, 1);
80697       if( pParse->nErr==0 ){
80698         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
80699         if( pSelTab==0 ) return;
80700         assert( p->aCol==0 );
80701         p->nCol = pSelTab->nCol;
80702         p->aCol = pSelTab->aCol;
80703         pSelTab->nCol = 0;
80704         pSelTab->aCol = 0;
80705         sqlite3DeleteTable(db, pSelTab);
80706       }
80707     }
80708 
80709     /* Compute the complete text of the CREATE statement */
80710     if( pSelect ){
80711       zStmt = createTableStmt(db, p);
80712     }else{
80713       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
80714       zStmt = sqlite3MPrintf(db,
80715           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
80716       );
80717     }
80718 
80719     /* A slot for the record has already been allocated in the
80720     ** SQLITE_MASTER table.  We just need to update that slot with all
80721     ** the information we've collected.
80722     */
80723     sqlite3NestedParse(pParse,
80724       "UPDATE %Q.%s "
80725          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
80726        "WHERE rowid=#%d",
80727       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
80728       zType,
80729       p->zName,
80730       p->zName,
80731       pParse->regRoot,
80732       zStmt,
80733       pParse->regRowid
80734     );
80735     sqlite3DbFree(db, zStmt);
80736     sqlite3ChangeCookie(pParse, iDb);
80737 
80738 #ifndef SQLITE_OMIT_AUTOINCREMENT
80739     /* Check to see if we need to create an sqlite_sequence table for
80740     ** keeping track of autoincrement keys.
80741     */
80742     if( p->tabFlags & TF_Autoincrement ){
80743       Db *pDb = &db->aDb[iDb];
80744       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80745       if( pDb->pSchema->pSeqTab==0 ){
80746         sqlite3NestedParse(pParse,
80747           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
80748           pDb->zName
80749         );
80750       }
80751     }
80752 #endif
80753 
80754     /* Reparse everything to update our internal data structures */
80755     sqlite3VdbeAddParseSchemaOp(v, iDb,
80756                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
80757   }
80758 
80759 
80760   /* Add the table to the in-memory representation of the database.
80761   */
80762   if( db->init.busy ){
80763     Table *pOld;
80764     Schema *pSchema = p->pSchema;
80765     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80766     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
80767                              sqlite3Strlen30(p->zName),p);
80768     if( pOld ){
80769       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
80770       db->mallocFailed = 1;
80771       return;
80772     }
80773     pParse->pNewTable = 0;
80774     db->nTable++;
80775     db->flags |= SQLITE_InternChanges;
80776 
80777 #ifndef SQLITE_OMIT_ALTERTABLE
80778     if( !p->pSelect ){
80779       const char *zName = (const char *)pParse->sNameToken.z;
80780       int nName;
80781       assert( !pSelect && pCons && pEnd );
80782       if( pCons->z==0 ){
80783         pCons = pEnd;
80784       }
80785       nName = (int)((const char *)pCons->z - zName);
80786       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
80787     }
80788 #endif
80789   }
80790 }
80791 
80792 #ifndef SQLITE_OMIT_VIEW
80793 /*
80794 ** The parser calls this routine in order to create a new VIEW
80795 */
80796 SQLITE_PRIVATE void sqlite3CreateView(
80797   Parse *pParse,     /* The parsing context */
80798   Token *pBegin,     /* The CREATE token that begins the statement */
80799   Token *pName1,     /* The token that holds the name of the view */
80800   Token *pName2,     /* The token that holds the name of the view */
80801   Select *pSelect,   /* A SELECT statement that will become the new view */
80802   int isTemp,        /* TRUE for a TEMPORARY view */
80803   int noErr          /* Suppress error messages if VIEW already exists */
80804 ){
80805   Table *p;
80806   int n;
80807   const char *z;
80808   Token sEnd;
80809   DbFixer sFix;
80810   Token *pName = 0;
80811   int iDb;
80812   sqlite3 *db = pParse->db;
80813 
80814   if( pParse->nVar>0 ){
80815     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
80816     sqlite3SelectDelete(db, pSelect);
80817     return;
80818   }
80819   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
80820   p = pParse->pNewTable;
80821   if( p==0 || pParse->nErr ){
80822     sqlite3SelectDelete(db, pSelect);
80823     return;
80824   }
80825   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
80826   iDb = sqlite3SchemaToIndex(db, p->pSchema);
80827   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
80828     && sqlite3FixSelect(&sFix, pSelect)
80829   ){
80830     sqlite3SelectDelete(db, pSelect);
80831     return;
80832   }
80833 
80834   /* Make a copy of the entire SELECT statement that defines the view.
80835   ** This will force all the Expr.token.z values to be dynamically
80836   ** allocated rather than point to the input string - which means that
80837   ** they will persist after the current sqlite3_exec() call returns.
80838   */
80839   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
80840   sqlite3SelectDelete(db, pSelect);
80841   if( db->mallocFailed ){
80842     return;
80843   }
80844   if( !db->init.busy ){
80845     sqlite3ViewGetColumnNames(pParse, p);
80846   }
80847 
80848   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
80849   ** the end.
80850   */
80851   sEnd = pParse->sLastToken;
80852   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
80853     sEnd.z += sEnd.n;
80854   }
80855   sEnd.n = 0;
80856   n = (int)(sEnd.z - pBegin->z);
80857   z = pBegin->z;
80858   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
80859   sEnd.z = &z[n-1];
80860   sEnd.n = 1;
80861 
80862   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
80863   sqlite3EndTable(pParse, 0, &sEnd, 0);
80864   return;
80865 }
80866 #endif /* SQLITE_OMIT_VIEW */
80867 
80868 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
80869 /*
80870 ** The Table structure pTable is really a VIEW.  Fill in the names of
80871 ** the columns of the view in the pTable structure.  Return the number
80872 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
80873 */
80874 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
80875   Table *pSelTab;   /* A fake table from which we get the result set */
80876   Select *pSel;     /* Copy of the SELECT that implements the view */
80877   int nErr = 0;     /* Number of errors encountered */
80878   int n;            /* Temporarily holds the number of cursors assigned */
80879   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
80880   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
80881 
80882   assert( pTable );
80883 
80884 #ifndef SQLITE_OMIT_VIRTUALTABLE
80885   if( sqlite3VtabCallConnect(pParse, pTable) ){
80886     return SQLITE_ERROR;
80887   }
80888   if( IsVirtual(pTable) ) return 0;
80889 #endif
80890 
80891 #ifndef SQLITE_OMIT_VIEW
80892   /* A positive nCol means the columns names for this view are
80893   ** already known.
80894   */
80895   if( pTable->nCol>0 ) return 0;
80896 
80897   /* A negative nCol is a special marker meaning that we are currently
80898   ** trying to compute the column names.  If we enter this routine with
80899   ** a negative nCol, it means two or more views form a loop, like this:
80900   **
80901   **     CREATE VIEW one AS SELECT * FROM two;
80902   **     CREATE VIEW two AS SELECT * FROM one;
80903   **
80904   ** Actually, the error above is now caught prior to reaching this point.
80905   ** But the following test is still important as it does come up
80906   ** in the following:
80907   **
80908   **     CREATE TABLE main.ex1(a);
80909   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
80910   **     SELECT * FROM temp.ex1;
80911   */
80912   if( pTable->nCol<0 ){
80913     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
80914     return 1;
80915   }
80916   assert( pTable->nCol>=0 );
80917 
80918   /* If we get this far, it means we need to compute the table names.
80919   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
80920   ** "*" elements in the results set of the view and will assign cursors
80921   ** to the elements of the FROM clause.  But we do not want these changes
80922   ** to be permanent.  So the computation is done on a copy of the SELECT
80923   ** statement that defines the view.
80924   */
80925   assert( pTable->pSelect );
80926   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
80927   if( pSel ){
80928     u8 enableLookaside = db->lookaside.bEnabled;
80929     n = pParse->nTab;
80930     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
80931     pTable->nCol = -1;
80932     db->lookaside.bEnabled = 0;
80933 #ifndef SQLITE_OMIT_AUTHORIZATION
80934     xAuth = db->xAuth;
80935     db->xAuth = 0;
80936     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
80937     db->xAuth = xAuth;
80938 #else
80939     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
80940 #endif
80941     db->lookaside.bEnabled = enableLookaside;
80942     pParse->nTab = n;
80943     if( pSelTab ){
80944       assert( pTable->aCol==0 );
80945       pTable->nCol = pSelTab->nCol;
80946       pTable->aCol = pSelTab->aCol;
80947       pSelTab->nCol = 0;
80948       pSelTab->aCol = 0;
80949       sqlite3DeleteTable(db, pSelTab);
80950       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
80951       pTable->pSchema->flags |= DB_UnresetViews;
80952     }else{
80953       pTable->nCol = 0;
80954       nErr++;
80955     }
80956     sqlite3SelectDelete(db, pSel);
80957   } else {
80958     nErr++;
80959   }
80960 #endif /* SQLITE_OMIT_VIEW */
80961   return nErr;
80962 }
80963 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
80964 
80965 #ifndef SQLITE_OMIT_VIEW
80966 /*
80967 ** Clear the column names from every VIEW in database idx.
80968 */
80969 static void sqliteViewResetAll(sqlite3 *db, int idx){
80970   HashElem *i;
80971   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
80972   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
80973   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
80974     Table *pTab = sqliteHashData(i);
80975     if( pTab->pSelect ){
80976       sqliteDeleteColumnNames(db, pTab);
80977       pTab->aCol = 0;
80978       pTab->nCol = 0;
80979     }
80980   }
80981   DbClearProperty(db, idx, DB_UnresetViews);
80982 }
80983 #else
80984 # define sqliteViewResetAll(A,B)
80985 #endif /* SQLITE_OMIT_VIEW */
80986 
80987 /*
80988 ** This function is called by the VDBE to adjust the internal schema
80989 ** used by SQLite when the btree layer moves a table root page. The
80990 ** root-page of a table or index in database iDb has changed from iFrom
80991 ** to iTo.
80992 **
80993 ** Ticket #1728:  The symbol table might still contain information
80994 ** on tables and/or indices that are the process of being deleted.
80995 ** If you are unlucky, one of those deleted indices or tables might
80996 ** have the same rootpage number as the real table or index that is
80997 ** being moved.  So we cannot stop searching after the first match
80998 ** because the first match might be for one of the deleted indices
80999 ** or tables and not the table/index that is actually being moved.
81000 ** We must continue looping until all tables and indices with
81001 ** rootpage==iFrom have been converted to have a rootpage of iTo
81002 ** in order to be certain that we got the right one.
81003 */
81004 #ifndef SQLITE_OMIT_AUTOVACUUM
81005 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
81006   HashElem *pElem;
81007   Hash *pHash;
81008   Db *pDb;
81009 
81010   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81011   pDb = &db->aDb[iDb];
81012   pHash = &pDb->pSchema->tblHash;
81013   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
81014     Table *pTab = sqliteHashData(pElem);
81015     if( pTab->tnum==iFrom ){
81016       pTab->tnum = iTo;
81017     }
81018   }
81019   pHash = &pDb->pSchema->idxHash;
81020   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
81021     Index *pIdx = sqliteHashData(pElem);
81022     if( pIdx->tnum==iFrom ){
81023       pIdx->tnum = iTo;
81024     }
81025   }
81026 }
81027 #endif
81028 
81029 /*
81030 ** Write code to erase the table with root-page iTable from database iDb.
81031 ** Also write code to modify the sqlite_master table and internal schema
81032 ** if a root-page of another table is moved by the btree-layer whilst
81033 ** erasing iTable (this can happen with an auto-vacuum database).
81034 */
81035 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
81036   Vdbe *v = sqlite3GetVdbe(pParse);
81037   int r1 = sqlite3GetTempReg(pParse);
81038   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
81039   sqlite3MayAbort(pParse);
81040 #ifndef SQLITE_OMIT_AUTOVACUUM
81041   /* OP_Destroy stores an in integer r1. If this integer
81042   ** is non-zero, then it is the root page number of a table moved to
81043   ** location iTable. The following code modifies the sqlite_master table to
81044   ** reflect this.
81045   **
81046   ** The "#NNN" in the SQL is a special constant that means whatever value
81047   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
81048   ** token for additional information.
81049   */
81050   sqlite3NestedParse(pParse,
81051      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
81052      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
81053 #endif
81054   sqlite3ReleaseTempReg(pParse, r1);
81055 }
81056 
81057 /*
81058 ** Write VDBE code to erase table pTab and all associated indices on disk.
81059 ** Code to update the sqlite_master tables and internal schema definitions
81060 ** in case a root-page belonging to another table is moved by the btree layer
81061 ** is also added (this can happen with an auto-vacuum database).
81062 */
81063 static void destroyTable(Parse *pParse, Table *pTab){
81064 #ifdef SQLITE_OMIT_AUTOVACUUM
81065   Index *pIdx;
81066   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81067   destroyRootPage(pParse, pTab->tnum, iDb);
81068   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81069     destroyRootPage(pParse, pIdx->tnum, iDb);
81070   }
81071 #else
81072   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
81073   ** is not defined), then it is important to call OP_Destroy on the
81074   ** table and index root-pages in order, starting with the numerically
81075   ** largest root-page number. This guarantees that none of the root-pages
81076   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
81077   ** following were coded:
81078   **
81079   ** OP_Destroy 4 0
81080   ** ...
81081   ** OP_Destroy 5 0
81082   **
81083   ** and root page 5 happened to be the largest root-page number in the
81084   ** database, then root page 5 would be moved to page 4 by the
81085   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
81086   ** a free-list page.
81087   */
81088   int iTab = pTab->tnum;
81089   int iDestroyed = 0;
81090 
81091   while( 1 ){
81092     Index *pIdx;
81093     int iLargest = 0;
81094 
81095     if( iDestroyed==0 || iTab<iDestroyed ){
81096       iLargest = iTab;
81097     }
81098     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81099       int iIdx = pIdx->tnum;
81100       assert( pIdx->pSchema==pTab->pSchema );
81101       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
81102         iLargest = iIdx;
81103       }
81104     }
81105     if( iLargest==0 ){
81106       return;
81107     }else{
81108       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
81109       destroyRootPage(pParse, iLargest, iDb);
81110       iDestroyed = iLargest;
81111     }
81112   }
81113 #endif
81114 }
81115 
81116 /*
81117 ** Remove entries from the sqlite_stat1 and sqlite_stat2 tables
81118 ** after a DROP INDEX or DROP TABLE command.
81119 */
81120 static void sqlite3ClearStatTables(
81121   Parse *pParse,         /* The parsing context */
81122   int iDb,               /* The database number */
81123   const char *zType,     /* "idx" or "tbl" */
81124   const char *zName      /* Name of index or table */
81125 ){
81126   static const char *azStatTab[] = { "sqlite_stat1", "sqlite_stat2" };
81127   int i;
81128   const char *zDbName = pParse->db->aDb[iDb].zName;
81129   for(i=0; i<ArraySize(azStatTab); i++){
81130     if( sqlite3FindTable(pParse->db, azStatTab[i], zDbName) ){
81131       sqlite3NestedParse(pParse,
81132         "DELETE FROM %Q.%s WHERE %s=%Q",
81133         zDbName, azStatTab[i], zType, zName
81134       );
81135     }
81136   }
81137 }
81138 
81139 /*
81140 ** This routine is called to do the work of a DROP TABLE statement.
81141 ** pName is the name of the table to be dropped.
81142 */
81143 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
81144   Table *pTab;
81145   Vdbe *v;
81146   sqlite3 *db = pParse->db;
81147   int iDb;
81148 
81149   if( db->mallocFailed ){
81150     goto exit_drop_table;
81151   }
81152   assert( pParse->nErr==0 );
81153   assert( pName->nSrc==1 );
81154   if( noErr ) db->suppressErr++;
81155   pTab = sqlite3LocateTable(pParse, isView,
81156                             pName->a[0].zName, pName->a[0].zDatabase);
81157   if( noErr ) db->suppressErr--;
81158 
81159   if( pTab==0 ){
81160     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
81161     goto exit_drop_table;
81162   }
81163   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81164   assert( iDb>=0 && iDb<db->nDb );
81165 
81166   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
81167   ** it is initialized.
81168   */
81169   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
81170     goto exit_drop_table;
81171   }
81172 #ifndef SQLITE_OMIT_AUTHORIZATION
81173   {
81174     int code;
81175     const char *zTab = SCHEMA_TABLE(iDb);
81176     const char *zDb = db->aDb[iDb].zName;
81177     const char *zArg2 = 0;
81178     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
81179       goto exit_drop_table;
81180     }
81181     if( isView ){
81182       if( !OMIT_TEMPDB && iDb==1 ){
81183         code = SQLITE_DROP_TEMP_VIEW;
81184       }else{
81185         code = SQLITE_DROP_VIEW;
81186       }
81187 #ifndef SQLITE_OMIT_VIRTUALTABLE
81188     }else if( IsVirtual(pTab) ){
81189       code = SQLITE_DROP_VTABLE;
81190       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
81191 #endif
81192     }else{
81193       if( !OMIT_TEMPDB && iDb==1 ){
81194         code = SQLITE_DROP_TEMP_TABLE;
81195       }else{
81196         code = SQLITE_DROP_TABLE;
81197       }
81198     }
81199     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
81200       goto exit_drop_table;
81201     }
81202     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
81203       goto exit_drop_table;
81204     }
81205   }
81206 #endif
81207   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
81208     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
81209     goto exit_drop_table;
81210   }
81211 
81212 #ifndef SQLITE_OMIT_VIEW
81213   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
81214   ** on a table.
81215   */
81216   if( isView && pTab->pSelect==0 ){
81217     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
81218     goto exit_drop_table;
81219   }
81220   if( !isView && pTab->pSelect ){
81221     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
81222     goto exit_drop_table;
81223   }
81224 #endif
81225 
81226   /* Generate code to remove the table from the master table
81227   ** on disk.
81228   */
81229   v = sqlite3GetVdbe(pParse);
81230   if( v ){
81231     Trigger *pTrigger;
81232     Db *pDb = &db->aDb[iDb];
81233     sqlite3BeginWriteOperation(pParse, 1, iDb);
81234 
81235 #ifndef SQLITE_OMIT_VIRTUALTABLE
81236     if( IsVirtual(pTab) ){
81237       sqlite3VdbeAddOp0(v, OP_VBegin);
81238     }
81239 #endif
81240     sqlite3FkDropTable(pParse, pName, pTab);
81241 
81242     /* Drop all triggers associated with the table being dropped. Code
81243     ** is generated to remove entries from sqlite_master and/or
81244     ** sqlite_temp_master if required.
81245     */
81246     pTrigger = sqlite3TriggerList(pParse, pTab);
81247     while( pTrigger ){
81248       assert( pTrigger->pSchema==pTab->pSchema ||
81249           pTrigger->pSchema==db->aDb[1].pSchema );
81250       sqlite3DropTriggerPtr(pParse, pTrigger);
81251       pTrigger = pTrigger->pNext;
81252     }
81253 
81254 #ifndef SQLITE_OMIT_AUTOINCREMENT
81255     /* Remove any entries of the sqlite_sequence table associated with
81256     ** the table being dropped. This is done before the table is dropped
81257     ** at the btree level, in case the sqlite_sequence table needs to
81258     ** move as a result of the drop (can happen in auto-vacuum mode).
81259     */
81260     if( pTab->tabFlags & TF_Autoincrement ){
81261       sqlite3NestedParse(pParse,
81262         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
81263         pDb->zName, pTab->zName
81264       );
81265     }
81266 #endif
81267 
81268     /* Drop all SQLITE_MASTER table and index entries that refer to the
81269     ** table. The program name loops through the master table and deletes
81270     ** every row that refers to a table of the same name as the one being
81271     ** dropped. Triggers are handled seperately because a trigger can be
81272     ** created in the temp database that refers to a table in another
81273     ** database.
81274     */
81275     sqlite3NestedParse(pParse,
81276         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
81277         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
81278     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
81279     if( !isView && !IsVirtual(pTab) ){
81280       destroyTable(pParse, pTab);
81281     }
81282 
81283     /* Remove the table entry from SQLite's internal schema and modify
81284     ** the schema cookie.
81285     */
81286     if( IsVirtual(pTab) ){
81287       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
81288     }
81289     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
81290     sqlite3ChangeCookie(pParse, iDb);
81291   }
81292   sqliteViewResetAll(db, iDb);
81293 
81294 exit_drop_table:
81295   sqlite3SrcListDelete(db, pName);
81296 }
81297 
81298 /*
81299 ** This routine is called to create a new foreign key on the table
81300 ** currently under construction.  pFromCol determines which columns
81301 ** in the current table point to the foreign key.  If pFromCol==0 then
81302 ** connect the key to the last column inserted.  pTo is the name of
81303 ** the table referred to.  pToCol is a list of tables in the other
81304 ** pTo table that the foreign key points to.  flags contains all
81305 ** information about the conflict resolution algorithms specified
81306 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
81307 **
81308 ** An FKey structure is created and added to the table currently
81309 ** under construction in the pParse->pNewTable field.
81310 **
81311 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
81312 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
81313 */
81314 SQLITE_PRIVATE void sqlite3CreateForeignKey(
81315   Parse *pParse,       /* Parsing context */
81316   ExprList *pFromCol,  /* Columns in this table that point to other table */
81317   Token *pTo,          /* Name of the other table */
81318   ExprList *pToCol,    /* Columns in the other table */
81319   int flags            /* Conflict resolution algorithms. */
81320 ){
81321   sqlite3 *db = pParse->db;
81322 #ifndef SQLITE_OMIT_FOREIGN_KEY
81323   FKey *pFKey = 0;
81324   FKey *pNextTo;
81325   Table *p = pParse->pNewTable;
81326   int nByte;
81327   int i;
81328   int nCol;
81329   char *z;
81330 
81331   assert( pTo!=0 );
81332   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
81333   if( pFromCol==0 ){
81334     int iCol = p->nCol-1;
81335     if( NEVER(iCol<0) ) goto fk_end;
81336     if( pToCol && pToCol->nExpr!=1 ){
81337       sqlite3ErrorMsg(pParse, "foreign key on %s"
81338          " should reference only one column of table %T",
81339          p->aCol[iCol].zName, pTo);
81340       goto fk_end;
81341     }
81342     nCol = 1;
81343   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
81344     sqlite3ErrorMsg(pParse,
81345         "number of columns in foreign key does not match the number of "
81346         "columns in the referenced table");
81347     goto fk_end;
81348   }else{
81349     nCol = pFromCol->nExpr;
81350   }
81351   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
81352   if( pToCol ){
81353     for(i=0; i<pToCol->nExpr; i++){
81354       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
81355     }
81356   }
81357   pFKey = sqlite3DbMallocZero(db, nByte );
81358   if( pFKey==0 ){
81359     goto fk_end;
81360   }
81361   pFKey->pFrom = p;
81362   pFKey->pNextFrom = p->pFKey;
81363   z = (char*)&pFKey->aCol[nCol];
81364   pFKey->zTo = z;
81365   memcpy(z, pTo->z, pTo->n);
81366   z[pTo->n] = 0;
81367   sqlite3Dequote(z);
81368   z += pTo->n+1;
81369   pFKey->nCol = nCol;
81370   if( pFromCol==0 ){
81371     pFKey->aCol[0].iFrom = p->nCol-1;
81372   }else{
81373     for(i=0; i<nCol; i++){
81374       int j;
81375       for(j=0; j<p->nCol; j++){
81376         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
81377           pFKey->aCol[i].iFrom = j;
81378           break;
81379         }
81380       }
81381       if( j>=p->nCol ){
81382         sqlite3ErrorMsg(pParse,
81383           "unknown column \"%s\" in foreign key definition",
81384           pFromCol->a[i].zName);
81385         goto fk_end;
81386       }
81387     }
81388   }
81389   if( pToCol ){
81390     for(i=0; i<nCol; i++){
81391       int n = sqlite3Strlen30(pToCol->a[i].zName);
81392       pFKey->aCol[i].zCol = z;
81393       memcpy(z, pToCol->a[i].zName, n);
81394       z[n] = 0;
81395       z += n+1;
81396     }
81397   }
81398   pFKey->isDeferred = 0;
81399   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
81400   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
81401 
81402   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
81403   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
81404       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
81405   );
81406   if( pNextTo==pFKey ){
81407     db->mallocFailed = 1;
81408     goto fk_end;
81409   }
81410   if( pNextTo ){
81411     assert( pNextTo->pPrevTo==0 );
81412     pFKey->pNextTo = pNextTo;
81413     pNextTo->pPrevTo = pFKey;
81414   }
81415 
81416   /* Link the foreign key to the table as the last step.
81417   */
81418   p->pFKey = pFKey;
81419   pFKey = 0;
81420 
81421 fk_end:
81422   sqlite3DbFree(db, pFKey);
81423 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
81424   sqlite3ExprListDelete(db, pFromCol);
81425   sqlite3ExprListDelete(db, pToCol);
81426 }
81427 
81428 /*
81429 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
81430 ** clause is seen as part of a foreign key definition.  The isDeferred
81431 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
81432 ** The behavior of the most recently created foreign key is adjusted
81433 ** accordingly.
81434 */
81435 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
81436 #ifndef SQLITE_OMIT_FOREIGN_KEY
81437   Table *pTab;
81438   FKey *pFKey;
81439   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
81440   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
81441   pFKey->isDeferred = (u8)isDeferred;
81442 #endif
81443 }
81444 
81445 /*
81446 ** Generate code that will erase and refill index *pIdx.  This is
81447 ** used to initialize a newly created index or to recompute the
81448 ** content of an index in response to a REINDEX command.
81449 **
81450 ** if memRootPage is not negative, it means that the index is newly
81451 ** created.  The register specified by memRootPage contains the
81452 ** root page number of the index.  If memRootPage is negative, then
81453 ** the index already exists and must be cleared before being refilled and
81454 ** the root page number of the index is taken from pIndex->tnum.
81455 */
81456 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
81457   Table *pTab = pIndex->pTable;  /* The table that is indexed */
81458   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
81459   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
81460   int iSorter = iTab;            /* Cursor opened by OpenSorter (if in use) */
81461   int addr1;                     /* Address of top of loop */
81462   int addr2;                     /* Address to jump to for next iteration */
81463   int tnum;                      /* Root page of index */
81464   Vdbe *v;                       /* Generate code into this virtual machine */
81465   KeyInfo *pKey;                 /* KeyInfo for index */
81466   int regIdxKey;                 /* Registers containing the index key */
81467   int regRecord;                 /* Register holding assemblied index record */
81468   sqlite3 *db = pParse->db;      /* The database connection */
81469   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
81470 
81471 #ifndef SQLITE_OMIT_AUTHORIZATION
81472   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
81473       db->aDb[iDb].zName ) ){
81474     return;
81475   }
81476 #endif
81477 
81478   /* Require a write-lock on the table to perform this operation */
81479   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
81480 
81481   v = sqlite3GetVdbe(pParse);
81482   if( v==0 ) return;
81483   if( memRootPage>=0 ){
81484     tnum = memRootPage;
81485   }else{
81486     tnum = pIndex->tnum;
81487     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
81488   }
81489   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
81490   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
81491                     (char *)pKey, P4_KEYINFO_HANDOFF);
81492   if( memRootPage>=0 ){
81493     sqlite3VdbeChangeP5(v, 1);
81494   }
81495 
81496 #ifndef SQLITE_OMIT_MERGE_SORT
81497   /* Open the sorter cursor if we are to use one. */
81498   iSorter = pParse->nTab++;
81499   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
81500 #endif
81501 
81502   /* Open the table. Loop through all rows of the table, inserting index
81503   ** records into the sorter. */
81504   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
81505   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
81506   addr2 = addr1 + 1;
81507   regRecord = sqlite3GetTempReg(pParse);
81508   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
81509 
81510 #ifndef SQLITE_OMIT_MERGE_SORT
81511   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
81512   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
81513   sqlite3VdbeJumpHere(v, addr1);
81514   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
81515   if( pIndex->onError!=OE_None ){
81516     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
81517     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
81518     addr2 = sqlite3VdbeCurrentAddr(v);
81519     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
81520     sqlite3HaltConstraint(
81521         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
81522     );
81523   }else{
81524     addr2 = sqlite3VdbeCurrentAddr(v);
81525   }
81526   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
81527   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
81528   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81529 #else
81530   if( pIndex->onError!=OE_None ){
81531     const int regRowid = regIdxKey + pIndex->nColumn;
81532     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
81533     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
81534 
81535     /* The registers accessed by the OP_IsUnique opcode were allocated
81536     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
81537     ** call above. Just before that function was freed they were released
81538     ** (made available to the compiler for reuse) using
81539     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
81540     ** opcode use the values stored within seems dangerous. However, since
81541     ** we can be sure that no other temp registers have been allocated
81542     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
81543     */
81544     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
81545     sqlite3HaltConstraint(
81546         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
81547   }
81548   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
81549   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
81550 #endif
81551   sqlite3ReleaseTempReg(pParse, regRecord);
81552   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
81553   sqlite3VdbeJumpHere(v, addr1);
81554 
81555   sqlite3VdbeAddOp1(v, OP_Close, iTab);
81556   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
81557   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
81558 }
81559 
81560 /*
81561 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index
81562 ** and pTblList is the name of the table that is to be indexed.  Both will
81563 ** be NULL for a primary key or an index that is created to satisfy a
81564 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
81565 ** as the table to be indexed.  pParse->pNewTable is a table that is
81566 ** currently being constructed by a CREATE TABLE statement.
81567 **
81568 ** pList is a list of columns to be indexed.  pList will be NULL if this
81569 ** is a primary key or unique-constraint on the most recent column added
81570 ** to the table currently under construction.
81571 **
81572 ** If the index is created successfully, return a pointer to the new Index
81573 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
81574 ** as the tables primary key (Index.autoIndex==2).
81575 */
81576 SQLITE_PRIVATE Index *sqlite3CreateIndex(
81577   Parse *pParse,     /* All information about this parse */
81578   Token *pName1,     /* First part of index name. May be NULL */
81579   Token *pName2,     /* Second part of index name. May be NULL */
81580   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
81581   ExprList *pList,   /* A list of columns to be indexed */
81582   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
81583   Token *pStart,     /* The CREATE token that begins this statement */
81584   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
81585   int sortOrder,     /* Sort order of primary key when pList==NULL */
81586   int ifNotExist     /* Omit error if index already exists */
81587 ){
81588   Index *pRet = 0;     /* Pointer to return */
81589   Table *pTab = 0;     /* Table to be indexed */
81590   Index *pIndex = 0;   /* The index to be created */
81591   char *zName = 0;     /* Name of the index */
81592   int nName;           /* Number of characters in zName */
81593   int i, j;
81594   Token nullId;        /* Fake token for an empty ID list */
81595   DbFixer sFix;        /* For assigning database names to pTable */
81596   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
81597   sqlite3 *db = pParse->db;
81598   Db *pDb;             /* The specific table containing the indexed database */
81599   int iDb;             /* Index of the database that is being written */
81600   Token *pName = 0;    /* Unqualified name of the index to create */
81601   struct ExprList_item *pListItem; /* For looping over pList */
81602   int nCol;
81603   int nExtra = 0;
81604   char *zExtra;
81605 
81606   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
81607   assert( pParse->nErr==0 );      /* Never called with prior errors */
81608   if( db->mallocFailed || IN_DECLARE_VTAB ){
81609     goto exit_create_index;
81610   }
81611   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81612     goto exit_create_index;
81613   }
81614 
81615   /*
81616   ** Find the table that is to be indexed.  Return early if not found.
81617   */
81618   if( pTblName!=0 ){
81619 
81620     /* Use the two-part index name to determine the database
81621     ** to search for the table. 'Fix' the table name to this db
81622     ** before looking up the table.
81623     */
81624     assert( pName1 && pName2 );
81625     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81626     if( iDb<0 ) goto exit_create_index;
81627 
81628 #ifndef SQLITE_OMIT_TEMPDB
81629     /* If the index name was unqualified, check if the the table
81630     ** is a temp table. If so, set the database to 1. Do not do this
81631     ** if initialising a database schema.
81632     */
81633     if( !db->init.busy ){
81634       pTab = sqlite3SrcListLookup(pParse, pTblName);
81635       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
81636         iDb = 1;
81637       }
81638     }
81639 #endif
81640 
81641     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
81642         sqlite3FixSrcList(&sFix, pTblName)
81643     ){
81644       /* Because the parser constructs pTblName from a single identifier,
81645       ** sqlite3FixSrcList can never fail. */
81646       assert(0);
81647     }
81648     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
81649         pTblName->a[0].zDatabase);
81650     if( !pTab || db->mallocFailed ) goto exit_create_index;
81651     assert( db->aDb[iDb].pSchema==pTab->pSchema );
81652   }else{
81653     assert( pName==0 );
81654     pTab = pParse->pNewTable;
81655     if( !pTab ) goto exit_create_index;
81656     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
81657   }
81658   pDb = &db->aDb[iDb];
81659 
81660   assert( pTab!=0 );
81661   assert( pParse->nErr==0 );
81662   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
81663        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
81664     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
81665     goto exit_create_index;
81666   }
81667 #ifndef SQLITE_OMIT_VIEW
81668   if( pTab->pSelect ){
81669     sqlite3ErrorMsg(pParse, "views may not be indexed");
81670     goto exit_create_index;
81671   }
81672 #endif
81673 #ifndef SQLITE_OMIT_VIRTUALTABLE
81674   if( IsVirtual(pTab) ){
81675     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
81676     goto exit_create_index;
81677   }
81678 #endif
81679 
81680   /*
81681   ** Find the name of the index.  Make sure there is not already another
81682   ** index or table with the same name.
81683   **
81684   ** Exception:  If we are reading the names of permanent indices from the
81685   ** sqlite_master table (because some other process changed the schema) and
81686   ** one of the index names collides with the name of a temporary table or
81687   ** index, then we will continue to process this index.
81688   **
81689   ** If pName==0 it means that we are
81690   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
81691   ** own name.
81692   */
81693   if( pName ){
81694     zName = sqlite3NameFromToken(db, pName);
81695     if( zName==0 ) goto exit_create_index;
81696     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81697       goto exit_create_index;
81698     }
81699     if( !db->init.busy ){
81700       if( sqlite3FindTable(db, zName, 0)!=0 ){
81701         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
81702         goto exit_create_index;
81703       }
81704     }
81705     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
81706       if( !ifNotExist ){
81707         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
81708       }else{
81709         assert( !db->init.busy );
81710         sqlite3CodeVerifySchema(pParse, iDb);
81711       }
81712       goto exit_create_index;
81713     }
81714   }else{
81715     int n;
81716     Index *pLoop;
81717     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
81718     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
81719     if( zName==0 ){
81720       goto exit_create_index;
81721     }
81722   }
81723 
81724   /* Check for authorization to create an index.
81725   */
81726 #ifndef SQLITE_OMIT_AUTHORIZATION
81727   {
81728     const char *zDb = pDb->zName;
81729     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
81730       goto exit_create_index;
81731     }
81732     i = SQLITE_CREATE_INDEX;
81733     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
81734     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
81735       goto exit_create_index;
81736     }
81737   }
81738 #endif
81739 
81740   /* If pList==0, it means this routine was called to make a primary
81741   ** key out of the last column added to the table under construction.
81742   ** So create a fake list to simulate this.
81743   */
81744   if( pList==0 ){
81745     nullId.z = pTab->aCol[pTab->nCol-1].zName;
81746     nullId.n = sqlite3Strlen30((char*)nullId.z);
81747     pList = sqlite3ExprListAppend(pParse, 0, 0);
81748     if( pList==0 ) goto exit_create_index;
81749     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
81750     pList->a[0].sortOrder = (u8)sortOrder;
81751   }
81752 
81753   /* Figure out how many bytes of space are required to store explicitly
81754   ** specified collation sequence names.
81755   */
81756   for(i=0; i<pList->nExpr; i++){
81757     Expr *pExpr = pList->a[i].pExpr;
81758     if( pExpr ){
81759       CollSeq *pColl = pExpr->pColl;
81760       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
81761       ** failure we have quit before reaching this point. */
81762       if( ALWAYS(pColl) ){
81763         nExtra += (1 + sqlite3Strlen30(pColl->zName));
81764       }
81765     }
81766   }
81767 
81768   /*
81769   ** Allocate the index structure.
81770   */
81771   nName = sqlite3Strlen30(zName);
81772   nCol = pList->nExpr;
81773   pIndex = sqlite3DbMallocZero(db,
81774       sizeof(Index) +              /* Index structure  */
81775       sizeof(int)*nCol +           /* Index.aiColumn   */
81776       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
81777       sizeof(char *)*nCol +        /* Index.azColl     */
81778       sizeof(u8)*nCol +            /* Index.aSortOrder */
81779       nName + 1 +                  /* Index.zName      */
81780       nExtra                       /* Collation sequence names */
81781   );
81782   if( db->mallocFailed ){
81783     goto exit_create_index;
81784   }
81785   pIndex->azColl = (char**)(&pIndex[1]);
81786   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
81787   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
81788   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
81789   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
81790   zExtra = (char *)(&pIndex->zName[nName+1]);
81791   memcpy(pIndex->zName, zName, nName+1);
81792   pIndex->pTable = pTab;
81793   pIndex->nColumn = pList->nExpr;
81794   pIndex->onError = (u8)onError;
81795   pIndex->autoIndex = (u8)(pName==0);
81796   pIndex->pSchema = db->aDb[iDb].pSchema;
81797   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81798 
81799   /* Check to see if we should honor DESC requests on index columns
81800   */
81801   if( pDb->pSchema->file_format>=4 ){
81802     sortOrderMask = -1;   /* Honor DESC */
81803   }else{
81804     sortOrderMask = 0;    /* Ignore DESC */
81805   }
81806 
81807   /* Scan the names of the columns of the table to be indexed and
81808   ** load the column indices into the Index structure.  Report an error
81809   ** if any column is not found.
81810   **
81811   ** TODO:  Add a test to make sure that the same column is not named
81812   ** more than once within the same index.  Only the first instance of
81813   ** the column will ever be used by the optimizer.  Note that using the
81814   ** same column more than once cannot be an error because that would
81815   ** break backwards compatibility - it needs to be a warning.
81816   */
81817   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
81818     const char *zColName = pListItem->zName;
81819     Column *pTabCol;
81820     int requestedSortOrder;
81821     char *zColl;                   /* Collation sequence name */
81822 
81823     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
81824       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
81825     }
81826     if( j>=pTab->nCol ){
81827       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
81828         pTab->zName, zColName);
81829       pParse->checkSchema = 1;
81830       goto exit_create_index;
81831     }
81832     pIndex->aiColumn[i] = j;
81833     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
81834     ** the way the "idxlist" non-terminal is constructed by the parser,
81835     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
81836     ** must exist or else there must have been an OOM error.  But if there
81837     ** was an OOM error, we would never reach this point. */
81838     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
81839       int nColl;
81840       zColl = pListItem->pExpr->pColl->zName;
81841       nColl = sqlite3Strlen30(zColl) + 1;
81842       assert( nExtra>=nColl );
81843       memcpy(zExtra, zColl, nColl);
81844       zColl = zExtra;
81845       zExtra += nColl;
81846       nExtra -= nColl;
81847     }else{
81848       zColl = pTab->aCol[j].zColl;
81849       if( !zColl ){
81850         zColl = db->pDfltColl->zName;
81851       }
81852     }
81853     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
81854       goto exit_create_index;
81855     }
81856     pIndex->azColl[i] = zColl;
81857     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
81858     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
81859   }
81860   sqlite3DefaultRowEst(pIndex);
81861 
81862   if( pTab==pParse->pNewTable ){
81863     /* This routine has been called to create an automatic index as a
81864     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
81865     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
81866     ** i.e. one of:
81867     **
81868     ** CREATE TABLE t(x PRIMARY KEY, y);
81869     ** CREATE TABLE t(x, y, UNIQUE(x, y));
81870     **
81871     ** Either way, check to see if the table already has such an index. If
81872     ** so, don't bother creating this one. This only applies to
81873     ** automatically created indices. Users can do as they wish with
81874     ** explicit indices.
81875     **
81876     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
81877     ** (and thus suppressing the second one) even if they have different
81878     ** sort orders.
81879     **
81880     ** If there are different collating sequences or if the columns of
81881     ** the constraint occur in different orders, then the constraints are
81882     ** considered distinct and both result in separate indices.
81883     */
81884     Index *pIdx;
81885     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
81886       int k;
81887       assert( pIdx->onError!=OE_None );
81888       assert( pIdx->autoIndex );
81889       assert( pIndex->onError!=OE_None );
81890 
81891       if( pIdx->nColumn!=pIndex->nColumn ) continue;
81892       for(k=0; k<pIdx->nColumn; k++){
81893         const char *z1;
81894         const char *z2;
81895         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
81896         z1 = pIdx->azColl[k];
81897         z2 = pIndex->azColl[k];
81898         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
81899       }
81900       if( k==pIdx->nColumn ){
81901         if( pIdx->onError!=pIndex->onError ){
81902           /* This constraint creates the same index as a previous
81903           ** constraint specified somewhere in the CREATE TABLE statement.
81904           ** However the ON CONFLICT clauses are different. If both this
81905           ** constraint and the previous equivalent constraint have explicit
81906           ** ON CONFLICT clauses this is an error. Otherwise, use the
81907           ** explicitly specified behaviour for the index.
81908           */
81909           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
81910             sqlite3ErrorMsg(pParse,
81911                 "conflicting ON CONFLICT clauses specified", 0);
81912           }
81913           if( pIdx->onError==OE_Default ){
81914             pIdx->onError = pIndex->onError;
81915           }
81916         }
81917         goto exit_create_index;
81918       }
81919     }
81920   }
81921 
81922   /* Link the new Index structure to its table and to the other
81923   ** in-memory database structures.
81924   */
81925   if( db->init.busy ){
81926     Index *p;
81927     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81928     p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
81929                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
81930                           pIndex);
81931     if( p ){
81932       assert( p==pIndex );  /* Malloc must have failed */
81933       db->mallocFailed = 1;
81934       goto exit_create_index;
81935     }
81936     db->flags |= SQLITE_InternChanges;
81937     if( pTblName!=0 ){
81938       pIndex->tnum = db->init.newTnum;
81939     }
81940   }
81941 
81942   /* If the db->init.busy is 0 then create the index on disk.  This
81943   ** involves writing the index into the master table and filling in the
81944   ** index with the current table contents.
81945   **
81946   ** The db->init.busy is 0 when the user first enters a CREATE INDEX
81947   ** command.  db->init.busy is 1 when a database is opened and
81948   ** CREATE INDEX statements are read out of the master table.  In
81949   ** the latter case the index already exists on disk, which is why
81950   ** we don't want to recreate it.
81951   **
81952   ** If pTblName==0 it means this index is generated as a primary key
81953   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
81954   ** has just been created, it contains no data and the index initialization
81955   ** step can be skipped.
81956   */
81957   else{ /* if( db->init.busy==0 ) */
81958     Vdbe *v;
81959     char *zStmt;
81960     int iMem = ++pParse->nMem;
81961 
81962     v = sqlite3GetVdbe(pParse);
81963     if( v==0 ) goto exit_create_index;
81964 
81965 
81966     /* Create the rootpage for the index
81967     */
81968     sqlite3BeginWriteOperation(pParse, 1, iDb);
81969     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
81970 
81971     /* Gather the complete text of the CREATE INDEX statement into
81972     ** the zStmt variable
81973     */
81974     if( pStart ){
81975       assert( pEnd!=0 );
81976       /* A named index with an explicit CREATE INDEX statement */
81977       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
81978         onError==OE_None ? "" : " UNIQUE",
81979         (int)(pEnd->z - pName->z) + 1,
81980         pName->z);
81981     }else{
81982       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
81983       /* zStmt = sqlite3MPrintf(""); */
81984       zStmt = 0;
81985     }
81986 
81987     /* Add an entry in sqlite_master for this index
81988     */
81989     sqlite3NestedParse(pParse,
81990         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
81991         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
81992         pIndex->zName,
81993         pTab->zName,
81994         iMem,
81995         zStmt
81996     );
81997     sqlite3DbFree(db, zStmt);
81998 
81999     /* Fill the index with data and reparse the schema. Code an OP_Expire
82000     ** to invalidate all pre-compiled statements.
82001     */
82002     if( pTblName ){
82003       sqlite3RefillIndex(pParse, pIndex, iMem);
82004       sqlite3ChangeCookie(pParse, iDb);
82005       sqlite3VdbeAddParseSchemaOp(v, iDb,
82006          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
82007       sqlite3VdbeAddOp1(v, OP_Expire, 0);
82008     }
82009   }
82010 
82011   /* When adding an index to the list of indices for a table, make
82012   ** sure all indices labeled OE_Replace come after all those labeled
82013   ** OE_Ignore.  This is necessary for the correct constraint check
82014   ** processing (in sqlite3GenerateConstraintChecks()) as part of
82015   ** UPDATE and INSERT statements.
82016   */
82017   if( db->init.busy || pTblName==0 ){
82018     if( onError!=OE_Replace || pTab->pIndex==0
82019          || pTab->pIndex->onError==OE_Replace){
82020       pIndex->pNext = pTab->pIndex;
82021       pTab->pIndex = pIndex;
82022     }else{
82023       Index *pOther = pTab->pIndex;
82024       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
82025         pOther = pOther->pNext;
82026       }
82027       pIndex->pNext = pOther->pNext;
82028       pOther->pNext = pIndex;
82029     }
82030     pRet = pIndex;
82031     pIndex = 0;
82032   }
82033 
82034   /* Clean up before exiting */
82035 exit_create_index:
82036   if( pIndex ){
82037     sqlite3DbFree(db, pIndex->zColAff);
82038     sqlite3DbFree(db, pIndex);
82039   }
82040   sqlite3ExprListDelete(db, pList);
82041   sqlite3SrcListDelete(db, pTblName);
82042   sqlite3DbFree(db, zName);
82043   return pRet;
82044 }
82045 
82046 /*
82047 ** Fill the Index.aiRowEst[] array with default information - information
82048 ** to be used when we have not run the ANALYZE command.
82049 **
82050 ** aiRowEst[0] is suppose to contain the number of elements in the index.
82051 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
82052 ** number of rows in the table that match any particular value of the
82053 ** first column of the index.  aiRowEst[2] is an estimate of the number
82054 ** of rows that match any particular combiniation of the first 2 columns
82055 ** of the index.  And so forth.  It must always be the case that
82056 *
82057 **           aiRowEst[N]<=aiRowEst[N-1]
82058 **           aiRowEst[N]>=1
82059 **
82060 ** Apart from that, we have little to go on besides intuition as to
82061 ** how aiRowEst[] should be initialized.  The numbers generated here
82062 ** are based on typical values found in actual indices.
82063 */
82064 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
82065   unsigned *a = pIdx->aiRowEst;
82066   int i;
82067   unsigned n;
82068   assert( a!=0 );
82069   a[0] = pIdx->pTable->nRowEst;
82070   if( a[0]<10 ) a[0] = 10;
82071   n = 10;
82072   for(i=1; i<=pIdx->nColumn; i++){
82073     a[i] = n;
82074     if( n>5 ) n--;
82075   }
82076   if( pIdx->onError!=OE_None ){
82077     a[pIdx->nColumn] = 1;
82078   }
82079 }
82080 
82081 /*
82082 ** This routine will drop an existing named index.  This routine
82083 ** implements the DROP INDEX statement.
82084 */
82085 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
82086   Index *pIndex;
82087   Vdbe *v;
82088   sqlite3 *db = pParse->db;
82089   int iDb;
82090 
82091   assert( pParse->nErr==0 );   /* Never called with prior errors */
82092   if( db->mallocFailed ){
82093     goto exit_drop_index;
82094   }
82095   assert( pName->nSrc==1 );
82096   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82097     goto exit_drop_index;
82098   }
82099   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
82100   if( pIndex==0 ){
82101     if( !ifExists ){
82102       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
82103     }else{
82104       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
82105     }
82106     pParse->checkSchema = 1;
82107     goto exit_drop_index;
82108   }
82109   if( pIndex->autoIndex ){
82110     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
82111       "or PRIMARY KEY constraint cannot be dropped", 0);
82112     goto exit_drop_index;
82113   }
82114   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
82115 #ifndef SQLITE_OMIT_AUTHORIZATION
82116   {
82117     int code = SQLITE_DROP_INDEX;
82118     Table *pTab = pIndex->pTable;
82119     const char *zDb = db->aDb[iDb].zName;
82120     const char *zTab = SCHEMA_TABLE(iDb);
82121     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
82122       goto exit_drop_index;
82123     }
82124     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
82125     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
82126       goto exit_drop_index;
82127     }
82128   }
82129 #endif
82130 
82131   /* Generate code to remove the index and from the master table */
82132   v = sqlite3GetVdbe(pParse);
82133   if( v ){
82134     sqlite3BeginWriteOperation(pParse, 1, iDb);
82135     sqlite3NestedParse(pParse,
82136        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
82137        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
82138     );
82139     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
82140     sqlite3ChangeCookie(pParse, iDb);
82141     destroyRootPage(pParse, pIndex->tnum, iDb);
82142     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
82143   }
82144 
82145 exit_drop_index:
82146   sqlite3SrcListDelete(db, pName);
82147 }
82148 
82149 /*
82150 ** pArray is a pointer to an array of objects.  Each object in the
82151 ** array is szEntry bytes in size.  This routine allocates a new
82152 ** object on the end of the array.
82153 **
82154 ** *pnEntry is the number of entries already in use.  *pnAlloc is
82155 ** the previously allocated size of the array.  initSize is the
82156 ** suggested initial array size allocation.
82157 **
82158 ** The index of the new entry is returned in *pIdx.
82159 **
82160 ** This routine returns a pointer to the array of objects.  This
82161 ** might be the same as the pArray parameter or it might be a different
82162 ** pointer if the array was resized.
82163 */
82164 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
82165   sqlite3 *db,      /* Connection to notify of malloc failures */
82166   void *pArray,     /* Array of objects.  Might be reallocated */
82167   int szEntry,      /* Size of each object in the array */
82168   int initSize,     /* Suggested initial allocation, in elements */
82169   int *pnEntry,     /* Number of objects currently in use */
82170   int *pnAlloc,     /* Current size of the allocation, in elements */
82171   int *pIdx         /* Write the index of a new slot here */
82172 ){
82173   char *z;
82174   if( *pnEntry >= *pnAlloc ){
82175     void *pNew;
82176     int newSize;
82177     newSize = (*pnAlloc)*2 + initSize;
82178     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
82179     if( pNew==0 ){
82180       *pIdx = -1;
82181       return pArray;
82182     }
82183     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
82184     pArray = pNew;
82185   }
82186   z = (char*)pArray;
82187   memset(&z[*pnEntry * szEntry], 0, szEntry);
82188   *pIdx = *pnEntry;
82189   ++*pnEntry;
82190   return pArray;
82191 }
82192 
82193 /*
82194 ** Append a new element to the given IdList.  Create a new IdList if
82195 ** need be.
82196 **
82197 ** A new IdList is returned, or NULL if malloc() fails.
82198 */
82199 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
82200   int i;
82201   if( pList==0 ){
82202     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
82203     if( pList==0 ) return 0;
82204     pList->nAlloc = 0;
82205   }
82206   pList->a = sqlite3ArrayAllocate(
82207       db,
82208       pList->a,
82209       sizeof(pList->a[0]),
82210       5,
82211       &pList->nId,
82212       &pList->nAlloc,
82213       &i
82214   );
82215   if( i<0 ){
82216     sqlite3IdListDelete(db, pList);
82217     return 0;
82218   }
82219   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
82220   return pList;
82221 }
82222 
82223 /*
82224 ** Delete an IdList.
82225 */
82226 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
82227   int i;
82228   if( pList==0 ) return;
82229   for(i=0; i<pList->nId; i++){
82230     sqlite3DbFree(db, pList->a[i].zName);
82231   }
82232   sqlite3DbFree(db, pList->a);
82233   sqlite3DbFree(db, pList);
82234 }
82235 
82236 /*
82237 ** Return the index in pList of the identifier named zId.  Return -1
82238 ** if not found.
82239 */
82240 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
82241   int i;
82242   if( pList==0 ) return -1;
82243   for(i=0; i<pList->nId; i++){
82244     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
82245   }
82246   return -1;
82247 }
82248 
82249 /*
82250 ** Expand the space allocated for the given SrcList object by
82251 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
82252 ** New slots are zeroed.
82253 **
82254 ** For example, suppose a SrcList initially contains two entries: A,B.
82255 ** To append 3 new entries onto the end, do this:
82256 **
82257 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
82258 **
82259 ** After the call above it would contain:  A, B, nil, nil, nil.
82260 ** If the iStart argument had been 1 instead of 2, then the result
82261 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
82262 ** the iStart value would be 0.  The result then would
82263 ** be: nil, nil, nil, A, B.
82264 **
82265 ** If a memory allocation fails the SrcList is unchanged.  The
82266 ** db->mallocFailed flag will be set to true.
82267 */
82268 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
82269   sqlite3 *db,       /* Database connection to notify of OOM errors */
82270   SrcList *pSrc,     /* The SrcList to be enlarged */
82271   int nExtra,        /* Number of new slots to add to pSrc->a[] */
82272   int iStart         /* Index in pSrc->a[] of first new slot */
82273 ){
82274   int i;
82275 
82276   /* Sanity checking on calling parameters */
82277   assert( iStart>=0 );
82278   assert( nExtra>=1 );
82279   assert( pSrc!=0 );
82280   assert( iStart<=pSrc->nSrc );
82281 
82282   /* Allocate additional space if needed */
82283   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
82284     SrcList *pNew;
82285     int nAlloc = pSrc->nSrc+nExtra;
82286     int nGot;
82287     pNew = sqlite3DbRealloc(db, pSrc,
82288                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
82289     if( pNew==0 ){
82290       assert( db->mallocFailed );
82291       return pSrc;
82292     }
82293     pSrc = pNew;
82294     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
82295     pSrc->nAlloc = (u16)nGot;
82296   }
82297 
82298   /* Move existing slots that come after the newly inserted slots
82299   ** out of the way */
82300   for(i=pSrc->nSrc-1; i>=iStart; i--){
82301     pSrc->a[i+nExtra] = pSrc->a[i];
82302   }
82303   pSrc->nSrc += (i16)nExtra;
82304 
82305   /* Zero the newly allocated slots */
82306   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
82307   for(i=iStart; i<iStart+nExtra; i++){
82308     pSrc->a[i].iCursor = -1;
82309   }
82310 
82311   /* Return a pointer to the enlarged SrcList */
82312   return pSrc;
82313 }
82314 
82315 
82316 /*
82317 ** Append a new table name to the given SrcList.  Create a new SrcList if
82318 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
82319 **
82320 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
82321 ** SrcList might be the same as the SrcList that was input or it might be
82322 ** a new one.  If an OOM error does occurs, then the prior value of pList
82323 ** that is input to this routine is automatically freed.
82324 **
82325 ** If pDatabase is not null, it means that the table has an optional
82326 ** database name prefix.  Like this:  "database.table".  The pDatabase
82327 ** points to the table name and the pTable points to the database name.
82328 ** The SrcList.a[].zName field is filled with the table name which might
82329 ** come from pTable (if pDatabase is NULL) or from pDatabase.
82330 ** SrcList.a[].zDatabase is filled with the database name from pTable,
82331 ** or with NULL if no database is specified.
82332 **
82333 ** In other words, if call like this:
82334 **
82335 **         sqlite3SrcListAppend(D,A,B,0);
82336 **
82337 ** Then B is a table name and the database name is unspecified.  If called
82338 ** like this:
82339 **
82340 **         sqlite3SrcListAppend(D,A,B,C);
82341 **
82342 ** Then C is the table name and B is the database name.  If C is defined
82343 ** then so is B.  In other words, we never have a case where:
82344 **
82345 **         sqlite3SrcListAppend(D,A,0,C);
82346 **
82347 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
82348 ** before being added to the SrcList.
82349 */
82350 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
82351   sqlite3 *db,        /* Connection to notify of malloc failures */
82352   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
82353   Token *pTable,      /* Table to append */
82354   Token *pDatabase    /* Database of the table */
82355 ){
82356   struct SrcList_item *pItem;
82357   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
82358   if( pList==0 ){
82359     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
82360     if( pList==0 ) return 0;
82361     pList->nAlloc = 1;
82362   }
82363   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
82364   if( db->mallocFailed ){
82365     sqlite3SrcListDelete(db, pList);
82366     return 0;
82367   }
82368   pItem = &pList->a[pList->nSrc-1];
82369   if( pDatabase && pDatabase->z==0 ){
82370     pDatabase = 0;
82371   }
82372   if( pDatabase ){
82373     Token *pTemp = pDatabase;
82374     pDatabase = pTable;
82375     pTable = pTemp;
82376   }
82377   pItem->zName = sqlite3NameFromToken(db, pTable);
82378   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
82379   return pList;
82380 }
82381 
82382 /*
82383 ** Assign VdbeCursor index numbers to all tables in a SrcList
82384 */
82385 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
82386   int i;
82387   struct SrcList_item *pItem;
82388   assert(pList || pParse->db->mallocFailed );
82389   if( pList ){
82390     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
82391       if( pItem->iCursor>=0 ) break;
82392       pItem->iCursor = pParse->nTab++;
82393       if( pItem->pSelect ){
82394         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
82395       }
82396     }
82397   }
82398 }
82399 
82400 /*
82401 ** Delete an entire SrcList including all its substructure.
82402 */
82403 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
82404   int i;
82405   struct SrcList_item *pItem;
82406   if( pList==0 ) return;
82407   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
82408     sqlite3DbFree(db, pItem->zDatabase);
82409     sqlite3DbFree(db, pItem->zName);
82410     sqlite3DbFree(db, pItem->zAlias);
82411     sqlite3DbFree(db, pItem->zIndex);
82412     sqlite3DeleteTable(db, pItem->pTab);
82413     sqlite3SelectDelete(db, pItem->pSelect);
82414     sqlite3ExprDelete(db, pItem->pOn);
82415     sqlite3IdListDelete(db, pItem->pUsing);
82416   }
82417   sqlite3DbFree(db, pList);
82418 }
82419 
82420 /*
82421 ** This routine is called by the parser to add a new term to the
82422 ** end of a growing FROM clause.  The "p" parameter is the part of
82423 ** the FROM clause that has already been constructed.  "p" is NULL
82424 ** if this is the first term of the FROM clause.  pTable and pDatabase
82425 ** are the name of the table and database named in the FROM clause term.
82426 ** pDatabase is NULL if the database name qualifier is missing - the
82427 ** usual case.  If the term has a alias, then pAlias points to the
82428 ** alias token.  If the term is a subquery, then pSubquery is the
82429 ** SELECT statement that the subquery encodes.  The pTable and
82430 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
82431 ** parameters are the content of the ON and USING clauses.
82432 **
82433 ** Return a new SrcList which encodes is the FROM with the new
82434 ** term added.
82435 */
82436 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
82437   Parse *pParse,          /* Parsing context */
82438   SrcList *p,             /* The left part of the FROM clause already seen */
82439   Token *pTable,          /* Name of the table to add to the FROM clause */
82440   Token *pDatabase,       /* Name of the database containing pTable */
82441   Token *pAlias,          /* The right-hand side of the AS subexpression */
82442   Select *pSubquery,      /* A subquery used in place of a table name */
82443   Expr *pOn,              /* The ON clause of a join */
82444   IdList *pUsing          /* The USING clause of a join */
82445 ){
82446   struct SrcList_item *pItem;
82447   sqlite3 *db = pParse->db;
82448   if( !p && (pOn || pUsing) ){
82449     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
82450       (pOn ? "ON" : "USING")
82451     );
82452     goto append_from_error;
82453   }
82454   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
82455   if( p==0 || NEVER(p->nSrc==0) ){
82456     goto append_from_error;
82457   }
82458   pItem = &p->a[p->nSrc-1];
82459   assert( pAlias!=0 );
82460   if( pAlias->n ){
82461     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
82462   }
82463   pItem->pSelect = pSubquery;
82464   pItem->pOn = pOn;
82465   pItem->pUsing = pUsing;
82466   return p;
82467 
82468  append_from_error:
82469   assert( p==0 );
82470   sqlite3ExprDelete(db, pOn);
82471   sqlite3IdListDelete(db, pUsing);
82472   sqlite3SelectDelete(db, pSubquery);
82473   return 0;
82474 }
82475 
82476 /*
82477 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
82478 ** element of the source-list passed as the second argument.
82479 */
82480 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
82481   assert( pIndexedBy!=0 );
82482   if( p && ALWAYS(p->nSrc>0) ){
82483     struct SrcList_item *pItem = &p->a[p->nSrc-1];
82484     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
82485     if( pIndexedBy->n==1 && !pIndexedBy->z ){
82486       /* A "NOT INDEXED" clause was supplied. See parse.y
82487       ** construct "indexed_opt" for details. */
82488       pItem->notIndexed = 1;
82489     }else{
82490       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
82491     }
82492   }
82493 }
82494 
82495 /*
82496 ** When building up a FROM clause in the parser, the join operator
82497 ** is initially attached to the left operand.  But the code generator
82498 ** expects the join operator to be on the right operand.  This routine
82499 ** Shifts all join operators from left to right for an entire FROM
82500 ** clause.
82501 **
82502 ** Example: Suppose the join is like this:
82503 **
82504 **           A natural cross join B
82505 **
82506 ** The operator is "natural cross join".  The A and B operands are stored
82507 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
82508 ** operator with A.  This routine shifts that operator over to B.
82509 */
82510 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
82511   if( p ){
82512     int i;
82513     assert( p->a || p->nSrc==0 );
82514     for(i=p->nSrc-1; i>0; i--){
82515       p->a[i].jointype = p->a[i-1].jointype;
82516     }
82517     p->a[0].jointype = 0;
82518   }
82519 }
82520 
82521 /*
82522 ** Begin a transaction
82523 */
82524 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
82525   sqlite3 *db;
82526   Vdbe *v;
82527   int i;
82528 
82529   assert( pParse!=0 );
82530   db = pParse->db;
82531   assert( db!=0 );
82532 /*  if( db->aDb[0].pBt==0 ) return; */
82533   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
82534     return;
82535   }
82536   v = sqlite3GetVdbe(pParse);
82537   if( !v ) return;
82538   if( type!=TK_DEFERRED ){
82539     for(i=0; i<db->nDb; i++){
82540       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
82541       sqlite3VdbeUsesBtree(v, i);
82542     }
82543   }
82544   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
82545 }
82546 
82547 /*
82548 ** Commit a transaction
82549 */
82550 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
82551   sqlite3 *db;
82552   Vdbe *v;
82553 
82554   assert( pParse!=0 );
82555   db = pParse->db;
82556   assert( db!=0 );
82557 /*  if( db->aDb[0].pBt==0 ) return; */
82558   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
82559     return;
82560   }
82561   v = sqlite3GetVdbe(pParse);
82562   if( v ){
82563     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
82564   }
82565 }
82566 
82567 /*
82568 ** Rollback a transaction
82569 */
82570 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
82571   sqlite3 *db;
82572   Vdbe *v;
82573 
82574   assert( pParse!=0 );
82575   db = pParse->db;
82576   assert( db!=0 );
82577 /*  if( db->aDb[0].pBt==0 ) return; */
82578   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
82579     return;
82580   }
82581   v = sqlite3GetVdbe(pParse);
82582   if( v ){
82583     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
82584   }
82585 }
82586 
82587 /*
82588 ** This function is called by the parser when it parses a command to create,
82589 ** release or rollback an SQL savepoint.
82590 */
82591 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
82592   char *zName = sqlite3NameFromToken(pParse->db, pName);
82593   if( zName ){
82594     Vdbe *v = sqlite3GetVdbe(pParse);
82595 #ifndef SQLITE_OMIT_AUTHORIZATION
82596     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
82597     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
82598 #endif
82599     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
82600       sqlite3DbFree(pParse->db, zName);
82601       return;
82602     }
82603     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
82604   }
82605 }
82606 
82607 /*
82608 ** Make sure the TEMP database is open and available for use.  Return
82609 ** the number of errors.  Leave any error messages in the pParse structure.
82610 */
82611 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
82612   sqlite3 *db = pParse->db;
82613   if( db->aDb[1].pBt==0 && !pParse->explain ){
82614     int rc;
82615     Btree *pBt;
82616     static const int flags =
82617           SQLITE_OPEN_READWRITE |
82618           SQLITE_OPEN_CREATE |
82619           SQLITE_OPEN_EXCLUSIVE |
82620           SQLITE_OPEN_DELETEONCLOSE |
82621           SQLITE_OPEN_TEMP_DB;
82622 
82623     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
82624     if( rc!=SQLITE_OK ){
82625       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
82626         "file for storing temporary tables");
82627       pParse->rc = rc;
82628       return 1;
82629     }
82630     db->aDb[1].pBt = pBt;
82631     assert( db->aDb[1].pSchema );
82632     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
82633       db->mallocFailed = 1;
82634       return 1;
82635     }
82636   }
82637   return 0;
82638 }
82639 
82640 /*
82641 ** Generate VDBE code that will verify the schema cookie and start
82642 ** a read-transaction for all named database files.
82643 **
82644 ** It is important that all schema cookies be verified and all
82645 ** read transactions be started before anything else happens in
82646 ** the VDBE program.  But this routine can be called after much other
82647 ** code has been generated.  So here is what we do:
82648 **
82649 ** The first time this routine is called, we code an OP_Goto that
82650 ** will jump to a subroutine at the end of the program.  Then we
82651 ** record every database that needs its schema verified in the
82652 ** pParse->cookieMask field.  Later, after all other code has been
82653 ** generated, the subroutine that does the cookie verifications and
82654 ** starts the transactions will be coded and the OP_Goto P2 value
82655 ** will be made to point to that subroutine.  The generation of the
82656 ** cookie verification subroutine code happens in sqlite3FinishCoding().
82657 **
82658 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
82659 ** schema on any databases.  This can be used to position the OP_Goto
82660 ** early in the code, before we know if any database tables will be used.
82661 */
82662 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
82663   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82664 
82665   if( pToplevel->cookieGoto==0 ){
82666     Vdbe *v = sqlite3GetVdbe(pToplevel);
82667     if( v==0 ) return;  /* This only happens if there was a prior error */
82668     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
82669   }
82670   if( iDb>=0 ){
82671     sqlite3 *db = pToplevel->db;
82672     yDbMask mask;
82673 
82674     assert( iDb<db->nDb );
82675     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
82676     assert( iDb<SQLITE_MAX_ATTACHED+2 );
82677     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82678     mask = ((yDbMask)1)<<iDb;
82679     if( (pToplevel->cookieMask & mask)==0 ){
82680       pToplevel->cookieMask |= mask;
82681       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
82682       if( !OMIT_TEMPDB && iDb==1 ){
82683         sqlite3OpenTempDatabase(pToplevel);
82684       }
82685     }
82686   }
82687 }
82688 
82689 /*
82690 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
82691 ** attached database. Otherwise, invoke it for the database named zDb only.
82692 */
82693 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
82694   sqlite3 *db = pParse->db;
82695   int i;
82696   for(i=0; i<db->nDb; i++){
82697     Db *pDb = &db->aDb[i];
82698     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
82699       sqlite3CodeVerifySchema(pParse, i);
82700     }
82701   }
82702 }
82703 
82704 /*
82705 ** Generate VDBE code that prepares for doing an operation that
82706 ** might change the database.
82707 **
82708 ** This routine starts a new transaction if we are not already within
82709 ** a transaction.  If we are already within a transaction, then a checkpoint
82710 ** is set if the setStatement parameter is true.  A checkpoint should
82711 ** be set for operations that might fail (due to a constraint) part of
82712 ** the way through and which will need to undo some writes without having to
82713 ** rollback the whole transaction.  For operations where all constraints
82714 ** can be checked before any changes are made to the database, it is never
82715 ** necessary to undo a write and the checkpoint should not be set.
82716 */
82717 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
82718   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82719   sqlite3CodeVerifySchema(pParse, iDb);
82720   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
82721   pToplevel->isMultiWrite |= setStatement;
82722 }
82723 
82724 /*
82725 ** Indicate that the statement currently under construction might write
82726 ** more than one entry (example: deleting one row then inserting another,
82727 ** inserting multiple rows in a table, or inserting a row and index entries.)
82728 ** If an abort occurs after some of these writes have completed, then it will
82729 ** be necessary to undo the completed writes.
82730 */
82731 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
82732   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82733   pToplevel->isMultiWrite = 1;
82734 }
82735 
82736 /*
82737 ** The code generator calls this routine if is discovers that it is
82738 ** possible to abort a statement prior to completion.  In order to
82739 ** perform this abort without corrupting the database, we need to make
82740 ** sure that the statement is protected by a statement transaction.
82741 **
82742 ** Technically, we only need to set the mayAbort flag if the
82743 ** isMultiWrite flag was previously set.  There is a time dependency
82744 ** such that the abort must occur after the multiwrite.  This makes
82745 ** some statements involving the REPLACE conflict resolution algorithm
82746 ** go a little faster.  But taking advantage of this time dependency
82747 ** makes it more difficult to prove that the code is correct (in
82748 ** particular, it prevents us from writing an effective
82749 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
82750 ** to take the safe route and skip the optimization.
82751 */
82752 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
82753   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82754   pToplevel->mayAbort = 1;
82755 }
82756 
82757 /*
82758 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
82759 ** error. The onError parameter determines which (if any) of the statement
82760 ** and/or current transaction is rolled back.
82761 */
82762 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
82763   Vdbe *v = sqlite3GetVdbe(pParse);
82764   if( onError==OE_Abort ){
82765     sqlite3MayAbort(pParse);
82766   }
82767   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
82768 }
82769 
82770 /*
82771 ** Check to see if pIndex uses the collating sequence pColl.  Return
82772 ** true if it does and false if it does not.
82773 */
82774 #ifndef SQLITE_OMIT_REINDEX
82775 static int collationMatch(const char *zColl, Index *pIndex){
82776   int i;
82777   assert( zColl!=0 );
82778   for(i=0; i<pIndex->nColumn; i++){
82779     const char *z = pIndex->azColl[i];
82780     assert( z!=0 );
82781     if( 0==sqlite3StrICmp(z, zColl) ){
82782       return 1;
82783     }
82784   }
82785   return 0;
82786 }
82787 #endif
82788 
82789 /*
82790 ** Recompute all indices of pTab that use the collating sequence pColl.
82791 ** If pColl==0 then recompute all indices of pTab.
82792 */
82793 #ifndef SQLITE_OMIT_REINDEX
82794 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
82795   Index *pIndex;              /* An index associated with pTab */
82796 
82797   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
82798     if( zColl==0 || collationMatch(zColl, pIndex) ){
82799       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
82800       sqlite3BeginWriteOperation(pParse, 0, iDb);
82801       sqlite3RefillIndex(pParse, pIndex, -1);
82802     }
82803   }
82804 }
82805 #endif
82806 
82807 /*
82808 ** Recompute all indices of all tables in all databases where the
82809 ** indices use the collating sequence pColl.  If pColl==0 then recompute
82810 ** all indices everywhere.
82811 */
82812 #ifndef SQLITE_OMIT_REINDEX
82813 static void reindexDatabases(Parse *pParse, char const *zColl){
82814   Db *pDb;                    /* A single database */
82815   int iDb;                    /* The database index number */
82816   sqlite3 *db = pParse->db;   /* The database connection */
82817   HashElem *k;                /* For looping over tables in pDb */
82818   Table *pTab;                /* A table in the database */
82819 
82820   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
82821   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
82822     assert( pDb!=0 );
82823     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
82824       pTab = (Table*)sqliteHashData(k);
82825       reindexTable(pParse, pTab, zColl);
82826     }
82827   }
82828 }
82829 #endif
82830 
82831 /*
82832 ** Generate code for the REINDEX command.
82833 **
82834 **        REINDEX                            -- 1
82835 **        REINDEX  <collation>               -- 2
82836 **        REINDEX  ?<database>.?<tablename>  -- 3
82837 **        REINDEX  ?<database>.?<indexname>  -- 4
82838 **
82839 ** Form 1 causes all indices in all attached databases to be rebuilt.
82840 ** Form 2 rebuilds all indices in all databases that use the named
82841 ** collating function.  Forms 3 and 4 rebuild the named index or all
82842 ** indices associated with the named table.
82843 */
82844 #ifndef SQLITE_OMIT_REINDEX
82845 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
82846   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
82847   char *z;                    /* Name of a table or index */
82848   const char *zDb;            /* Name of the database */
82849   Table *pTab;                /* A table in the database */
82850   Index *pIndex;              /* An index associated with pTab */
82851   int iDb;                    /* The database index number */
82852   sqlite3 *db = pParse->db;   /* The database connection */
82853   Token *pObjName;            /* Name of the table or index to be reindexed */
82854 
82855   /* Read the database schema. If an error occurs, leave an error message
82856   ** and code in pParse and return NULL. */
82857   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82858     return;
82859   }
82860 
82861   if( pName1==0 ){
82862     reindexDatabases(pParse, 0);
82863     return;
82864   }else if( NEVER(pName2==0) || pName2->z==0 ){
82865     char *zColl;
82866     assert( pName1->z );
82867     zColl = sqlite3NameFromToken(pParse->db, pName1);
82868     if( !zColl ) return;
82869     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
82870     if( pColl ){
82871       reindexDatabases(pParse, zColl);
82872       sqlite3DbFree(db, zColl);
82873       return;
82874     }
82875     sqlite3DbFree(db, zColl);
82876   }
82877   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
82878   if( iDb<0 ) return;
82879   z = sqlite3NameFromToken(db, pObjName);
82880   if( z==0 ) return;
82881   zDb = db->aDb[iDb].zName;
82882   pTab = sqlite3FindTable(db, z, zDb);
82883   if( pTab ){
82884     reindexTable(pParse, pTab, 0);
82885     sqlite3DbFree(db, z);
82886     return;
82887   }
82888   pIndex = sqlite3FindIndex(db, z, zDb);
82889   sqlite3DbFree(db, z);
82890   if( pIndex ){
82891     sqlite3BeginWriteOperation(pParse, 0, iDb);
82892     sqlite3RefillIndex(pParse, pIndex, -1);
82893     return;
82894   }
82895   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
82896 }
82897 #endif
82898 
82899 /*
82900 ** Return a dynamicly allocated KeyInfo structure that can be used
82901 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
82902 **
82903 ** If successful, a pointer to the new structure is returned. In this case
82904 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
82905 ** pointer. If an error occurs (out of memory or missing collation
82906 ** sequence), NULL is returned and the state of pParse updated to reflect
82907 ** the error.
82908 */
82909 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
82910   int i;
82911   int nCol = pIdx->nColumn;
82912   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
82913   sqlite3 *db = pParse->db;
82914   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
82915 
82916   if( pKey ){
82917     pKey->db = pParse->db;
82918     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
82919     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
82920     for(i=0; i<nCol; i++){
82921       char *zColl = pIdx->azColl[i];
82922       assert( zColl );
82923       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
82924       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
82925     }
82926     pKey->nField = (u16)nCol;
82927   }
82928 
82929   if( pParse->nErr ){
82930     sqlite3DbFree(db, pKey);
82931     pKey = 0;
82932   }
82933   return pKey;
82934 }
82935 
82936 /************** End of build.c ***********************************************/
82937 /************** Begin file callback.c ****************************************/
82938 /*
82939 ** 2005 May 23
82940 **
82941 ** The author disclaims copyright to this source code.  In place of
82942 ** a legal notice, here is a blessing:
82943 **
82944 **    May you do good and not evil.
82945 **    May you find forgiveness for yourself and forgive others.
82946 **    May you share freely, never taking more than you give.
82947 **
82948 *************************************************************************
82949 **
82950 ** This file contains functions used to access the internal hash tables
82951 ** of user defined functions and collation sequences.
82952 */
82953 
82954 
82955 /*
82956 ** Invoke the 'collation needed' callback to request a collation sequence
82957 ** in the encoding enc of name zName, length nName.
82958 */
82959 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
82960   assert( !db->xCollNeeded || !db->xCollNeeded16 );
82961   if( db->xCollNeeded ){
82962     char *zExternal = sqlite3DbStrDup(db, zName);
82963     if( !zExternal ) return;
82964     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
82965     sqlite3DbFree(db, zExternal);
82966   }
82967 #ifndef SQLITE_OMIT_UTF16
82968   if( db->xCollNeeded16 ){
82969     char const *zExternal;
82970     sqlite3_value *pTmp = sqlite3ValueNew(db);
82971     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
82972     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
82973     if( zExternal ){
82974       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
82975     }
82976     sqlite3ValueFree(pTmp);
82977   }
82978 #endif
82979 }
82980 
82981 /*
82982 ** This routine is called if the collation factory fails to deliver a
82983 ** collation function in the best encoding but there may be other versions
82984 ** of this collation function (for other text encodings) available. Use one
82985 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
82986 ** possible.
82987 */
82988 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
82989   CollSeq *pColl2;
82990   char *z = pColl->zName;
82991   int i;
82992   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
82993   for(i=0; i<3; i++){
82994     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
82995     if( pColl2->xCmp!=0 ){
82996       memcpy(pColl, pColl2, sizeof(CollSeq));
82997       pColl->xDel = 0;         /* Do not copy the destructor */
82998       return SQLITE_OK;
82999     }
83000   }
83001   return SQLITE_ERROR;
83002 }
83003 
83004 /*
83005 ** This function is responsible for invoking the collation factory callback
83006 ** or substituting a collation sequence of a different encoding when the
83007 ** requested collation sequence is not available in the desired encoding.
83008 **
83009 ** If it is not NULL, then pColl must point to the database native encoding
83010 ** collation sequence with name zName, length nName.
83011 **
83012 ** The return value is either the collation sequence to be used in database
83013 ** db for collation type name zName, length nName, or NULL, if no collation
83014 ** sequence can be found.
83015 **
83016 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
83017 */
83018 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
83019   sqlite3* db,          /* The database connection */
83020   u8 enc,               /* The desired encoding for the collating sequence */
83021   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
83022   const char *zName     /* Collating sequence name */
83023 ){
83024   CollSeq *p;
83025 
83026   p = pColl;
83027   if( !p ){
83028     p = sqlite3FindCollSeq(db, enc, zName, 0);
83029   }
83030   if( !p || !p->xCmp ){
83031     /* No collation sequence of this type for this encoding is registered.
83032     ** Call the collation factory to see if it can supply us with one.
83033     */
83034     callCollNeeded(db, enc, zName);
83035     p = sqlite3FindCollSeq(db, enc, zName, 0);
83036   }
83037   if( p && !p->xCmp && synthCollSeq(db, p) ){
83038     p = 0;
83039   }
83040   assert( !p || p->xCmp );
83041   return p;
83042 }
83043 
83044 /*
83045 ** This routine is called on a collation sequence before it is used to
83046 ** check that it is defined. An undefined collation sequence exists when
83047 ** a database is loaded that contains references to collation sequences
83048 ** that have not been defined by sqlite3_create_collation() etc.
83049 **
83050 ** If required, this routine calls the 'collation needed' callback to
83051 ** request a definition of the collating sequence. If this doesn't work,
83052 ** an equivalent collating sequence that uses a text encoding different
83053 ** from the main database is substituted, if one is available.
83054 */
83055 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
83056   if( pColl ){
83057     const char *zName = pColl->zName;
83058     sqlite3 *db = pParse->db;
83059     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
83060     if( !p ){
83061       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
83062       pParse->nErr++;
83063       return SQLITE_ERROR;
83064     }
83065     assert( p==pColl );
83066   }
83067   return SQLITE_OK;
83068 }
83069 
83070 
83071 
83072 /*
83073 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
83074 ** specified by zName and nName is not found and parameter 'create' is
83075 ** true, then create a new entry. Otherwise return NULL.
83076 **
83077 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
83078 ** array of three CollSeq structures. The first is the collation sequence
83079 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
83080 **
83081 ** Stored immediately after the three collation sequences is a copy of
83082 ** the collation sequence name. A pointer to this string is stored in
83083 ** each collation sequence structure.
83084 */
83085 static CollSeq *findCollSeqEntry(
83086   sqlite3 *db,          /* Database connection */
83087   const char *zName,    /* Name of the collating sequence */
83088   int create            /* Create a new entry if true */
83089 ){
83090   CollSeq *pColl;
83091   int nName = sqlite3Strlen30(zName);
83092   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
83093 
83094   if( 0==pColl && create ){
83095     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
83096     if( pColl ){
83097       CollSeq *pDel = 0;
83098       pColl[0].zName = (char*)&pColl[3];
83099       pColl[0].enc = SQLITE_UTF8;
83100       pColl[1].zName = (char*)&pColl[3];
83101       pColl[1].enc = SQLITE_UTF16LE;
83102       pColl[2].zName = (char*)&pColl[3];
83103       pColl[2].enc = SQLITE_UTF16BE;
83104       memcpy(pColl[0].zName, zName, nName);
83105       pColl[0].zName[nName] = 0;
83106       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
83107 
83108       /* If a malloc() failure occurred in sqlite3HashInsert(), it will
83109       ** return the pColl pointer to be deleted (because it wasn't added
83110       ** to the hash table).
83111       */
83112       assert( pDel==0 || pDel==pColl );
83113       if( pDel!=0 ){
83114         db->mallocFailed = 1;
83115         sqlite3DbFree(db, pDel);
83116         pColl = 0;
83117       }
83118     }
83119   }
83120   return pColl;
83121 }
83122 
83123 /*
83124 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
83125 ** Return the CollSeq* pointer for the collation sequence named zName
83126 ** for the encoding 'enc' from the database 'db'.
83127 **
83128 ** If the entry specified is not found and 'create' is true, then create a
83129 ** new entry.  Otherwise return NULL.
83130 **
83131 ** A separate function sqlite3LocateCollSeq() is a wrapper around
83132 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
83133 ** if necessary and generates an error message if the collating sequence
83134 ** cannot be found.
83135 **
83136 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
83137 */
83138 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
83139   sqlite3 *db,
83140   u8 enc,
83141   const char *zName,
83142   int create
83143 ){
83144   CollSeq *pColl;
83145   if( zName ){
83146     pColl = findCollSeqEntry(db, zName, create);
83147   }else{
83148     pColl = db->pDfltColl;
83149   }
83150   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
83151   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
83152   if( pColl ) pColl += enc-1;
83153   return pColl;
83154 }
83155 
83156 /* During the search for the best function definition, this procedure
83157 ** is called to test how well the function passed as the first argument
83158 ** matches the request for a function with nArg arguments in a system
83159 ** that uses encoding enc. The value returned indicates how well the
83160 ** request is matched. A higher value indicates a better match.
83161 **
83162 ** The returned value is always between 0 and 6, as follows:
83163 **
83164 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
83165 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
83166 **    encoding is requested, or vice versa.
83167 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
83168 **    requested, or vice versa.
83169 ** 3: A variable arguments function using the same text encoding.
83170 ** 4: A function with the exact number of arguments requested that
83171 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
83172 ** 5: A function with the exact number of arguments requested that
83173 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
83174 ** 6: An exact match.
83175 **
83176 */
83177 static int matchQuality(FuncDef *p, int nArg, u8 enc){
83178   int match = 0;
83179   if( p->nArg==-1 || p->nArg==nArg
83180    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
83181   ){
83182     match = 1;
83183     if( p->nArg==nArg || nArg==-1 ){
83184       match = 4;
83185     }
83186     if( enc==p->iPrefEnc ){
83187       match += 2;
83188     }
83189     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
83190              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
83191       match += 1;
83192     }
83193   }
83194   return match;
83195 }
83196 
83197 /*
83198 ** Search a FuncDefHash for a function with the given name.  Return
83199 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
83200 */
83201 static FuncDef *functionSearch(
83202   FuncDefHash *pHash,  /* Hash table to search */
83203   int h,               /* Hash of the name */
83204   const char *zFunc,   /* Name of function */
83205   int nFunc            /* Number of bytes in zFunc */
83206 ){
83207   FuncDef *p;
83208   for(p=pHash->a[h]; p; p=p->pHash){
83209     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
83210       return p;
83211     }
83212   }
83213   return 0;
83214 }
83215 
83216 /*
83217 ** Insert a new FuncDef into a FuncDefHash hash table.
83218 */
83219 SQLITE_PRIVATE void sqlite3FuncDefInsert(
83220   FuncDefHash *pHash,  /* The hash table into which to insert */
83221   FuncDef *pDef        /* The function definition to insert */
83222 ){
83223   FuncDef *pOther;
83224   int nName = sqlite3Strlen30(pDef->zName);
83225   u8 c1 = (u8)pDef->zName[0];
83226   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
83227   pOther = functionSearch(pHash, h, pDef->zName, nName);
83228   if( pOther ){
83229     assert( pOther!=pDef && pOther->pNext!=pDef );
83230     pDef->pNext = pOther->pNext;
83231     pOther->pNext = pDef;
83232   }else{
83233     pDef->pNext = 0;
83234     pDef->pHash = pHash->a[h];
83235     pHash->a[h] = pDef;
83236   }
83237 }
83238 
83239 
83240 
83241 /*
83242 ** Locate a user function given a name, a number of arguments and a flag
83243 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
83244 ** pointer to the FuncDef structure that defines that function, or return
83245 ** NULL if the function does not exist.
83246 **
83247 ** If the createFlag argument is true, then a new (blank) FuncDef
83248 ** structure is created and liked into the "db" structure if a
83249 ** no matching function previously existed.  When createFlag is true
83250 ** and the nArg parameter is -1, then only a function that accepts
83251 ** any number of arguments will be returned.
83252 **
83253 ** If createFlag is false and nArg is -1, then the first valid
83254 ** function found is returned.  A function is valid if either xFunc
83255 ** or xStep is non-zero.
83256 **
83257 ** If createFlag is false, then a function with the required name and
83258 ** number of arguments may be returned even if the eTextRep flag does not
83259 ** match that requested.
83260 */
83261 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
83262   sqlite3 *db,       /* An open database */
83263   const char *zName, /* Name of the function.  Not null-terminated */
83264   int nName,         /* Number of characters in the name */
83265   int nArg,          /* Number of arguments.  -1 means any number */
83266   u8 enc,            /* Preferred text encoding */
83267   int createFlag     /* Create new entry if true and does not otherwise exist */
83268 ){
83269   FuncDef *p;         /* Iterator variable */
83270   FuncDef *pBest = 0; /* Best match found so far */
83271   int bestScore = 0;  /* Score of best match */
83272   int h;              /* Hash value */
83273 
83274 
83275   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
83276   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
83277 
83278   /* First search for a match amongst the application-defined functions.
83279   */
83280   p = functionSearch(&db->aFunc, h, zName, nName);
83281   while( p ){
83282     int score = matchQuality(p, nArg, enc);
83283     if( score>bestScore ){
83284       pBest = p;
83285       bestScore = score;
83286     }
83287     p = p->pNext;
83288   }
83289 
83290   /* If no match is found, search the built-in functions.
83291   **
83292   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
83293   ** functions even if a prior app-defined function was found.  And give
83294   ** priority to built-in functions.
83295   **
83296   ** Except, if createFlag is true, that means that we are trying to
83297   ** install a new function.  Whatever FuncDef structure is returned it will
83298   ** have fields overwritten with new information appropriate for the
83299   ** new function.  But the FuncDefs for built-in functions are read-only.
83300   ** So we must not search for built-ins when creating a new function.
83301   */
83302   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
83303     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
83304     bestScore = 0;
83305     p = functionSearch(pHash, h, zName, nName);
83306     while( p ){
83307       int score = matchQuality(p, nArg, enc);
83308       if( score>bestScore ){
83309         pBest = p;
83310         bestScore = score;
83311       }
83312       p = p->pNext;
83313     }
83314   }
83315 
83316   /* If the createFlag parameter is true and the search did not reveal an
83317   ** exact match for the name, number of arguments and encoding, then add a
83318   ** new entry to the hash table and return it.
83319   */
83320   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
83321       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
83322     pBest->zName = (char *)&pBest[1];
83323     pBest->nArg = (u16)nArg;
83324     pBest->iPrefEnc = enc;
83325     memcpy(pBest->zName, zName, nName);
83326     pBest->zName[nName] = 0;
83327     sqlite3FuncDefInsert(&db->aFunc, pBest);
83328   }
83329 
83330   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
83331     return pBest;
83332   }
83333   return 0;
83334 }
83335 
83336 /*
83337 ** Free all resources held by the schema structure. The void* argument points
83338 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
83339 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
83340 ** of the schema hash tables).
83341 **
83342 ** The Schema.cache_size variable is not cleared.
83343 */
83344 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
83345   Hash temp1;
83346   Hash temp2;
83347   HashElem *pElem;
83348   Schema *pSchema = (Schema *)p;
83349 
83350   temp1 = pSchema->tblHash;
83351   temp2 = pSchema->trigHash;
83352   sqlite3HashInit(&pSchema->trigHash);
83353   sqlite3HashClear(&pSchema->idxHash);
83354   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
83355     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
83356   }
83357   sqlite3HashClear(&temp2);
83358   sqlite3HashInit(&pSchema->tblHash);
83359   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
83360     Table *pTab = sqliteHashData(pElem);
83361     sqlite3DeleteTable(0, pTab);
83362   }
83363   sqlite3HashClear(&temp1);
83364   sqlite3HashClear(&pSchema->fkeyHash);
83365   pSchema->pSeqTab = 0;
83366   if( pSchema->flags & DB_SchemaLoaded ){
83367     pSchema->iGeneration++;
83368     pSchema->flags &= ~DB_SchemaLoaded;
83369   }
83370 }
83371 
83372 /*
83373 ** Find and return the schema associated with a BTree.  Create
83374 ** a new one if necessary.
83375 */
83376 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
83377   Schema * p;
83378   if( pBt ){
83379     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
83380   }else{
83381     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
83382   }
83383   if( !p ){
83384     db->mallocFailed = 1;
83385   }else if ( 0==p->file_format ){
83386     sqlite3HashInit(&p->tblHash);
83387     sqlite3HashInit(&p->idxHash);
83388     sqlite3HashInit(&p->trigHash);
83389     sqlite3HashInit(&p->fkeyHash);
83390     p->enc = SQLITE_UTF8;
83391   }
83392   return p;
83393 }
83394 
83395 /************** End of callback.c ********************************************/
83396 /************** Begin file delete.c ******************************************/
83397 /*
83398 ** 2001 September 15
83399 **
83400 ** The author disclaims copyright to this source code.  In place of
83401 ** a legal notice, here is a blessing:
83402 **
83403 **    May you do good and not evil.
83404 **    May you find forgiveness for yourself and forgive others.
83405 **    May you share freely, never taking more than you give.
83406 **
83407 *************************************************************************
83408 ** This file contains C code routines that are called by the parser
83409 ** in order to generate code for DELETE FROM statements.
83410 */
83411 
83412 /*
83413 ** While a SrcList can in general represent multiple tables and subqueries
83414 ** (as in the FROM clause of a SELECT statement) in this case it contains
83415 ** the name of a single table, as one might find in an INSERT, DELETE,
83416 ** or UPDATE statement.  Look up that table in the symbol table and
83417 ** return a pointer.  Set an error message and return NULL if the table
83418 ** name is not found or if any other error occurs.
83419 **
83420 ** The following fields are initialized appropriate in pSrc:
83421 **
83422 **    pSrc->a[0].pTab       Pointer to the Table object
83423 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
83424 **
83425 */
83426 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
83427   struct SrcList_item *pItem = pSrc->a;
83428   Table *pTab;
83429   assert( pItem && pSrc->nSrc==1 );
83430   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
83431   sqlite3DeleteTable(pParse->db, pItem->pTab);
83432   pItem->pTab = pTab;
83433   if( pTab ){
83434     pTab->nRef++;
83435   }
83436   if( sqlite3IndexedByLookup(pParse, pItem) ){
83437     pTab = 0;
83438   }
83439   return pTab;
83440 }
83441 
83442 /*
83443 ** Check to make sure the given table is writable.  If it is not
83444 ** writable, generate an error message and return 1.  If it is
83445 ** writable return 0;
83446 */
83447 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
83448   /* A table is not writable under the following circumstances:
83449   **
83450   **   1) It is a virtual table and no implementation of the xUpdate method
83451   **      has been provided, or
83452   **   2) It is a system table (i.e. sqlite_master), this call is not
83453   **      part of a nested parse and writable_schema pragma has not
83454   **      been specified.
83455   **
83456   ** In either case leave an error message in pParse and return non-zero.
83457   */
83458   if( ( IsVirtual(pTab)
83459      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
83460    || ( (pTab->tabFlags & TF_Readonly)!=0
83461      && (pParse->db->flags & SQLITE_WriteSchema)==0
83462      && pParse->nested==0 )
83463   ){
83464     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
83465     return 1;
83466   }
83467 
83468 #ifndef SQLITE_OMIT_VIEW
83469   if( !viewOk && pTab->pSelect ){
83470     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
83471     return 1;
83472   }
83473 #endif
83474   return 0;
83475 }
83476 
83477 
83478 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
83479 /*
83480 ** Evaluate a view and store its result in an ephemeral table.  The
83481 ** pWhere argument is an optional WHERE clause that restricts the
83482 ** set of rows in the view that are to be added to the ephemeral table.
83483 */
83484 SQLITE_PRIVATE void sqlite3MaterializeView(
83485   Parse *pParse,       /* Parsing context */
83486   Table *pView,        /* View definition */
83487   Expr *pWhere,        /* Optional WHERE clause to be added */
83488   int iCur             /* Cursor number for ephemerial table */
83489 ){
83490   SelectDest dest;
83491   Select *pDup;
83492   sqlite3 *db = pParse->db;
83493 
83494   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
83495   if( pWhere ){
83496     SrcList *pFrom;
83497 
83498     pWhere = sqlite3ExprDup(db, pWhere, 0);
83499     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
83500     if( pFrom ){
83501       assert( pFrom->nSrc==1 );
83502       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
83503       pFrom->a[0].pSelect = pDup;
83504       assert( pFrom->a[0].pOn==0 );
83505       assert( pFrom->a[0].pUsing==0 );
83506     }else{
83507       sqlite3SelectDelete(db, pDup);
83508     }
83509     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
83510   }
83511   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
83512   sqlite3Select(pParse, pDup, &dest);
83513   sqlite3SelectDelete(db, pDup);
83514 }
83515 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
83516 
83517 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
83518 /*
83519 ** Generate an expression tree to implement the WHERE, ORDER BY,
83520 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
83521 **
83522 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
83523 **                            \__________________________/
83524 **                               pLimitWhere (pInClause)
83525 */
83526 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
83527   Parse *pParse,               /* The parser context */
83528   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
83529   Expr *pWhere,                /* The WHERE clause.  May be null */
83530   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
83531   Expr *pLimit,                /* The LIMIT clause.  May be null */
83532   Expr *pOffset,               /* The OFFSET clause.  May be null */
83533   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
83534 ){
83535   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
83536   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
83537   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
83538   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
83539   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
83540   Select *pSelect = NULL;      /* Complete SELECT tree */
83541 
83542   /* Check that there isn't an ORDER BY without a LIMIT clause.
83543   */
83544   if( pOrderBy && (pLimit == 0) ) {
83545     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
83546     pParse->parseError = 1;
83547     goto limit_where_cleanup_2;
83548   }
83549 
83550   /* We only need to generate a select expression if there
83551   ** is a limit/offset term to enforce.
83552   */
83553   if( pLimit == 0 ) {
83554     /* if pLimit is null, pOffset will always be null as well. */
83555     assert( pOffset == 0 );
83556     return pWhere;
83557   }
83558 
83559   /* Generate a select expression tree to enforce the limit/offset
83560   ** term for the DELETE or UPDATE statement.  For example:
83561   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
83562   ** becomes:
83563   **   DELETE FROM table_a WHERE rowid IN (
83564   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
83565   **   );
83566   */
83567 
83568   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
83569   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
83570   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
83571   if( pEList == 0 ) goto limit_where_cleanup_2;
83572 
83573   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
83574   ** and the SELECT subtree. */
83575   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
83576   if( pSelectSrc == 0 ) {
83577     sqlite3ExprListDelete(pParse->db, pEList);
83578     goto limit_where_cleanup_2;
83579   }
83580 
83581   /* generate the SELECT expression tree. */
83582   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
83583                              pOrderBy,0,pLimit,pOffset);
83584   if( pSelect == 0 ) return 0;
83585 
83586   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
83587   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
83588   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
83589   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
83590   if( pInClause == 0 ) goto limit_where_cleanup_1;
83591 
83592   pInClause->x.pSelect = pSelect;
83593   pInClause->flags |= EP_xIsSelect;
83594   sqlite3ExprSetHeight(pParse, pInClause);
83595   return pInClause;
83596 
83597   /* something went wrong. clean up anything allocated. */
83598 limit_where_cleanup_1:
83599   sqlite3SelectDelete(pParse->db, pSelect);
83600   return 0;
83601 
83602 limit_where_cleanup_2:
83603   sqlite3ExprDelete(pParse->db, pWhere);
83604   sqlite3ExprListDelete(pParse->db, pOrderBy);
83605   sqlite3ExprDelete(pParse->db, pLimit);
83606   sqlite3ExprDelete(pParse->db, pOffset);
83607   return 0;
83608 }
83609 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
83610 
83611 /*
83612 ** Generate code for a DELETE FROM statement.
83613 **
83614 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
83615 **                 \________/       \________________/
83616 **                  pTabList              pWhere
83617 */
83618 SQLITE_PRIVATE void sqlite3DeleteFrom(
83619   Parse *pParse,         /* The parser context */
83620   SrcList *pTabList,     /* The table from which we should delete things */
83621   Expr *pWhere           /* The WHERE clause.  May be null */
83622 ){
83623   Vdbe *v;               /* The virtual database engine */
83624   Table *pTab;           /* The table from which records will be deleted */
83625   const char *zDb;       /* Name of database holding pTab */
83626   int end, addr = 0;     /* A couple addresses of generated code */
83627   int i;                 /* Loop counter */
83628   WhereInfo *pWInfo;     /* Information about the WHERE clause */
83629   Index *pIdx;           /* For looping over indices of the table */
83630   int iCur;              /* VDBE Cursor number for pTab */
83631   sqlite3 *db;           /* Main database structure */
83632   AuthContext sContext;  /* Authorization context */
83633   NameContext sNC;       /* Name context to resolve expressions in */
83634   int iDb;               /* Database number */
83635   int memCnt = -1;       /* Memory cell used for change counting */
83636   int rcauth;            /* Value returned by authorization callback */
83637 
83638 #ifndef SQLITE_OMIT_TRIGGER
83639   int isView;                  /* True if attempting to delete from a view */
83640   Trigger *pTrigger;           /* List of table triggers, if required */
83641 #endif
83642 
83643   memset(&sContext, 0, sizeof(sContext));
83644   db = pParse->db;
83645   if( pParse->nErr || db->mallocFailed ){
83646     goto delete_from_cleanup;
83647   }
83648   assert( pTabList->nSrc==1 );
83649 
83650   /* Locate the table which we want to delete.  This table has to be
83651   ** put in an SrcList structure because some of the subroutines we
83652   ** will be calling are designed to work with multiple tables and expect
83653   ** an SrcList* parameter instead of just a Table* parameter.
83654   */
83655   pTab = sqlite3SrcListLookup(pParse, pTabList);
83656   if( pTab==0 )  goto delete_from_cleanup;
83657 
83658   /* Figure out if we have any triggers and if the table being
83659   ** deleted from is a view
83660   */
83661 #ifndef SQLITE_OMIT_TRIGGER
83662   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
83663   isView = pTab->pSelect!=0;
83664 #else
83665 # define pTrigger 0
83666 # define isView 0
83667 #endif
83668 #ifdef SQLITE_OMIT_VIEW
83669 # undef isView
83670 # define isView 0
83671 #endif
83672 
83673   /* If pTab is really a view, make sure it has been initialized.
83674   */
83675   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
83676     goto delete_from_cleanup;
83677   }
83678 
83679   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
83680     goto delete_from_cleanup;
83681   }
83682   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83683   assert( iDb<db->nDb );
83684   zDb = db->aDb[iDb].zName;
83685   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
83686   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
83687   if( rcauth==SQLITE_DENY ){
83688     goto delete_from_cleanup;
83689   }
83690   assert(!isView || pTrigger);
83691 
83692   /* Assign  cursor number to the table and all its indices.
83693   */
83694   assert( pTabList->nSrc==1 );
83695   iCur = pTabList->a[0].iCursor = pParse->nTab++;
83696   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83697     pParse->nTab++;
83698   }
83699 
83700   /* Start the view context
83701   */
83702   if( isView ){
83703     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
83704   }
83705 
83706   /* Begin generating code.
83707   */
83708   v = sqlite3GetVdbe(pParse);
83709   if( v==0 ){
83710     goto delete_from_cleanup;
83711   }
83712   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
83713   sqlite3BeginWriteOperation(pParse, 1, iDb);
83714 
83715   /* If we are trying to delete from a view, realize that view into
83716   ** a ephemeral table.
83717   */
83718 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
83719   if( isView ){
83720     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
83721   }
83722 #endif
83723 
83724   /* Resolve the column names in the WHERE clause.
83725   */
83726   memset(&sNC, 0, sizeof(sNC));
83727   sNC.pParse = pParse;
83728   sNC.pSrcList = pTabList;
83729   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
83730     goto delete_from_cleanup;
83731   }
83732 
83733   /* Initialize the counter of the number of rows deleted, if
83734   ** we are counting rows.
83735   */
83736   if( db->flags & SQLITE_CountRows ){
83737     memCnt = ++pParse->nMem;
83738     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
83739   }
83740 
83741 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
83742   /* Special case: A DELETE without a WHERE clause deletes everything.
83743   ** It is easier just to erase the whole table. Prior to version 3.6.5,
83744   ** this optimization caused the row change count (the value returned by
83745   ** API function sqlite3_count_changes) to be set incorrectly.  */
83746   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
83747    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
83748   ){
83749     assert( !isView );
83750     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
83751                       pTab->zName, P4_STATIC);
83752     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83753       assert( pIdx->pSchema==pTab->pSchema );
83754       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
83755     }
83756   }else
83757 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
83758   /* The usual case: There is a WHERE clause so we have to scan through
83759   ** the table and pick which records to delete.
83760   */
83761   {
83762     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
83763     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
83764     int regRowid;                   /* Actual register containing rowids */
83765 
83766     /* Collect rowids of every row to be deleted.
83767     */
83768     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
83769     pWInfo = sqlite3WhereBegin(
83770         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
83771     );
83772     if( pWInfo==0 ) goto delete_from_cleanup;
83773     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
83774     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
83775     if( db->flags & SQLITE_CountRows ){
83776       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
83777     }
83778     sqlite3WhereEnd(pWInfo);
83779 
83780     /* Delete every item whose key was written to the list during the
83781     ** database scan.  We have to delete items after the scan is complete
83782     ** because deleting an item can change the scan order.  */
83783     end = sqlite3VdbeMakeLabel(v);
83784 
83785     /* Unless this is a view, open cursors for the table we are
83786     ** deleting from and all its indices. If this is a view, then the
83787     ** only effect this statement has is to fire the INSTEAD OF
83788     ** triggers.  */
83789     if( !isView ){
83790       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
83791     }
83792 
83793     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
83794 
83795     /* Delete the row */
83796 #ifndef SQLITE_OMIT_VIRTUALTABLE
83797     if( IsVirtual(pTab) ){
83798       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
83799       sqlite3VtabMakeWritable(pParse, pTab);
83800       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
83801       sqlite3VdbeChangeP5(v, OE_Abort);
83802       sqlite3MayAbort(pParse);
83803     }else
83804 #endif
83805     {
83806       int count = (pParse->nested==0);    /* True to count changes */
83807       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
83808     }
83809 
83810     /* End of the delete loop */
83811     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
83812     sqlite3VdbeResolveLabel(v, end);
83813 
83814     /* Close the cursors open on the table and its indexes. */
83815     if( !isView && !IsVirtual(pTab) ){
83816       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
83817         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
83818       }
83819       sqlite3VdbeAddOp1(v, OP_Close, iCur);
83820     }
83821   }
83822 
83823   /* Update the sqlite_sequence table by storing the content of the
83824   ** maximum rowid counter values recorded while inserting into
83825   ** autoincrement tables.
83826   */
83827   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
83828     sqlite3AutoincrementEnd(pParse);
83829   }
83830 
83831   /* Return the number of rows that were deleted. If this routine is
83832   ** generating code because of a call to sqlite3NestedParse(), do not
83833   ** invoke the callback function.
83834   */
83835   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
83836     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
83837     sqlite3VdbeSetNumCols(v, 1);
83838     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
83839   }
83840 
83841 delete_from_cleanup:
83842   sqlite3AuthContextPop(&sContext);
83843   sqlite3SrcListDelete(db, pTabList);
83844   sqlite3ExprDelete(db, pWhere);
83845   return;
83846 }
83847 /* Make sure "isView" and other macros defined above are undefined. Otherwise
83848 ** thely may interfere with compilation of other functions in this file
83849 ** (or in another file, if this file becomes part of the amalgamation).  */
83850 #ifdef isView
83851  #undef isView
83852 #endif
83853 #ifdef pTrigger
83854  #undef pTrigger
83855 #endif
83856 
83857 /*
83858 ** This routine generates VDBE code that causes a single row of a
83859 ** single table to be deleted.
83860 **
83861 ** The VDBE must be in a particular state when this routine is called.
83862 ** These are the requirements:
83863 **
83864 **   1.  A read/write cursor pointing to pTab, the table containing the row
83865 **       to be deleted, must be opened as cursor number $iCur.
83866 **
83867 **   2.  Read/write cursors for all indices of pTab must be open as
83868 **       cursor number base+i for the i-th index.
83869 **
83870 **   3.  The record number of the row to be deleted must be stored in
83871 **       memory cell iRowid.
83872 **
83873 ** This routine generates code to remove both the table record and all
83874 ** index entries that point to that record.
83875 */
83876 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
83877   Parse *pParse,     /* Parsing context */
83878   Table *pTab,       /* Table containing the row to be deleted */
83879   int iCur,          /* Cursor number for the table */
83880   int iRowid,        /* Memory cell that contains the rowid to delete */
83881   int count,         /* If non-zero, increment the row change counter */
83882   Trigger *pTrigger, /* List of triggers to (potentially) fire */
83883   int onconf         /* Default ON CONFLICT policy for triggers */
83884 ){
83885   Vdbe *v = pParse->pVdbe;        /* Vdbe */
83886   int iOld = 0;                   /* First register in OLD.* array */
83887   int iLabel;                     /* Label resolved to end of generated code */
83888 
83889   /* Vdbe is guaranteed to have been allocated by this stage. */
83890   assert( v );
83891 
83892   /* Seek cursor iCur to the row to delete. If this row no longer exists
83893   ** (this can happen if a trigger program has already deleted it), do
83894   ** not attempt to delete it or fire any DELETE triggers.  */
83895   iLabel = sqlite3VdbeMakeLabel(v);
83896   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
83897 
83898   /* If there are any triggers to fire, allocate a range of registers to
83899   ** use for the old.* references in the triggers.  */
83900   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
83901     u32 mask;                     /* Mask of OLD.* columns in use */
83902     int iCol;                     /* Iterator used while populating OLD.* */
83903 
83904     /* TODO: Could use temporary registers here. Also could attempt to
83905     ** avoid copying the contents of the rowid register.  */
83906     mask = sqlite3TriggerColmask(
83907         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
83908     );
83909     mask |= sqlite3FkOldmask(pParse, pTab);
83910     iOld = pParse->nMem+1;
83911     pParse->nMem += (1 + pTab->nCol);
83912 
83913     /* Populate the OLD.* pseudo-table register array. These values will be
83914     ** used by any BEFORE and AFTER triggers that exist.  */
83915     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
83916     for(iCol=0; iCol<pTab->nCol; iCol++){
83917       if( mask==0xffffffff || mask&(1<<iCol) ){
83918         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
83919       }
83920     }
83921 
83922     /* Invoke BEFORE DELETE trigger programs. */
83923     sqlite3CodeRowTrigger(pParse, pTrigger,
83924         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
83925     );
83926 
83927     /* Seek the cursor to the row to be deleted again. It may be that
83928     ** the BEFORE triggers coded above have already removed the row
83929     ** being deleted. Do not attempt to delete the row a second time, and
83930     ** do not fire AFTER triggers.  */
83931     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
83932 
83933     /* Do FK processing. This call checks that any FK constraints that
83934     ** refer to this table (i.e. constraints attached to other tables)
83935     ** are not violated by deleting this row.  */
83936     sqlite3FkCheck(pParse, pTab, iOld, 0);
83937   }
83938 
83939   /* Delete the index and table entries. Skip this step if pTab is really
83940   ** a view (in which case the only effect of the DELETE statement is to
83941   ** fire the INSTEAD OF triggers).  */
83942   if( pTab->pSelect==0 ){
83943     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
83944     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
83945     if( count ){
83946       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
83947     }
83948   }
83949 
83950   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
83951   ** handle rows (possibly in other tables) that refer via a foreign key
83952   ** to the row just deleted. */
83953   sqlite3FkActions(pParse, pTab, 0, iOld);
83954 
83955   /* Invoke AFTER DELETE trigger programs. */
83956   sqlite3CodeRowTrigger(pParse, pTrigger,
83957       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
83958   );
83959 
83960   /* Jump here if the row had already been deleted before any BEFORE
83961   ** trigger programs were invoked. Or if a trigger program throws a
83962   ** RAISE(IGNORE) exception.  */
83963   sqlite3VdbeResolveLabel(v, iLabel);
83964 }
83965 
83966 /*
83967 ** This routine generates VDBE code that causes the deletion of all
83968 ** index entries associated with a single row of a single table.
83969 **
83970 ** The VDBE must be in a particular state when this routine is called.
83971 ** These are the requirements:
83972 **
83973 **   1.  A read/write cursor pointing to pTab, the table containing the row
83974 **       to be deleted, must be opened as cursor number "iCur".
83975 **
83976 **   2.  Read/write cursors for all indices of pTab must be open as
83977 **       cursor number iCur+i for the i-th index.
83978 **
83979 **   3.  The "iCur" cursor must be pointing to the row that is to be
83980 **       deleted.
83981 */
83982 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
83983   Parse *pParse,     /* Parsing and code generating context */
83984   Table *pTab,       /* Table containing the row to be deleted */
83985   int iCur,          /* Cursor number for the table */
83986   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
83987 ){
83988   int i;
83989   Index *pIdx;
83990   int r1;
83991 
83992   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
83993     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
83994     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
83995     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
83996   }
83997 }
83998 
83999 /*
84000 ** Generate code that will assemble an index key and put it in register
84001 ** regOut.  The key with be for index pIdx which is an index on pTab.
84002 ** iCur is the index of a cursor open on the pTab table and pointing to
84003 ** the entry that needs indexing.
84004 **
84005 ** Return a register number which is the first in a block of
84006 ** registers that holds the elements of the index key.  The
84007 ** block of registers has already been deallocated by the time
84008 ** this routine returns.
84009 */
84010 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
84011   Parse *pParse,     /* Parsing context */
84012   Index *pIdx,       /* The index for which to generate a key */
84013   int iCur,          /* Cursor number for the pIdx->pTable table */
84014   int regOut,        /* Write the new index key to this register */
84015   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
84016 ){
84017   Vdbe *v = pParse->pVdbe;
84018   int j;
84019   Table *pTab = pIdx->pTable;
84020   int regBase;
84021   int nCol;
84022 
84023   nCol = pIdx->nColumn;
84024   regBase = sqlite3GetTempRange(pParse, nCol+1);
84025   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
84026   for(j=0; j<nCol; j++){
84027     int idx = pIdx->aiColumn[j];
84028     if( idx==pTab->iPKey ){
84029       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
84030     }else{
84031       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
84032       sqlite3ColumnDefault(v, pTab, idx, -1);
84033     }
84034   }
84035   if( doMakeRec ){
84036     const char *zAff;
84037     if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
84038       zAff = 0;
84039     }else{
84040       zAff = sqlite3IndexAffinityStr(v, pIdx);
84041     }
84042     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
84043     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
84044   }
84045   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
84046   return regBase;
84047 }
84048 
84049 /************** End of delete.c **********************************************/
84050 /************** Begin file func.c ********************************************/
84051 /*
84052 ** 2002 February 23
84053 **
84054 ** The author disclaims copyright to this source code.  In place of
84055 ** a legal notice, here is a blessing:
84056 **
84057 **    May you do good and not evil.
84058 **    May you find forgiveness for yourself and forgive others.
84059 **    May you share freely, never taking more than you give.
84060 **
84061 *************************************************************************
84062 ** This file contains the C functions that implement various SQL
84063 ** functions of SQLite.
84064 **
84065 ** There is only one exported symbol in this file - the function
84066 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
84067 ** All other code has file scope.
84068 */
84069 /* #include <stdlib.h> */
84070 /* #include <assert.h> */
84071 
84072 /*
84073 ** Return the collating function associated with a function.
84074 */
84075 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
84076   return context->pColl;
84077 }
84078 
84079 /*
84080 ** Implementation of the non-aggregate min() and max() functions
84081 */
84082 static void minmaxFunc(
84083   sqlite3_context *context,
84084   int argc,
84085   sqlite3_value **argv
84086 ){
84087   int i;
84088   int mask;    /* 0 for min() or 0xffffffff for max() */
84089   int iBest;
84090   CollSeq *pColl;
84091 
84092   assert( argc>1 );
84093   mask = sqlite3_user_data(context)==0 ? 0 : -1;
84094   pColl = sqlite3GetFuncCollSeq(context);
84095   assert( pColl );
84096   assert( mask==-1 || mask==0 );
84097   iBest = 0;
84098   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
84099   for(i=1; i<argc; i++){
84100     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
84101     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
84102       testcase( mask==0 );
84103       iBest = i;
84104     }
84105   }
84106   sqlite3_result_value(context, argv[iBest]);
84107 }
84108 
84109 /*
84110 ** Return the type of the argument.
84111 */
84112 static void typeofFunc(
84113   sqlite3_context *context,
84114   int NotUsed,
84115   sqlite3_value **argv
84116 ){
84117   const char *z = 0;
84118   UNUSED_PARAMETER(NotUsed);
84119   switch( sqlite3_value_type(argv[0]) ){
84120     case SQLITE_INTEGER: z = "integer"; break;
84121     case SQLITE_TEXT:    z = "text";    break;
84122     case SQLITE_FLOAT:   z = "real";    break;
84123     case SQLITE_BLOB:    z = "blob";    break;
84124     default:             z = "null";    break;
84125   }
84126   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
84127 }
84128 
84129 
84130 /*
84131 ** Implementation of the length() function
84132 */
84133 static void lengthFunc(
84134   sqlite3_context *context,
84135   int argc,
84136   sqlite3_value **argv
84137 ){
84138   int len;
84139 
84140   assert( argc==1 );
84141   UNUSED_PARAMETER(argc);
84142   switch( sqlite3_value_type(argv[0]) ){
84143     case SQLITE_BLOB:
84144     case SQLITE_INTEGER:
84145     case SQLITE_FLOAT: {
84146       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
84147       break;
84148     }
84149     case SQLITE_TEXT: {
84150       const unsigned char *z = sqlite3_value_text(argv[0]);
84151       if( z==0 ) return;
84152       len = 0;
84153       while( *z ){
84154         len++;
84155         SQLITE_SKIP_UTF8(z);
84156       }
84157       sqlite3_result_int(context, len);
84158       break;
84159     }
84160     default: {
84161       sqlite3_result_null(context);
84162       break;
84163     }
84164   }
84165 }
84166 
84167 /*
84168 ** Implementation of the abs() function.
84169 **
84170 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
84171 ** the numeric argument X.
84172 */
84173 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84174   assert( argc==1 );
84175   UNUSED_PARAMETER(argc);
84176   switch( sqlite3_value_type(argv[0]) ){
84177     case SQLITE_INTEGER: {
84178       i64 iVal = sqlite3_value_int64(argv[0]);
84179       if( iVal<0 ){
84180         if( (iVal<<1)==0 ){
84181           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
84182           ** abs(X) throws an integer overflow error since there is no
84183           ** equivalent positive 64-bit two complement value. */
84184           sqlite3_result_error(context, "integer overflow", -1);
84185           return;
84186         }
84187         iVal = -iVal;
84188       }
84189       sqlite3_result_int64(context, iVal);
84190       break;
84191     }
84192     case SQLITE_NULL: {
84193       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
84194       sqlite3_result_null(context);
84195       break;
84196     }
84197     default: {
84198       /* Because sqlite3_value_double() returns 0.0 if the argument is not
84199       ** something that can be converted into a number, we have:
84200       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
84201       ** cannot be converted to a numeric value.
84202       */
84203       double rVal = sqlite3_value_double(argv[0]);
84204       if( rVal<0 ) rVal = -rVal;
84205       sqlite3_result_double(context, rVal);
84206       break;
84207     }
84208   }
84209 }
84210 
84211 /*
84212 ** Implementation of the substr() function.
84213 **
84214 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
84215 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
84216 ** of x.  If x is text, then we actually count UTF-8 characters.
84217 ** If x is a blob, then we count bytes.
84218 **
84219 ** If p1 is negative, then we begin abs(p1) from the end of x[].
84220 **
84221 ** If p2 is negative, return the p2 characters preceeding p1.
84222 */
84223 static void substrFunc(
84224   sqlite3_context *context,
84225   int argc,
84226   sqlite3_value **argv
84227 ){
84228   const unsigned char *z;
84229   const unsigned char *z2;
84230   int len;
84231   int p0type;
84232   i64 p1, p2;
84233   int negP2 = 0;
84234 
84235   assert( argc==3 || argc==2 );
84236   if( sqlite3_value_type(argv[1])==SQLITE_NULL
84237    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
84238   ){
84239     return;
84240   }
84241   p0type = sqlite3_value_type(argv[0]);
84242   p1 = sqlite3_value_int(argv[1]);
84243   if( p0type==SQLITE_BLOB ){
84244     len = sqlite3_value_bytes(argv[0]);
84245     z = sqlite3_value_blob(argv[0]);
84246     if( z==0 ) return;
84247     assert( len==sqlite3_value_bytes(argv[0]) );
84248   }else{
84249     z = sqlite3_value_text(argv[0]);
84250     if( z==0 ) return;
84251     len = 0;
84252     if( p1<0 ){
84253       for(z2=z; *z2; len++){
84254         SQLITE_SKIP_UTF8(z2);
84255       }
84256     }
84257   }
84258   if( argc==3 ){
84259     p2 = sqlite3_value_int(argv[2]);
84260     if( p2<0 ){
84261       p2 = -p2;
84262       negP2 = 1;
84263     }
84264   }else{
84265     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
84266   }
84267   if( p1<0 ){
84268     p1 += len;
84269     if( p1<0 ){
84270       p2 += p1;
84271       if( p2<0 ) p2 = 0;
84272       p1 = 0;
84273     }
84274   }else if( p1>0 ){
84275     p1--;
84276   }else if( p2>0 ){
84277     p2--;
84278   }
84279   if( negP2 ){
84280     p1 -= p2;
84281     if( p1<0 ){
84282       p2 += p1;
84283       p1 = 0;
84284     }
84285   }
84286   assert( p1>=0 && p2>=0 );
84287   if( p0type!=SQLITE_BLOB ){
84288     while( *z && p1 ){
84289       SQLITE_SKIP_UTF8(z);
84290       p1--;
84291     }
84292     for(z2=z; *z2 && p2; p2--){
84293       SQLITE_SKIP_UTF8(z2);
84294     }
84295     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
84296   }else{
84297     if( p1+p2>len ){
84298       p2 = len-p1;
84299       if( p2<0 ) p2 = 0;
84300     }
84301     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
84302   }
84303 }
84304 
84305 /*
84306 ** Implementation of the round() function
84307 */
84308 #ifndef SQLITE_OMIT_FLOATING_POINT
84309 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84310   int n = 0;
84311   double r;
84312   char *zBuf;
84313   assert( argc==1 || argc==2 );
84314   if( argc==2 ){
84315     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
84316     n = sqlite3_value_int(argv[1]);
84317     if( n>30 ) n = 30;
84318     if( n<0 ) n = 0;
84319   }
84320   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
84321   r = sqlite3_value_double(argv[0]);
84322   /* If Y==0 and X will fit in a 64-bit int,
84323   ** handle the rounding directly,
84324   ** otherwise use printf.
84325   */
84326   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
84327     r = (double)((sqlite_int64)(r+0.5));
84328   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
84329     r = -(double)((sqlite_int64)((-r)+0.5));
84330   }else{
84331     zBuf = sqlite3_mprintf("%.*f",n,r);
84332     if( zBuf==0 ){
84333       sqlite3_result_error_nomem(context);
84334       return;
84335     }
84336     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
84337     sqlite3_free(zBuf);
84338   }
84339   sqlite3_result_double(context, r);
84340 }
84341 #endif
84342 
84343 /*
84344 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
84345 ** allocation fails, call sqlite3_result_error_nomem() to notify
84346 ** the database handle that malloc() has failed and return NULL.
84347 ** If nByte is larger than the maximum string or blob length, then
84348 ** raise an SQLITE_TOOBIG exception and return NULL.
84349 */
84350 static void *contextMalloc(sqlite3_context *context, i64 nByte){
84351   char *z;
84352   sqlite3 *db = sqlite3_context_db_handle(context);
84353   assert( nByte>0 );
84354   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
84355   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
84356   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
84357     sqlite3_result_error_toobig(context);
84358     z = 0;
84359   }else{
84360     z = sqlite3Malloc((int)nByte);
84361     if( !z ){
84362       sqlite3_result_error_nomem(context);
84363     }
84364   }
84365   return z;
84366 }
84367 
84368 /*
84369 ** Implementation of the upper() and lower() SQL functions.
84370 */
84371 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84372   char *z1;
84373   const char *z2;
84374   int i, n;
84375   UNUSED_PARAMETER(argc);
84376   z2 = (char*)sqlite3_value_text(argv[0]);
84377   n = sqlite3_value_bytes(argv[0]);
84378   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
84379   assert( z2==(char*)sqlite3_value_text(argv[0]) );
84380   if( z2 ){
84381     z1 = contextMalloc(context, ((i64)n)+1);
84382     if( z1 ){
84383       memcpy(z1, z2, n+1);
84384       for(i=0; z1[i]; i++){
84385         z1[i] = (char)sqlite3Toupper(z1[i]);
84386       }
84387       sqlite3_result_text(context, z1, -1, sqlite3_free);
84388     }
84389   }
84390 }
84391 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84392   u8 *z1;
84393   const char *z2;
84394   int i, n;
84395   UNUSED_PARAMETER(argc);
84396   z2 = (char*)sqlite3_value_text(argv[0]);
84397   n = sqlite3_value_bytes(argv[0]);
84398   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
84399   assert( z2==(char*)sqlite3_value_text(argv[0]) );
84400   if( z2 ){
84401     z1 = contextMalloc(context, ((i64)n)+1);
84402     if( z1 ){
84403       memcpy(z1, z2, n+1);
84404       for(i=0; z1[i]; i++){
84405         z1[i] = sqlite3Tolower(z1[i]);
84406       }
84407       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
84408     }
84409   }
84410 }
84411 
84412 
84413 #if 0  /* This function is never used. */
84414 /*
84415 ** The COALESCE() and IFNULL() functions used to be implemented as shown
84416 ** here.  But now they are implemented as VDBE code so that unused arguments
84417 ** do not have to be computed.  This legacy implementation is retained as
84418 ** comment.
84419 */
84420 /*
84421 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
84422 ** All three do the same thing.  They return the first non-NULL
84423 ** argument.
84424 */
84425 static void ifnullFunc(
84426   sqlite3_context *context,
84427   int argc,
84428   sqlite3_value **argv
84429 ){
84430   int i;
84431   for(i=0; i<argc; i++){
84432     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
84433       sqlite3_result_value(context, argv[i]);
84434       break;
84435     }
84436   }
84437 }
84438 #endif /* NOT USED */
84439 #define ifnullFunc versionFunc   /* Substitute function - never called */
84440 
84441 /*
84442 ** Implementation of random().  Return a random integer.
84443 */
84444 static void randomFunc(
84445   sqlite3_context *context,
84446   int NotUsed,
84447   sqlite3_value **NotUsed2
84448 ){
84449   sqlite_int64 r;
84450   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84451   sqlite3_randomness(sizeof(r), &r);
84452   if( r<0 ){
84453     /* We need to prevent a random number of 0x8000000000000000
84454     ** (or -9223372036854775808) since when you do abs() of that
84455     ** number of you get the same value back again.  To do this
84456     ** in a way that is testable, mask the sign bit off of negative
84457     ** values, resulting in a positive value.  Then take the
84458     ** 2s complement of that positive value.  The end result can
84459     ** therefore be no less than -9223372036854775807.
84460     */
84461     r = -(r ^ (((sqlite3_int64)1)<<63));
84462   }
84463   sqlite3_result_int64(context, r);
84464 }
84465 
84466 /*
84467 ** Implementation of randomblob(N).  Return a random blob
84468 ** that is N bytes long.
84469 */
84470 static void randomBlob(
84471   sqlite3_context *context,
84472   int argc,
84473   sqlite3_value **argv
84474 ){
84475   int n;
84476   unsigned char *p;
84477   assert( argc==1 );
84478   UNUSED_PARAMETER(argc);
84479   n = sqlite3_value_int(argv[0]);
84480   if( n<1 ){
84481     n = 1;
84482   }
84483   p = contextMalloc(context, n);
84484   if( p ){
84485     sqlite3_randomness(n, p);
84486     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
84487   }
84488 }
84489 
84490 /*
84491 ** Implementation of the last_insert_rowid() SQL function.  The return
84492 ** value is the same as the sqlite3_last_insert_rowid() API function.
84493 */
84494 static void last_insert_rowid(
84495   sqlite3_context *context,
84496   int NotUsed,
84497   sqlite3_value **NotUsed2
84498 ){
84499   sqlite3 *db = sqlite3_context_db_handle(context);
84500   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84501   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
84502   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
84503   ** function. */
84504   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
84505 }
84506 
84507 /*
84508 ** Implementation of the changes() SQL function.
84509 **
84510 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
84511 ** around the sqlite3_changes() C/C++ function and hence follows the same
84512 ** rules for counting changes.
84513 */
84514 static void changes(
84515   sqlite3_context *context,
84516   int NotUsed,
84517   sqlite3_value **NotUsed2
84518 ){
84519   sqlite3 *db = sqlite3_context_db_handle(context);
84520   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84521   sqlite3_result_int(context, sqlite3_changes(db));
84522 }
84523 
84524 /*
84525 ** Implementation of the total_changes() SQL function.  The return value is
84526 ** the same as the sqlite3_total_changes() API function.
84527 */
84528 static void total_changes(
84529   sqlite3_context *context,
84530   int NotUsed,
84531   sqlite3_value **NotUsed2
84532 ){
84533   sqlite3 *db = sqlite3_context_db_handle(context);
84534   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84535   /* IMP: R-52756-41993 This function is a wrapper around the
84536   ** sqlite3_total_changes() C/C++ interface. */
84537   sqlite3_result_int(context, sqlite3_total_changes(db));
84538 }
84539 
84540 /*
84541 ** A structure defining how to do GLOB-style comparisons.
84542 */
84543 struct compareInfo {
84544   u8 matchAll;
84545   u8 matchOne;
84546   u8 matchSet;
84547   u8 noCase;
84548 };
84549 
84550 /*
84551 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
84552 ** character is exactly one byte in size.  Also, all characters are
84553 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
84554 ** whereas only characters less than 0x80 do in ASCII.
84555 */
84556 #if defined(SQLITE_EBCDIC)
84557 # define sqlite3Utf8Read(A,C)  (*(A++))
84558 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
84559 #else
84560 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
84561 #endif
84562 
84563 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
84564 /* The correct SQL-92 behavior is for the LIKE operator to ignore
84565 ** case.  Thus  'a' LIKE 'A' would be true. */
84566 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
84567 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
84568 ** is case sensitive causing 'a' LIKE 'A' to be false */
84569 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
84570 
84571 /*
84572 ** Compare two UTF-8 strings for equality where the first string can
84573 ** potentially be a "glob" expression.  Return true (1) if they
84574 ** are the same and false (0) if they are different.
84575 **
84576 ** Globbing rules:
84577 **
84578 **      '*'       Matches any sequence of zero or more characters.
84579 **
84580 **      '?'       Matches exactly one character.
84581 **
84582 **     [...]      Matches one character from the enclosed list of
84583 **                characters.
84584 **
84585 **     [^...]     Matches one character not in the enclosed list.
84586 **
84587 ** With the [...] and [^...] matching, a ']' character can be included
84588 ** in the list by making it the first character after '[' or '^'.  A
84589 ** range of characters can be specified using '-'.  Example:
84590 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
84591 ** it the last character in the list.
84592 **
84593 ** This routine is usually quick, but can be N**2 in the worst case.
84594 **
84595 ** Hints: to match '*' or '?', put them in "[]".  Like this:
84596 **
84597 **         abc[*]xyz        Matches "abc*xyz" only
84598 */
84599 static int patternCompare(
84600   const u8 *zPattern,              /* The glob pattern */
84601   const u8 *zString,               /* The string to compare against the glob */
84602   const struct compareInfo *pInfo, /* Information about how to do the compare */
84603   u32 esc                          /* The escape character */
84604 ){
84605   u32 c, c2;
84606   int invert;
84607   int seen;
84608   u8 matchOne = pInfo->matchOne;
84609   u8 matchAll = pInfo->matchAll;
84610   u8 matchSet = pInfo->matchSet;
84611   u8 noCase = pInfo->noCase;
84612   int prevEscape = 0;     /* True if the previous character was 'escape' */
84613 
84614   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
84615     if( !prevEscape && c==matchAll ){
84616       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
84617                || c == matchOne ){
84618         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
84619           return 0;
84620         }
84621       }
84622       if( c==0 ){
84623         return 1;
84624       }else if( c==esc ){
84625         c = sqlite3Utf8Read(zPattern, &zPattern);
84626         if( c==0 ){
84627           return 0;
84628         }
84629       }else if( c==matchSet ){
84630         assert( esc==0 );         /* This is GLOB, not LIKE */
84631         assert( matchSet<0x80 );  /* '[' is a single-byte character */
84632         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
84633           SQLITE_SKIP_UTF8(zString);
84634         }
84635         return *zString!=0;
84636       }
84637       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
84638         if( noCase ){
84639           GlogUpperToLower(c2);
84640           GlogUpperToLower(c);
84641           while( c2 != 0 && c2 != c ){
84642             c2 = sqlite3Utf8Read(zString, &zString);
84643             GlogUpperToLower(c2);
84644           }
84645         }else{
84646           while( c2 != 0 && c2 != c ){
84647             c2 = sqlite3Utf8Read(zString, &zString);
84648           }
84649         }
84650         if( c2==0 ) return 0;
84651         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
84652       }
84653       return 0;
84654     }else if( !prevEscape && c==matchOne ){
84655       if( sqlite3Utf8Read(zString, &zString)==0 ){
84656         return 0;
84657       }
84658     }else if( c==matchSet ){
84659       u32 prior_c = 0;
84660       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
84661       seen = 0;
84662       invert = 0;
84663       c = sqlite3Utf8Read(zString, &zString);
84664       if( c==0 ) return 0;
84665       c2 = sqlite3Utf8Read(zPattern, &zPattern);
84666       if( c2=='^' ){
84667         invert = 1;
84668         c2 = sqlite3Utf8Read(zPattern, &zPattern);
84669       }
84670       if( c2==']' ){
84671         if( c==']' ) seen = 1;
84672         c2 = sqlite3Utf8Read(zPattern, &zPattern);
84673       }
84674       while( c2 && c2!=']' ){
84675         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
84676           c2 = sqlite3Utf8Read(zPattern, &zPattern);
84677           if( c>=prior_c && c<=c2 ) seen = 1;
84678           prior_c = 0;
84679         }else{
84680           if( c==c2 ){
84681             seen = 1;
84682           }
84683           prior_c = c2;
84684         }
84685         c2 = sqlite3Utf8Read(zPattern, &zPattern);
84686       }
84687       if( c2==0 || (seen ^ invert)==0 ){
84688         return 0;
84689       }
84690     }else if( esc==c && !prevEscape ){
84691       prevEscape = 1;
84692     }else{
84693       c2 = sqlite3Utf8Read(zString, &zString);
84694       if( noCase ){
84695         GlogUpperToLower(c);
84696         GlogUpperToLower(c2);
84697       }
84698       if( c!=c2 ){
84699         return 0;
84700       }
84701       prevEscape = 0;
84702     }
84703   }
84704   return *zString==0;
84705 }
84706 
84707 /*
84708 ** Count the number of times that the LIKE operator (or GLOB which is
84709 ** just a variation of LIKE) gets called.  This is used for testing
84710 ** only.
84711 */
84712 #ifdef SQLITE_TEST
84713 SQLITE_API int sqlite3_like_count = 0;
84714 #endif
84715 
84716 
84717 /*
84718 ** Implementation of the like() SQL function.  This function implements
84719 ** the build-in LIKE operator.  The first argument to the function is the
84720 ** pattern and the second argument is the string.  So, the SQL statements:
84721 **
84722 **       A LIKE B
84723 **
84724 ** is implemented as like(B,A).
84725 **
84726 ** This same function (with a different compareInfo structure) computes
84727 ** the GLOB operator.
84728 */
84729 static void likeFunc(
84730   sqlite3_context *context,
84731   int argc,
84732   sqlite3_value **argv
84733 ){
84734   const unsigned char *zA, *zB;
84735   u32 escape = 0;
84736   int nPat;
84737   sqlite3 *db = sqlite3_context_db_handle(context);
84738 
84739   zB = sqlite3_value_text(argv[0]);
84740   zA = sqlite3_value_text(argv[1]);
84741 
84742   /* Limit the length of the LIKE or GLOB pattern to avoid problems
84743   ** of deep recursion and N*N behavior in patternCompare().
84744   */
84745   nPat = sqlite3_value_bytes(argv[0]);
84746   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
84747   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
84748   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
84749     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
84750     return;
84751   }
84752   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
84753 
84754   if( argc==3 ){
84755     /* The escape character string must consist of a single UTF-8 character.
84756     ** Otherwise, return an error.
84757     */
84758     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
84759     if( zEsc==0 ) return;
84760     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
84761       sqlite3_result_error(context,
84762           "ESCAPE expression must be a single character", -1);
84763       return;
84764     }
84765     escape = sqlite3Utf8Read(zEsc, &zEsc);
84766   }
84767   if( zA && zB ){
84768     struct compareInfo *pInfo = sqlite3_user_data(context);
84769 #ifdef SQLITE_TEST
84770     sqlite3_like_count++;
84771 #endif
84772 
84773     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
84774   }
84775 }
84776 
84777 /*
84778 ** Implementation of the NULLIF(x,y) function.  The result is the first
84779 ** argument if the arguments are different.  The result is NULL if the
84780 ** arguments are equal to each other.
84781 */
84782 static void nullifFunc(
84783   sqlite3_context *context,
84784   int NotUsed,
84785   sqlite3_value **argv
84786 ){
84787   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
84788   UNUSED_PARAMETER(NotUsed);
84789   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
84790     sqlite3_result_value(context, argv[0]);
84791   }
84792 }
84793 
84794 /*
84795 ** Implementation of the sqlite_version() function.  The result is the version
84796 ** of the SQLite library that is running.
84797 */
84798 static void versionFunc(
84799   sqlite3_context *context,
84800   int NotUsed,
84801   sqlite3_value **NotUsed2
84802 ){
84803   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84804   /* IMP: R-48699-48617 This function is an SQL wrapper around the
84805   ** sqlite3_libversion() C-interface. */
84806   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
84807 }
84808 
84809 /*
84810 ** Implementation of the sqlite_source_id() function. The result is a string
84811 ** that identifies the particular version of the source code used to build
84812 ** SQLite.
84813 */
84814 static void sourceidFunc(
84815   sqlite3_context *context,
84816   int NotUsed,
84817   sqlite3_value **NotUsed2
84818 ){
84819   UNUSED_PARAMETER2(NotUsed, NotUsed2);
84820   /* IMP: R-24470-31136 This function is an SQL wrapper around the
84821   ** sqlite3_sourceid() C interface. */
84822   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
84823 }
84824 
84825 /*
84826 ** Implementation of the sqlite_log() function.  This is a wrapper around
84827 ** sqlite3_log().  The return value is NULL.  The function exists purely for
84828 ** its side-effects.
84829 */
84830 static void errlogFunc(
84831   sqlite3_context *context,
84832   int argc,
84833   sqlite3_value **argv
84834 ){
84835   UNUSED_PARAMETER(argc);
84836   UNUSED_PARAMETER(context);
84837   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
84838 }
84839 
84840 /*
84841 ** Implementation of the sqlite_compileoption_used() function.
84842 ** The result is an integer that identifies if the compiler option
84843 ** was used to build SQLite.
84844 */
84845 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
84846 static void compileoptionusedFunc(
84847   sqlite3_context *context,
84848   int argc,
84849   sqlite3_value **argv
84850 ){
84851   const char *zOptName;
84852   assert( argc==1 );
84853   UNUSED_PARAMETER(argc);
84854   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
84855   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
84856   ** function.
84857   */
84858   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
84859     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
84860   }
84861 }
84862 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
84863 
84864 /*
84865 ** Implementation of the sqlite_compileoption_get() function.
84866 ** The result is a string that identifies the compiler options
84867 ** used to build SQLite.
84868 */
84869 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
84870 static void compileoptiongetFunc(
84871   sqlite3_context *context,
84872   int argc,
84873   sqlite3_value **argv
84874 ){
84875   int n;
84876   assert( argc==1 );
84877   UNUSED_PARAMETER(argc);
84878   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
84879   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
84880   */
84881   n = sqlite3_value_int(argv[0]);
84882   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
84883 }
84884 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
84885 
84886 /* Array for converting from half-bytes (nybbles) into ASCII hex
84887 ** digits. */
84888 static const char hexdigits[] = {
84889   '0', '1', '2', '3', '4', '5', '6', '7',
84890   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
84891 };
84892 
84893 /*
84894 ** EXPERIMENTAL - This is not an official function.  The interface may
84895 ** change.  This function may disappear.  Do not write code that depends
84896 ** on this function.
84897 **
84898 ** Implementation of the QUOTE() function.  This function takes a single
84899 ** argument.  If the argument is numeric, the return value is the same as
84900 ** the argument.  If the argument is NULL, the return value is the string
84901 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
84902 ** single-quote escapes.
84903 */
84904 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
84905   assert( argc==1 );
84906   UNUSED_PARAMETER(argc);
84907   switch( sqlite3_value_type(argv[0]) ){
84908     case SQLITE_INTEGER:
84909     case SQLITE_FLOAT: {
84910       sqlite3_result_value(context, argv[0]);
84911       break;
84912     }
84913     case SQLITE_BLOB: {
84914       char *zText = 0;
84915       char const *zBlob = sqlite3_value_blob(argv[0]);
84916       int nBlob = sqlite3_value_bytes(argv[0]);
84917       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
84918       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
84919       if( zText ){
84920         int i;
84921         for(i=0; i<nBlob; i++){
84922           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
84923           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
84924         }
84925         zText[(nBlob*2)+2] = '\'';
84926         zText[(nBlob*2)+3] = '\0';
84927         zText[0] = 'X';
84928         zText[1] = '\'';
84929         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
84930         sqlite3_free(zText);
84931       }
84932       break;
84933     }
84934     case SQLITE_TEXT: {
84935       int i,j;
84936       u64 n;
84937       const unsigned char *zArg = sqlite3_value_text(argv[0]);
84938       char *z;
84939 
84940       if( zArg==0 ) return;
84941       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
84942       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
84943       if( z ){
84944         z[0] = '\'';
84945         for(i=0, j=1; zArg[i]; i++){
84946           z[j++] = zArg[i];
84947           if( zArg[i]=='\'' ){
84948             z[j++] = '\'';
84949           }
84950         }
84951         z[j++] = '\'';
84952         z[j] = 0;
84953         sqlite3_result_text(context, z, j, sqlite3_free);
84954       }
84955       break;
84956     }
84957     default: {
84958       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
84959       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
84960       break;
84961     }
84962   }
84963 }
84964 
84965 /*
84966 ** The hex() function.  Interpret the argument as a blob.  Return
84967 ** a hexadecimal rendering as text.
84968 */
84969 static void hexFunc(
84970   sqlite3_context *context,
84971   int argc,
84972   sqlite3_value **argv
84973 ){
84974   int i, n;
84975   const unsigned char *pBlob;
84976   char *zHex, *z;
84977   assert( argc==1 );
84978   UNUSED_PARAMETER(argc);
84979   pBlob = sqlite3_value_blob(argv[0]);
84980   n = sqlite3_value_bytes(argv[0]);
84981   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
84982   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
84983   if( zHex ){
84984     for(i=0; i<n; i++, pBlob++){
84985       unsigned char c = *pBlob;
84986       *(z++) = hexdigits[(c>>4)&0xf];
84987       *(z++) = hexdigits[c&0xf];
84988     }
84989     *z = 0;
84990     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
84991   }
84992 }
84993 
84994 /*
84995 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
84996 */
84997 static void zeroblobFunc(
84998   sqlite3_context *context,
84999   int argc,
85000   sqlite3_value **argv
85001 ){
85002   i64 n;
85003   sqlite3 *db = sqlite3_context_db_handle(context);
85004   assert( argc==1 );
85005   UNUSED_PARAMETER(argc);
85006   n = sqlite3_value_int64(argv[0]);
85007   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
85008   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
85009   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
85010     sqlite3_result_error_toobig(context);
85011   }else{
85012     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
85013   }
85014 }
85015 
85016 /*
85017 ** The replace() function.  Three arguments are all strings: call
85018 ** them A, B, and C. The result is also a string which is derived
85019 ** from A by replacing every occurance of B with C.  The match
85020 ** must be exact.  Collating sequences are not used.
85021 */
85022 static void replaceFunc(
85023   sqlite3_context *context,
85024   int argc,
85025   sqlite3_value **argv
85026 ){
85027   const unsigned char *zStr;        /* The input string A */
85028   const unsigned char *zPattern;    /* The pattern string B */
85029   const unsigned char *zRep;        /* The replacement string C */
85030   unsigned char *zOut;              /* The output */
85031   int nStr;                /* Size of zStr */
85032   int nPattern;            /* Size of zPattern */
85033   int nRep;                /* Size of zRep */
85034   i64 nOut;                /* Maximum size of zOut */
85035   int loopLimit;           /* Last zStr[] that might match zPattern[] */
85036   int i, j;                /* Loop counters */
85037 
85038   assert( argc==3 );
85039   UNUSED_PARAMETER(argc);
85040   zStr = sqlite3_value_text(argv[0]);
85041   if( zStr==0 ) return;
85042   nStr = sqlite3_value_bytes(argv[0]);
85043   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
85044   zPattern = sqlite3_value_text(argv[1]);
85045   if( zPattern==0 ){
85046     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
85047             || sqlite3_context_db_handle(context)->mallocFailed );
85048     return;
85049   }
85050   if( zPattern[0]==0 ){
85051     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
85052     sqlite3_result_value(context, argv[0]);
85053     return;
85054   }
85055   nPattern = sqlite3_value_bytes(argv[1]);
85056   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
85057   zRep = sqlite3_value_text(argv[2]);
85058   if( zRep==0 ) return;
85059   nRep = sqlite3_value_bytes(argv[2]);
85060   assert( zRep==sqlite3_value_text(argv[2]) );
85061   nOut = nStr + 1;
85062   assert( nOut<SQLITE_MAX_LENGTH );
85063   zOut = contextMalloc(context, (i64)nOut);
85064   if( zOut==0 ){
85065     return;
85066   }
85067   loopLimit = nStr - nPattern;
85068   for(i=j=0; i<=loopLimit; i++){
85069     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
85070       zOut[j++] = zStr[i];
85071     }else{
85072       u8 *zOld;
85073       sqlite3 *db = sqlite3_context_db_handle(context);
85074       nOut += nRep - nPattern;
85075       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
85076       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
85077       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
85078         sqlite3_result_error_toobig(context);
85079         sqlite3_free(zOut);
85080         return;
85081       }
85082       zOld = zOut;
85083       zOut = sqlite3_realloc(zOut, (int)nOut);
85084       if( zOut==0 ){
85085         sqlite3_result_error_nomem(context);
85086         sqlite3_free(zOld);
85087         return;
85088       }
85089       memcpy(&zOut[j], zRep, nRep);
85090       j += nRep;
85091       i += nPattern-1;
85092     }
85093   }
85094   assert( j+nStr-i+1==nOut );
85095   memcpy(&zOut[j], &zStr[i], nStr-i);
85096   j += nStr - i;
85097   assert( j<=nOut );
85098   zOut[j] = 0;
85099   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
85100 }
85101 
85102 /*
85103 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
85104 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
85105 */
85106 static void trimFunc(
85107   sqlite3_context *context,
85108   int argc,
85109   sqlite3_value **argv
85110 ){
85111   const unsigned char *zIn;         /* Input string */
85112   const unsigned char *zCharSet;    /* Set of characters to trim */
85113   int nIn;                          /* Number of bytes in input */
85114   int flags;                        /* 1: trimleft  2: trimright  3: trim */
85115   int i;                            /* Loop counter */
85116   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
85117   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
85118   int nChar;                        /* Number of characters in zCharSet */
85119 
85120   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
85121     return;
85122   }
85123   zIn = sqlite3_value_text(argv[0]);
85124   if( zIn==0 ) return;
85125   nIn = sqlite3_value_bytes(argv[0]);
85126   assert( zIn==sqlite3_value_text(argv[0]) );
85127   if( argc==1 ){
85128     static const unsigned char lenOne[] = { 1 };
85129     static unsigned char * const azOne[] = { (u8*)" " };
85130     nChar = 1;
85131     aLen = (u8*)lenOne;
85132     azChar = (unsigned char **)azOne;
85133     zCharSet = 0;
85134   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
85135     return;
85136   }else{
85137     const unsigned char *z;
85138     for(z=zCharSet, nChar=0; *z; nChar++){
85139       SQLITE_SKIP_UTF8(z);
85140     }
85141     if( nChar>0 ){
85142       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
85143       if( azChar==0 ){
85144         return;
85145       }
85146       aLen = (unsigned char*)&azChar[nChar];
85147       for(z=zCharSet, nChar=0; *z; nChar++){
85148         azChar[nChar] = (unsigned char *)z;
85149         SQLITE_SKIP_UTF8(z);
85150         aLen[nChar] = (u8)(z - azChar[nChar]);
85151       }
85152     }
85153   }
85154   if( nChar>0 ){
85155     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
85156     if( flags & 1 ){
85157       while( nIn>0 ){
85158         int len = 0;
85159         for(i=0; i<nChar; i++){
85160           len = aLen[i];
85161           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
85162         }
85163         if( i>=nChar ) break;
85164         zIn += len;
85165         nIn -= len;
85166       }
85167     }
85168     if( flags & 2 ){
85169       while( nIn>0 ){
85170         int len = 0;
85171         for(i=0; i<nChar; i++){
85172           len = aLen[i];
85173           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
85174         }
85175         if( i>=nChar ) break;
85176         nIn -= len;
85177       }
85178     }
85179     if( zCharSet ){
85180       sqlite3_free(azChar);
85181     }
85182   }
85183   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
85184 }
85185 
85186 
85187 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
85188 ** is only available if the SQLITE_SOUNDEX compile-time option is used
85189 ** when SQLite is built.
85190 */
85191 #ifdef SQLITE_SOUNDEX
85192 /*
85193 ** Compute the soundex encoding of a word.
85194 **
85195 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
85196 ** soundex encoding of the string X.
85197 */
85198 static void soundexFunc(
85199   sqlite3_context *context,
85200   int argc,
85201   sqlite3_value **argv
85202 ){
85203   char zResult[8];
85204   const u8 *zIn;
85205   int i, j;
85206   static const unsigned char iCode[] = {
85207     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85208     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85209     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85210     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
85211     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
85212     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
85213     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
85214     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
85215   };
85216   assert( argc==1 );
85217   zIn = (u8*)sqlite3_value_text(argv[0]);
85218   if( zIn==0 ) zIn = (u8*)"";
85219   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
85220   if( zIn[i] ){
85221     u8 prevcode = iCode[zIn[i]&0x7f];
85222     zResult[0] = sqlite3Toupper(zIn[i]);
85223     for(j=1; j<4 && zIn[i]; i++){
85224       int code = iCode[zIn[i]&0x7f];
85225       if( code>0 ){
85226         if( code!=prevcode ){
85227           prevcode = code;
85228           zResult[j++] = code + '0';
85229         }
85230       }else{
85231         prevcode = 0;
85232       }
85233     }
85234     while( j<4 ){
85235       zResult[j++] = '0';
85236     }
85237     zResult[j] = 0;
85238     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
85239   }else{
85240     /* IMP: R-64894-50321 The string "?000" is returned if the argument
85241     ** is NULL or contains no ASCII alphabetic characters. */
85242     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
85243   }
85244 }
85245 #endif /* SQLITE_SOUNDEX */
85246 
85247 #ifndef SQLITE_OMIT_LOAD_EXTENSION
85248 /*
85249 ** A function that loads a shared-library extension then returns NULL.
85250 */
85251 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
85252   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
85253   const char *zProc;
85254   sqlite3 *db = sqlite3_context_db_handle(context);
85255   char *zErrMsg = 0;
85256 
85257   if( argc==2 ){
85258     zProc = (const char *)sqlite3_value_text(argv[1]);
85259   }else{
85260     zProc = 0;
85261   }
85262   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
85263     sqlite3_result_error(context, zErrMsg, -1);
85264     sqlite3_free(zErrMsg);
85265   }
85266 }
85267 #endif
85268 
85269 
85270 /*
85271 ** An instance of the following structure holds the context of a
85272 ** sum() or avg() aggregate computation.
85273 */
85274 typedef struct SumCtx SumCtx;
85275 struct SumCtx {
85276   double rSum;      /* Floating point sum */
85277   i64 iSum;         /* Integer sum */
85278   i64 cnt;          /* Number of elements summed */
85279   u8 overflow;      /* True if integer overflow seen */
85280   u8 approx;        /* True if non-integer value was input to the sum */
85281 };
85282 
85283 /*
85284 ** Routines used to compute the sum, average, and total.
85285 **
85286 ** The SUM() function follows the (broken) SQL standard which means
85287 ** that it returns NULL if it sums over no inputs.  TOTAL returns
85288 ** 0.0 in that case.  In addition, TOTAL always returns a float where
85289 ** SUM might return an integer if it never encounters a floating point
85290 ** value.  TOTAL never fails, but SUM might through an exception if
85291 ** it overflows an integer.
85292 */
85293 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
85294   SumCtx *p;
85295   int type;
85296   assert( argc==1 );
85297   UNUSED_PARAMETER(argc);
85298   p = sqlite3_aggregate_context(context, sizeof(*p));
85299   type = sqlite3_value_numeric_type(argv[0]);
85300   if( p && type!=SQLITE_NULL ){
85301     p->cnt++;
85302     if( type==SQLITE_INTEGER ){
85303       i64 v = sqlite3_value_int64(argv[0]);
85304       p->rSum += v;
85305       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
85306         p->overflow = 1;
85307       }
85308     }else{
85309       p->rSum += sqlite3_value_double(argv[0]);
85310       p->approx = 1;
85311     }
85312   }
85313 }
85314 static void sumFinalize(sqlite3_context *context){
85315   SumCtx *p;
85316   p = sqlite3_aggregate_context(context, 0);
85317   if( p && p->cnt>0 ){
85318     if( p->overflow ){
85319       sqlite3_result_error(context,"integer overflow",-1);
85320     }else if( p->approx ){
85321       sqlite3_result_double(context, p->rSum);
85322     }else{
85323       sqlite3_result_int64(context, p->iSum);
85324     }
85325   }
85326 }
85327 static void avgFinalize(sqlite3_context *context){
85328   SumCtx *p;
85329   p = sqlite3_aggregate_context(context, 0);
85330   if( p && p->cnt>0 ){
85331     sqlite3_result_double(context, p->rSum/(double)p->cnt);
85332   }
85333 }
85334 static void totalFinalize(sqlite3_context *context){
85335   SumCtx *p;
85336   p = sqlite3_aggregate_context(context, 0);
85337   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
85338   sqlite3_result_double(context, p ? p->rSum : (double)0);
85339 }
85340 
85341 /*
85342 ** The following structure keeps track of state information for the
85343 ** count() aggregate function.
85344 */
85345 typedef struct CountCtx CountCtx;
85346 struct CountCtx {
85347   i64 n;
85348 };
85349 
85350 /*
85351 ** Routines to implement the count() aggregate function.
85352 */
85353 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
85354   CountCtx *p;
85355   p = sqlite3_aggregate_context(context, sizeof(*p));
85356   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
85357     p->n++;
85358   }
85359 
85360 #ifndef SQLITE_OMIT_DEPRECATED
85361   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
85362   ** sure it still operates correctly, verify that its count agrees with our
85363   ** internal count when using count(*) and when the total count can be
85364   ** expressed as a 32-bit integer. */
85365   assert( argc==1 || p==0 || p->n>0x7fffffff
85366           || p->n==sqlite3_aggregate_count(context) );
85367 #endif
85368 }
85369 static void countFinalize(sqlite3_context *context){
85370   CountCtx *p;
85371   p = sqlite3_aggregate_context(context, 0);
85372   sqlite3_result_int64(context, p ? p->n : 0);
85373 }
85374 
85375 /*
85376 ** Routines to implement min() and max() aggregate functions.
85377 */
85378 static void minmaxStep(
85379   sqlite3_context *context,
85380   int NotUsed,
85381   sqlite3_value **argv
85382 ){
85383   Mem *pArg  = (Mem *)argv[0];
85384   Mem *pBest;
85385   UNUSED_PARAMETER(NotUsed);
85386 
85387   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85388   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
85389   if( !pBest ) return;
85390 
85391   if( pBest->flags ){
85392     int max;
85393     int cmp;
85394     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
85395     /* This step function is used for both the min() and max() aggregates,
85396     ** the only difference between the two being that the sense of the
85397     ** comparison is inverted. For the max() aggregate, the
85398     ** sqlite3_user_data() function returns (void *)-1. For min() it
85399     ** returns (void *)db, where db is the sqlite3* database pointer.
85400     ** Therefore the next statement sets variable 'max' to 1 for the max()
85401     ** aggregate, or 0 for min().
85402     */
85403     max = sqlite3_user_data(context)!=0;
85404     cmp = sqlite3MemCompare(pBest, pArg, pColl);
85405     if( (max && cmp<0) || (!max && cmp>0) ){
85406       sqlite3VdbeMemCopy(pBest, pArg);
85407     }
85408   }else{
85409     sqlite3VdbeMemCopy(pBest, pArg);
85410   }
85411 }
85412 static void minMaxFinalize(sqlite3_context *context){
85413   sqlite3_value *pRes;
85414   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
85415   if( pRes ){
85416     if( ALWAYS(pRes->flags) ){
85417       sqlite3_result_value(context, pRes);
85418     }
85419     sqlite3VdbeMemRelease(pRes);
85420   }
85421 }
85422 
85423 /*
85424 ** group_concat(EXPR, ?SEPARATOR?)
85425 */
85426 static void groupConcatStep(
85427   sqlite3_context *context,
85428   int argc,
85429   sqlite3_value **argv
85430 ){
85431   const char *zVal;
85432   StrAccum *pAccum;
85433   const char *zSep;
85434   int nVal, nSep;
85435   assert( argc==1 || argc==2 );
85436   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
85437   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
85438 
85439   if( pAccum ){
85440     sqlite3 *db = sqlite3_context_db_handle(context);
85441     int firstTerm = pAccum->useMalloc==0;
85442     pAccum->useMalloc = 2;
85443     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
85444     if( !firstTerm ){
85445       if( argc==2 ){
85446         zSep = (char*)sqlite3_value_text(argv[1]);
85447         nSep = sqlite3_value_bytes(argv[1]);
85448       }else{
85449         zSep = ",";
85450         nSep = 1;
85451       }
85452       sqlite3StrAccumAppend(pAccum, zSep, nSep);
85453     }
85454     zVal = (char*)sqlite3_value_text(argv[0]);
85455     nVal = sqlite3_value_bytes(argv[0]);
85456     sqlite3StrAccumAppend(pAccum, zVal, nVal);
85457   }
85458 }
85459 static void groupConcatFinalize(sqlite3_context *context){
85460   StrAccum *pAccum;
85461   pAccum = sqlite3_aggregate_context(context, 0);
85462   if( pAccum ){
85463     if( pAccum->tooBig ){
85464       sqlite3_result_error_toobig(context);
85465     }else if( pAccum->mallocFailed ){
85466       sqlite3_result_error_nomem(context);
85467     }else{
85468       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
85469                           sqlite3_free);
85470     }
85471   }
85472 }
85473 
85474 /*
85475 ** This routine does per-connection function registration.  Most
85476 ** of the built-in functions above are part of the global function set.
85477 ** This routine only deals with those that are not global.
85478 */
85479 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
85480   int rc = sqlite3_overload_function(db, "MATCH", 2);
85481   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
85482   if( rc==SQLITE_NOMEM ){
85483     db->mallocFailed = 1;
85484   }
85485 }
85486 
85487 /*
85488 ** Set the LIKEOPT flag on the 2-argument function with the given name.
85489 */
85490 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
85491   FuncDef *pDef;
85492   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
85493                              2, SQLITE_UTF8, 0);
85494   if( ALWAYS(pDef) ){
85495     pDef->flags = flagVal;
85496   }
85497 }
85498 
85499 /*
85500 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
85501 ** parameter determines whether or not the LIKE operator is case
85502 ** sensitive.  GLOB is always case sensitive.
85503 */
85504 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
85505   struct compareInfo *pInfo;
85506   if( caseSensitive ){
85507     pInfo = (struct compareInfo*)&likeInfoAlt;
85508   }else{
85509     pInfo = (struct compareInfo*)&likeInfoNorm;
85510   }
85511   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
85512   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
85513   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
85514       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
85515   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
85516   setLikeOptFlag(db, "like",
85517       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
85518 }
85519 
85520 /*
85521 ** pExpr points to an expression which implements a function.  If
85522 ** it is appropriate to apply the LIKE optimization to that function
85523 ** then set aWc[0] through aWc[2] to the wildcard characters and
85524 ** return TRUE.  If the function is not a LIKE-style function then
85525 ** return FALSE.
85526 */
85527 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
85528   FuncDef *pDef;
85529   if( pExpr->op!=TK_FUNCTION
85530    || !pExpr->x.pList
85531    || pExpr->x.pList->nExpr!=2
85532   ){
85533     return 0;
85534   }
85535   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85536   pDef = sqlite3FindFunction(db, pExpr->u.zToken,
85537                              sqlite3Strlen30(pExpr->u.zToken),
85538                              2, SQLITE_UTF8, 0);
85539   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
85540     return 0;
85541   }
85542 
85543   /* The memcpy() statement assumes that the wildcard characters are
85544   ** the first three statements in the compareInfo structure.  The
85545   ** asserts() that follow verify that assumption
85546   */
85547   memcpy(aWc, pDef->pUserData, 3);
85548   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
85549   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
85550   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
85551   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
85552   return 1;
85553 }
85554 
85555 /*
85556 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
85557 ** to the global function hash table.  This occurs at start-time (as
85558 ** a consequence of calling sqlite3_initialize()).
85559 **
85560 ** After this routine runs
85561 */
85562 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
85563   /*
85564   ** The following array holds FuncDef structures for all of the functions
85565   ** defined in this file.
85566   **
85567   ** The array cannot be constant since changes are made to the
85568   ** FuncDef.pHash elements at start-time.  The elements of this array
85569   ** are read-only after initialization is complete.
85570   */
85571   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
85572     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
85573     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
85574     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
85575     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
85576     FUNCTION(trim,               1, 3, 0, trimFunc         ),
85577     FUNCTION(trim,               2, 3, 0, trimFunc         ),
85578     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
85579     FUNCTION(min,                0, 0, 1, 0                ),
85580     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
85581     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
85582     FUNCTION(max,                0, 1, 1, 0                ),
85583     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
85584     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
85585     FUNCTION(length,             1, 0, 0, lengthFunc       ),
85586     FUNCTION(substr,             2, 0, 0, substrFunc       ),
85587     FUNCTION(substr,             3, 0, 0, substrFunc       ),
85588     FUNCTION(abs,                1, 0, 0, absFunc          ),
85589 #ifndef SQLITE_OMIT_FLOATING_POINT
85590     FUNCTION(round,              1, 0, 0, roundFunc        ),
85591     FUNCTION(round,              2, 0, 0, roundFunc        ),
85592 #endif
85593     FUNCTION(upper,              1, 0, 0, upperFunc        ),
85594     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
85595     FUNCTION(coalesce,           1, 0, 0, 0                ),
85596     FUNCTION(coalesce,           0, 0, 0, 0                ),
85597 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
85598     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
85599     FUNCTION(hex,                1, 0, 0, hexFunc          ),
85600 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
85601     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
85602     FUNCTION(random,             0, 0, 0, randomFunc       ),
85603     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
85604     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
85605     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
85606     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
85607     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
85608 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
85609     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
85610     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
85611 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
85612     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
85613     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
85614     FUNCTION(changes,            0, 0, 0, changes          ),
85615     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
85616     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
85617     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
85618   #ifdef SQLITE_SOUNDEX
85619     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
85620   #endif
85621   #ifndef SQLITE_OMIT_LOAD_EXTENSION
85622     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
85623     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
85624   #endif
85625     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
85626     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
85627     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
85628  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
85629     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
85630     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
85631     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
85632     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
85633 
85634     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85635   #ifdef SQLITE_CASE_SENSITIVE_LIKE
85636     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85637     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
85638   #else
85639     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
85640     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
85641   #endif
85642   };
85643 
85644   int i;
85645   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85646   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
85647 
85648   for(i=0; i<ArraySize(aBuiltinFunc); i++){
85649     sqlite3FuncDefInsert(pHash, &aFunc[i]);
85650   }
85651   sqlite3RegisterDateTimeFunctions();
85652 #ifndef SQLITE_OMIT_ALTERTABLE
85653   sqlite3AlterFunctions();
85654 #endif
85655 }
85656 
85657 /************** End of func.c ************************************************/
85658 /************** Begin file fkey.c ********************************************/
85659 /*
85660 **
85661 ** The author disclaims copyright to this source code.  In place of
85662 ** a legal notice, here is a blessing:
85663 **
85664 **    May you do good and not evil.
85665 **    May you find forgiveness for yourself and forgive others.
85666 **    May you share freely, never taking more than you give.
85667 **
85668 *************************************************************************
85669 ** This file contains code used by the compiler to add foreign key
85670 ** support to compiled SQL statements.
85671 */
85672 
85673 #ifndef SQLITE_OMIT_FOREIGN_KEY
85674 #ifndef SQLITE_OMIT_TRIGGER
85675 
85676 /*
85677 ** Deferred and Immediate FKs
85678 ** --------------------------
85679 **
85680 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
85681 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
85682 ** is returned and the current statement transaction rolled back. If a
85683 ** deferred foreign key constraint is violated, no action is taken
85684 ** immediately. However if the application attempts to commit the
85685 ** transaction before fixing the constraint violation, the attempt fails.
85686 **
85687 ** Deferred constraints are implemented using a simple counter associated
85688 ** with the database handle. The counter is set to zero each time a
85689 ** database transaction is opened. Each time a statement is executed
85690 ** that causes a foreign key violation, the counter is incremented. Each
85691 ** time a statement is executed that removes an existing violation from
85692 ** the database, the counter is decremented. When the transaction is
85693 ** committed, the commit fails if the current value of the counter is
85694 ** greater than zero. This scheme has two big drawbacks:
85695 **
85696 **   * When a commit fails due to a deferred foreign key constraint,
85697 **     there is no way to tell which foreign constraint is not satisfied,
85698 **     or which row it is not satisfied for.
85699 **
85700 **   * If the database contains foreign key violations when the
85701 **     transaction is opened, this may cause the mechanism to malfunction.
85702 **
85703 ** Despite these problems, this approach is adopted as it seems simpler
85704 ** than the alternatives.
85705 **
85706 ** INSERT operations:
85707 **
85708 **   I.1) For each FK for which the table is the child table, search
85709 **        the parent table for a match. If none is found increment the
85710 **        constraint counter.
85711 **
85712 **   I.2) For each FK for which the table is the parent table,
85713 **        search the child table for rows that correspond to the new
85714 **        row in the parent table. Decrement the counter for each row
85715 **        found (as the constraint is now satisfied).
85716 **
85717 ** DELETE operations:
85718 **
85719 **   D.1) For each FK for which the table is the child table,
85720 **        search the parent table for a row that corresponds to the
85721 **        deleted row in the child table. If such a row is not found,
85722 **        decrement the counter.
85723 **
85724 **   D.2) For each FK for which the table is the parent table, search
85725 **        the child table for rows that correspond to the deleted row
85726 **        in the parent table. For each found increment the counter.
85727 **
85728 ** UPDATE operations:
85729 **
85730 **   An UPDATE command requires that all 4 steps above are taken, but only
85731 **   for FK constraints for which the affected columns are actually
85732 **   modified (values must be compared at runtime).
85733 **
85734 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
85735 ** This simplifies the implementation a bit.
85736 **
85737 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
85738 ** resolution is considered to delete rows before the new row is inserted.
85739 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
85740 ** is thrown, even if the FK constraint would be satisfied after the new
85741 ** row is inserted.
85742 **
85743 ** Immediate constraints are usually handled similarly. The only difference
85744 ** is that the counter used is stored as part of each individual statement
85745 ** object (struct Vdbe). If, after the statement has run, its immediate
85746 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
85747 ** and the statement transaction is rolled back. An exception is an INSERT
85748 ** statement that inserts a single row only (no triggers). In this case,
85749 ** instead of using a counter, an exception is thrown immediately if the
85750 ** INSERT violates a foreign key constraint. This is necessary as such
85751 ** an INSERT does not open a statement transaction.
85752 **
85753 ** TODO: How should dropping a table be handled? How should renaming a
85754 ** table be handled?
85755 **
85756 **
85757 ** Query API Notes
85758 ** ---------------
85759 **
85760 ** Before coding an UPDATE or DELETE row operation, the code-generator
85761 ** for those two operations needs to know whether or not the operation
85762 ** requires any FK processing and, if so, which columns of the original
85763 ** row are required by the FK processing VDBE code (i.e. if FKs were
85764 ** implemented using triggers, which of the old.* columns would be
85765 ** accessed). No information is required by the code-generator before
85766 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
85767 ** generation code to query for this information are:
85768 **
85769 **   sqlite3FkRequired() - Test to see if FK processing is required.
85770 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
85771 **
85772 **
85773 ** Externally accessible module functions
85774 ** --------------------------------------
85775 **
85776 **   sqlite3FkCheck()    - Check for foreign key violations.
85777 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
85778 **   sqlite3FkDelete()   - Delete an FKey structure.
85779 */
85780 
85781 /*
85782 ** VDBE Calling Convention
85783 ** -----------------------
85784 **
85785 ** Example:
85786 **
85787 **   For the following INSERT statement:
85788 **
85789 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
85790 **     INSERT INTO t1 VALUES(1, 2, 3.1);
85791 **
85792 **   Register (x):        2    (type integer)
85793 **   Register (x+1):      1    (type integer)
85794 **   Register (x+2):      NULL (type NULL)
85795 **   Register (x+3):      3.1  (type real)
85796 */
85797 
85798 /*
85799 ** A foreign key constraint requires that the key columns in the parent
85800 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
85801 ** Given that pParent is the parent table for foreign key constraint pFKey,
85802 ** search the schema a unique index on the parent key columns.
85803 **
85804 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
85805 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
85806 ** is set to point to the unique index.
85807 **
85808 ** If the parent key consists of a single column (the foreign key constraint
85809 ** is not a composite foreign key), output variable *paiCol is set to NULL.
85810 ** Otherwise, it is set to point to an allocated array of size N, where
85811 ** N is the number of columns in the parent key. The first element of the
85812 ** array is the index of the child table column that is mapped by the FK
85813 ** constraint to the parent table column stored in the left-most column
85814 ** of index *ppIdx. The second element of the array is the index of the
85815 ** child table column that corresponds to the second left-most column of
85816 ** *ppIdx, and so on.
85817 **
85818 ** If the required index cannot be found, either because:
85819 **
85820 **   1) The named parent key columns do not exist, or
85821 **
85822 **   2) The named parent key columns do exist, but are not subject to a
85823 **      UNIQUE or PRIMARY KEY constraint, or
85824 **
85825 **   3) No parent key columns were provided explicitly as part of the
85826 **      foreign key definition, and the parent table does not have a
85827 **      PRIMARY KEY, or
85828 **
85829 **   4) No parent key columns were provided explicitly as part of the
85830 **      foreign key definition, and the PRIMARY KEY of the parent table
85831 **      consists of a a different number of columns to the child key in
85832 **      the child table.
85833 **
85834 ** then non-zero is returned, and a "foreign key mismatch" error loaded
85835 ** into pParse. If an OOM error occurs, non-zero is returned and the
85836 ** pParse->db->mallocFailed flag is set.
85837 */
85838 static int locateFkeyIndex(
85839   Parse *pParse,                  /* Parse context to store any error in */
85840   Table *pParent,                 /* Parent table of FK constraint pFKey */
85841   FKey *pFKey,                    /* Foreign key to find index for */
85842   Index **ppIdx,                  /* OUT: Unique index on parent table */
85843   int **paiCol                    /* OUT: Map of index columns in pFKey */
85844 ){
85845   Index *pIdx = 0;                    /* Value to return via *ppIdx */
85846   int *aiCol = 0;                     /* Value to return via *paiCol */
85847   int nCol = pFKey->nCol;             /* Number of columns in parent key */
85848   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
85849 
85850   /* The caller is responsible for zeroing output parameters. */
85851   assert( ppIdx && *ppIdx==0 );
85852   assert( !paiCol || *paiCol==0 );
85853   assert( pParse );
85854 
85855   /* If this is a non-composite (single column) foreign key, check if it
85856   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
85857   ** and *paiCol set to zero and return early.
85858   **
85859   ** Otherwise, for a composite foreign key (more than one column), allocate
85860   ** space for the aiCol array (returned via output parameter *paiCol).
85861   ** Non-composite foreign keys do not require the aiCol array.
85862   */
85863   if( nCol==1 ){
85864     /* The FK maps to the IPK if any of the following are true:
85865     **
85866     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
85867     **      mapped to the primary key of table pParent, or
85868     **   2) The FK is explicitly mapped to a column declared as INTEGER
85869     **      PRIMARY KEY.
85870     */
85871     if( pParent->iPKey>=0 ){
85872       if( !zKey ) return 0;
85873       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
85874     }
85875   }else if( paiCol ){
85876     assert( nCol>1 );
85877     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
85878     if( !aiCol ) return 1;
85879     *paiCol = aiCol;
85880   }
85881 
85882   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
85883     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
85884       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
85885       ** of columns. If each indexed column corresponds to a foreign key
85886       ** column of pFKey, then this index is a winner.  */
85887 
85888       if( zKey==0 ){
85889         /* If zKey is NULL, then this foreign key is implicitly mapped to
85890         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
85891         ** identified by the test (Index.autoIndex==2).  */
85892         if( pIdx->autoIndex==2 ){
85893           if( aiCol ){
85894             int i;
85895             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
85896           }
85897           break;
85898         }
85899       }else{
85900         /* If zKey is non-NULL, then this foreign key was declared to
85901         ** map to an explicit list of columns in table pParent. Check if this
85902         ** index matches those columns. Also, check that the index uses
85903         ** the default collation sequences for each column. */
85904         int i, j;
85905         for(i=0; i<nCol; i++){
85906           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
85907           char *zDfltColl;                  /* Def. collation for column */
85908           char *zIdxCol;                    /* Name of indexed column */
85909 
85910           /* If the index uses a collation sequence that is different from
85911           ** the default collation sequence for the column, this index is
85912           ** unusable. Bail out early in this case.  */
85913           zDfltColl = pParent->aCol[iCol].zColl;
85914           if( !zDfltColl ){
85915             zDfltColl = "BINARY";
85916           }
85917           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
85918 
85919           zIdxCol = pParent->aCol[iCol].zName;
85920           for(j=0; j<nCol; j++){
85921             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
85922               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
85923               break;
85924             }
85925           }
85926           if( j==nCol ) break;
85927         }
85928         if( i==nCol ) break;      /* pIdx is usable */
85929       }
85930     }
85931   }
85932 
85933   if( !pIdx ){
85934     if( !pParse->disableTriggers ){
85935       sqlite3ErrorMsg(pParse, "foreign key mismatch");
85936     }
85937     sqlite3DbFree(pParse->db, aiCol);
85938     return 1;
85939   }
85940 
85941   *ppIdx = pIdx;
85942   return 0;
85943 }
85944 
85945 /*
85946 ** This function is called when a row is inserted into or deleted from the
85947 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
85948 ** on the child table of pFKey, this function is invoked twice for each row
85949 ** affected - once to "delete" the old row, and then again to "insert" the
85950 ** new row.
85951 **
85952 ** Each time it is called, this function generates VDBE code to locate the
85953 ** row in the parent table that corresponds to the row being inserted into
85954 ** or deleted from the child table. If the parent row can be found, no
85955 ** special action is taken. Otherwise, if the parent row can *not* be
85956 ** found in the parent table:
85957 **
85958 **   Operation | FK type   | Action taken
85959 **   --------------------------------------------------------------------------
85960 **   INSERT      immediate   Increment the "immediate constraint counter".
85961 **
85962 **   DELETE      immediate   Decrement the "immediate constraint counter".
85963 **
85964 **   INSERT      deferred    Increment the "deferred constraint counter".
85965 **
85966 **   DELETE      deferred    Decrement the "deferred constraint counter".
85967 **
85968 ** These operations are identified in the comment at the top of this file
85969 ** (fkey.c) as "I.1" and "D.1".
85970 */
85971 static void fkLookupParent(
85972   Parse *pParse,        /* Parse context */
85973   int iDb,              /* Index of database housing pTab */
85974   Table *pTab,          /* Parent table of FK pFKey */
85975   Index *pIdx,          /* Unique index on parent key columns in pTab */
85976   FKey *pFKey,          /* Foreign key constraint */
85977   int *aiCol,           /* Map from parent key columns to child table columns */
85978   int regData,          /* Address of array containing child table row */
85979   int nIncr,            /* Increment constraint counter by this */
85980   int isIgnore          /* If true, pretend pTab contains all NULL values */
85981 ){
85982   int i;                                    /* Iterator variable */
85983   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
85984   int iCur = pParse->nTab - 1;              /* Cursor number to use */
85985   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
85986 
85987   /* If nIncr is less than zero, then check at runtime if there are any
85988   ** outstanding constraints to resolve. If there are not, there is no need
85989   ** to check if deleting this row resolves any outstanding violations.
85990   **
85991   ** Check if any of the key columns in the child table row are NULL. If
85992   ** any are, then the constraint is considered satisfied. No need to
85993   ** search for a matching row in the parent table.  */
85994   if( nIncr<0 ){
85995     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
85996   }
85997   for(i=0; i<pFKey->nCol; i++){
85998     int iReg = aiCol[i] + regData + 1;
85999     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
86000   }
86001 
86002   if( isIgnore==0 ){
86003     if( pIdx==0 ){
86004       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
86005       ** column of the parent table (table pTab).  */
86006       int iMustBeInt;               /* Address of MustBeInt instruction */
86007       int regTemp = sqlite3GetTempReg(pParse);
86008 
86009       /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
86010       ** apply the affinity of the parent key). If this fails, then there
86011       ** is no matching parent key. Before using MustBeInt, make a copy of
86012       ** the value. Otherwise, the value inserted into the child key column
86013       ** will have INTEGER affinity applied to it, which may not be correct.  */
86014       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
86015       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
86016 
86017       /* If the parent table is the same as the child table, and we are about
86018       ** to increment the constraint-counter (i.e. this is an INSERT operation),
86019       ** then check if the row being inserted matches itself. If so, do not
86020       ** increment the constraint-counter.  */
86021       if( pTab==pFKey->pFrom && nIncr==1 ){
86022         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
86023       }
86024 
86025       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
86026       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
86027       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
86028       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
86029       sqlite3VdbeJumpHere(v, iMustBeInt);
86030       sqlite3ReleaseTempReg(pParse, regTemp);
86031     }else{
86032       int nCol = pFKey->nCol;
86033       int regTemp = sqlite3GetTempRange(pParse, nCol);
86034       int regRec = sqlite3GetTempReg(pParse);
86035       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86036 
86037       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
86038       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
86039       for(i=0; i<nCol; i++){
86040         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
86041       }
86042 
86043       /* If the parent table is the same as the child table, and we are about
86044       ** to increment the constraint-counter (i.e. this is an INSERT operation),
86045       ** then check if the row being inserted matches itself. If so, do not
86046       ** increment the constraint-counter.
86047       **
86048       ** If any of the parent-key values are NULL, then the row cannot match
86049       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
86050       ** of the parent-key values are NULL (at this point it is known that
86051       ** none of the child key values are).
86052       */
86053       if( pTab==pFKey->pFrom && nIncr==1 ){
86054         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
86055         for(i=0; i<nCol; i++){
86056           int iChild = aiCol[i]+1+regData;
86057           int iParent = pIdx->aiColumn[i]+1+regData;
86058           assert( aiCol[i]!=pTab->iPKey );
86059           if( pIdx->aiColumn[i]==pTab->iPKey ){
86060             /* The parent key is a composite key that includes the IPK column */
86061             iParent = regData;
86062           }
86063           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
86064           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
86065         }
86066         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
86067       }
86068 
86069       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
86070       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
86071       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
86072 
86073       sqlite3ReleaseTempReg(pParse, regRec);
86074       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
86075     }
86076   }
86077 
86078   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
86079     /* Special case: If this is an INSERT statement that will insert exactly
86080     ** one row into the table, raise a constraint immediately instead of
86081     ** incrementing a counter. This is necessary as the VM code is being
86082     ** generated for will not open a statement transaction.  */
86083     assert( nIncr==1 );
86084     sqlite3HaltConstraint(
86085         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
86086     );
86087   }else{
86088     if( nIncr>0 && pFKey->isDeferred==0 ){
86089       sqlite3ParseToplevel(pParse)->mayAbort = 1;
86090     }
86091     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
86092   }
86093 
86094   sqlite3VdbeResolveLabel(v, iOk);
86095   sqlite3VdbeAddOp1(v, OP_Close, iCur);
86096 }
86097 
86098 /*
86099 ** This function is called to generate code executed when a row is deleted
86100 ** from the parent table of foreign key constraint pFKey and, if pFKey is
86101 ** deferred, when a row is inserted into the same table. When generating
86102 ** code for an SQL UPDATE operation, this function may be called twice -
86103 ** once to "delete" the old row and once to "insert" the new row.
86104 **
86105 ** The code generated by this function scans through the rows in the child
86106 ** table that correspond to the parent table row being deleted or inserted.
86107 ** For each child row found, one of the following actions is taken:
86108 **
86109 **   Operation | FK type   | Action taken
86110 **   --------------------------------------------------------------------------
86111 **   DELETE      immediate   Increment the "immediate constraint counter".
86112 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
86113 **                           throw a "foreign key constraint failed" exception.
86114 **
86115 **   INSERT      immediate   Decrement the "immediate constraint counter".
86116 **
86117 **   DELETE      deferred    Increment the "deferred constraint counter".
86118 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
86119 **                           throw a "foreign key constraint failed" exception.
86120 **
86121 **   INSERT      deferred    Decrement the "deferred constraint counter".
86122 **
86123 ** These operations are identified in the comment at the top of this file
86124 ** (fkey.c) as "I.2" and "D.2".
86125 */
86126 static void fkScanChildren(
86127   Parse *pParse,                  /* Parse context */
86128   SrcList *pSrc,                  /* SrcList containing the table to scan */
86129   Table *pTab,
86130   Index *pIdx,                    /* Foreign key index */
86131   FKey *pFKey,                    /* Foreign key relationship */
86132   int *aiCol,                     /* Map from pIdx cols to child table cols */
86133   int regData,                    /* Referenced table data starts here */
86134   int nIncr                       /* Amount to increment deferred counter by */
86135 ){
86136   sqlite3 *db = pParse->db;       /* Database handle */
86137   int i;                          /* Iterator variable */
86138   Expr *pWhere = 0;               /* WHERE clause to scan with */
86139   NameContext sNameContext;       /* Context used to resolve WHERE clause */
86140   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
86141   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
86142   Vdbe *v = sqlite3GetVdbe(pParse);
86143 
86144   assert( !pIdx || pIdx->pTable==pTab );
86145 
86146   if( nIncr<0 ){
86147     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
86148   }
86149 
86150   /* Create an Expr object representing an SQL expression like:
86151   **
86152   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
86153   **
86154   ** The collation sequence used for the comparison should be that of
86155   ** the parent key columns. The affinity of the parent key column should
86156   ** be applied to each child key value before the comparison takes place.
86157   */
86158   for(i=0; i<pFKey->nCol; i++){
86159     Expr *pLeft;                  /* Value from parent table row */
86160     Expr *pRight;                 /* Column ref to child table */
86161     Expr *pEq;                    /* Expression (pLeft = pRight) */
86162     int iCol;                     /* Index of column in child table */
86163     const char *zCol;             /* Name of column in child table */
86164 
86165     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
86166     if( pLeft ){
86167       /* Set the collation sequence and affinity of the LHS of each TK_EQ
86168       ** expression to the parent key column defaults.  */
86169       if( pIdx ){
86170         Column *pCol;
86171         iCol = pIdx->aiColumn[i];
86172         pCol = &pTab->aCol[iCol];
86173         if( pTab->iPKey==iCol ) iCol = -1;
86174         pLeft->iTable = regData+iCol+1;
86175         pLeft->affinity = pCol->affinity;
86176         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
86177       }else{
86178         pLeft->iTable = regData;
86179         pLeft->affinity = SQLITE_AFF_INTEGER;
86180       }
86181     }
86182     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
86183     assert( iCol>=0 );
86184     zCol = pFKey->pFrom->aCol[iCol].zName;
86185     pRight = sqlite3Expr(db, TK_ID, zCol);
86186     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
86187     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
86188   }
86189 
86190   /* If the child table is the same as the parent table, and this scan
86191   ** is taking place as part of a DELETE operation (operation D.2), omit the
86192   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
86193   ** clause, where $rowid is the rowid of the row being deleted.  */
86194   if( pTab==pFKey->pFrom && nIncr>0 ){
86195     Expr *pEq;                    /* Expression (pLeft = pRight) */
86196     Expr *pLeft;                  /* Value from parent table row */
86197     Expr *pRight;                 /* Column ref to child table */
86198     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
86199     pRight = sqlite3Expr(db, TK_COLUMN, 0);
86200     if( pLeft && pRight ){
86201       pLeft->iTable = regData;
86202       pLeft->affinity = SQLITE_AFF_INTEGER;
86203       pRight->iTable = pSrc->a[0].iCursor;
86204       pRight->iColumn = -1;
86205     }
86206     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
86207     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
86208   }
86209 
86210   /* Resolve the references in the WHERE clause. */
86211   memset(&sNameContext, 0, sizeof(NameContext));
86212   sNameContext.pSrcList = pSrc;
86213   sNameContext.pParse = pParse;
86214   sqlite3ResolveExprNames(&sNameContext, pWhere);
86215 
86216   /* Create VDBE to loop through the entries in pSrc that match the WHERE
86217   ** clause. If the constraint is not deferred, throw an exception for
86218   ** each row found. Otherwise, for deferred constraints, increment the
86219   ** deferred constraint counter by nIncr for each row selected.  */
86220   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
86221   if( nIncr>0 && pFKey->isDeferred==0 ){
86222     sqlite3ParseToplevel(pParse)->mayAbort = 1;
86223   }
86224   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
86225   if( pWInfo ){
86226     sqlite3WhereEnd(pWInfo);
86227   }
86228 
86229   /* Clean up the WHERE clause constructed above. */
86230   sqlite3ExprDelete(db, pWhere);
86231   if( iFkIfZero ){
86232     sqlite3VdbeJumpHere(v, iFkIfZero);
86233   }
86234 }
86235 
86236 /*
86237 ** This function returns a pointer to the head of a linked list of FK
86238 ** constraints for which table pTab is the parent table. For example,
86239 ** given the following schema:
86240 **
86241 **   CREATE TABLE t1(a PRIMARY KEY);
86242 **   CREATE TABLE t2(b REFERENCES t1(a);
86243 **
86244 ** Calling this function with table "t1" as an argument returns a pointer
86245 ** to the FKey structure representing the foreign key constraint on table
86246 ** "t2". Calling this function with "t2" as the argument would return a
86247 ** NULL pointer (as there are no FK constraints for which t2 is the parent
86248 ** table).
86249 */
86250 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
86251   int nName = sqlite3Strlen30(pTab->zName);
86252   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
86253 }
86254 
86255 /*
86256 ** The second argument is a Trigger structure allocated by the
86257 ** fkActionTrigger() routine. This function deletes the Trigger structure
86258 ** and all of its sub-components.
86259 **
86260 ** The Trigger structure or any of its sub-components may be allocated from
86261 ** the lookaside buffer belonging to database handle dbMem.
86262 */
86263 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
86264   if( p ){
86265     TriggerStep *pStep = p->step_list;
86266     sqlite3ExprDelete(dbMem, pStep->pWhere);
86267     sqlite3ExprListDelete(dbMem, pStep->pExprList);
86268     sqlite3SelectDelete(dbMem, pStep->pSelect);
86269     sqlite3ExprDelete(dbMem, p->pWhen);
86270     sqlite3DbFree(dbMem, p);
86271   }
86272 }
86273 
86274 /*
86275 ** This function is called to generate code that runs when table pTab is
86276 ** being dropped from the database. The SrcList passed as the second argument
86277 ** to this function contains a single entry guaranteed to resolve to
86278 ** table pTab.
86279 **
86280 ** Normally, no code is required. However, if either
86281 **
86282 **   (a) The table is the parent table of a FK constraint, or
86283 **   (b) The table is the child table of a deferred FK constraint and it is
86284 **       determined at runtime that there are outstanding deferred FK
86285 **       constraint violations in the database,
86286 **
86287 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
86288 ** the table from the database. Triggers are disabled while running this
86289 ** DELETE, but foreign key actions are not.
86290 */
86291 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
86292   sqlite3 *db = pParse->db;
86293   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
86294     int iSkip = 0;
86295     Vdbe *v = sqlite3GetVdbe(pParse);
86296 
86297     assert( v );                  /* VDBE has already been allocated */
86298     if( sqlite3FkReferences(pTab)==0 ){
86299       /* Search for a deferred foreign key constraint for which this table
86300       ** is the child table. If one cannot be found, return without
86301       ** generating any VDBE code. If one can be found, then jump over
86302       ** the entire DELETE if there are no outstanding deferred constraints
86303       ** when this statement is run.  */
86304       FKey *p;
86305       for(p=pTab->pFKey; p; p=p->pNextFrom){
86306         if( p->isDeferred ) break;
86307       }
86308       if( !p ) return;
86309       iSkip = sqlite3VdbeMakeLabel(v);
86310       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
86311     }
86312 
86313     pParse->disableTriggers = 1;
86314     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
86315     pParse->disableTriggers = 0;
86316 
86317     /* If the DELETE has generated immediate foreign key constraint
86318     ** violations, halt the VDBE and return an error at this point, before
86319     ** any modifications to the schema are made. This is because statement
86320     ** transactions are not able to rollback schema changes.  */
86321     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
86322     sqlite3HaltConstraint(
86323         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
86324     );
86325 
86326     if( iSkip ){
86327       sqlite3VdbeResolveLabel(v, iSkip);
86328     }
86329   }
86330 }
86331 
86332 /*
86333 ** This function is called when inserting, deleting or updating a row of
86334 ** table pTab to generate VDBE code to perform foreign key constraint
86335 ** processing for the operation.
86336 **
86337 ** For a DELETE operation, parameter regOld is passed the index of the
86338 ** first register in an array of (pTab->nCol+1) registers containing the
86339 ** rowid of the row being deleted, followed by each of the column values
86340 ** of the row being deleted, from left to right. Parameter regNew is passed
86341 ** zero in this case.
86342 **
86343 ** For an INSERT operation, regOld is passed zero and regNew is passed the
86344 ** first register of an array of (pTab->nCol+1) registers containing the new
86345 ** row data.
86346 **
86347 ** For an UPDATE operation, this function is called twice. Once before
86348 ** the original record is deleted from the table using the calling convention
86349 ** described for DELETE. Then again after the original record is deleted
86350 ** but before the new record is inserted using the INSERT convention.
86351 */
86352 SQLITE_PRIVATE void sqlite3FkCheck(
86353   Parse *pParse,                  /* Parse context */
86354   Table *pTab,                    /* Row is being deleted from this table */
86355   int regOld,                     /* Previous row data is stored here */
86356   int regNew                      /* New row data is stored here */
86357 ){
86358   sqlite3 *db = pParse->db;       /* Database handle */
86359   FKey *pFKey;                    /* Used to iterate through FKs */
86360   int iDb;                        /* Index of database containing pTab */
86361   const char *zDb;                /* Name of database containing pTab */
86362   int isIgnoreErrors = pParse->disableTriggers;
86363 
86364   /* Exactly one of regOld and regNew should be non-zero. */
86365   assert( (regOld==0)!=(regNew==0) );
86366 
86367   /* If foreign-keys are disabled, this function is a no-op. */
86368   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
86369 
86370   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86371   zDb = db->aDb[iDb].zName;
86372 
86373   /* Loop through all the foreign key constraints for which pTab is the
86374   ** child table (the table that the foreign key definition is part of).  */
86375   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
86376     Table *pTo;                   /* Parent table of foreign key pFKey */
86377     Index *pIdx = 0;              /* Index on key columns in pTo */
86378     int *aiFree = 0;
86379     int *aiCol;
86380     int iCol;
86381     int i;
86382     int isIgnore = 0;
86383 
86384     /* Find the parent table of this foreign key. Also find a unique index
86385     ** on the parent key columns in the parent table. If either of these
86386     ** schema items cannot be located, set an error in pParse and return
86387     ** early.  */
86388     if( pParse->disableTriggers ){
86389       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
86390     }else{
86391       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
86392     }
86393     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
86394       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
86395       if( !isIgnoreErrors || db->mallocFailed ) return;
86396       if( pTo==0 ){
86397         /* If isIgnoreErrors is true, then a table is being dropped. In this
86398         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
86399         ** before actually dropping it in order to check FK constraints.
86400         ** If the parent table of an FK constraint on the current table is
86401         ** missing, behave as if it is empty. i.e. decrement the relevant
86402         ** FK counter for each row of the current table with non-NULL keys.
86403         */
86404         Vdbe *v = sqlite3GetVdbe(pParse);
86405         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
86406         for(i=0; i<pFKey->nCol; i++){
86407           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
86408           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
86409         }
86410         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
86411       }
86412       continue;
86413     }
86414     assert( pFKey->nCol==1 || (aiFree && pIdx) );
86415 
86416     if( aiFree ){
86417       aiCol = aiFree;
86418     }else{
86419       iCol = pFKey->aCol[0].iFrom;
86420       aiCol = &iCol;
86421     }
86422     for(i=0; i<pFKey->nCol; i++){
86423       if( aiCol[i]==pTab->iPKey ){
86424         aiCol[i] = -1;
86425       }
86426 #ifndef SQLITE_OMIT_AUTHORIZATION
86427       /* Request permission to read the parent key columns. If the
86428       ** authorization callback returns SQLITE_IGNORE, behave as if any
86429       ** values read from the parent table are NULL. */
86430       if( db->xAuth ){
86431         int rcauth;
86432         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
86433         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
86434         isIgnore = (rcauth==SQLITE_IGNORE);
86435       }
86436 #endif
86437     }
86438 
86439     /* Take a shared-cache advisory read-lock on the parent table. Allocate
86440     ** a cursor to use to search the unique index on the parent key columns
86441     ** in the parent table.  */
86442     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
86443     pParse->nTab++;
86444 
86445     if( regOld!=0 ){
86446       /* A row is being removed from the child table. Search for the parent.
86447       ** If the parent does not exist, removing the child row resolves an
86448       ** outstanding foreign key constraint violation. */
86449       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
86450     }
86451     if( regNew!=0 ){
86452       /* A row is being added to the child table. If a parent row cannot
86453       ** be found, adding the child row has violated the FK constraint. */
86454       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
86455     }
86456 
86457     sqlite3DbFree(db, aiFree);
86458   }
86459 
86460   /* Loop through all the foreign key constraints that refer to this table */
86461   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
86462     Index *pIdx = 0;              /* Foreign key index for pFKey */
86463     SrcList *pSrc;
86464     int *aiCol = 0;
86465 
86466     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
86467       assert( regOld==0 && regNew!=0 );
86468       /* Inserting a single row into a parent table cannot cause an immediate
86469       ** foreign key violation. So do nothing in this case.  */
86470       continue;
86471     }
86472 
86473     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
86474       if( !isIgnoreErrors || db->mallocFailed ) return;
86475       continue;
86476     }
86477     assert( aiCol || pFKey->nCol==1 );
86478 
86479     /* Create a SrcList structure containing a single table (the table
86480     ** the foreign key that refers to this table is attached to). This
86481     ** is required for the sqlite3WhereXXX() interface.  */
86482     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
86483     if( pSrc ){
86484       struct SrcList_item *pItem = pSrc->a;
86485       pItem->pTab = pFKey->pFrom;
86486       pItem->zName = pFKey->pFrom->zName;
86487       pItem->pTab->nRef++;
86488       pItem->iCursor = pParse->nTab++;
86489 
86490       if( regNew!=0 ){
86491         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
86492       }
86493       if( regOld!=0 ){
86494         /* If there is a RESTRICT action configured for the current operation
86495         ** on the parent table of this FK, then throw an exception
86496         ** immediately if the FK constraint is violated, even if this is a
86497         ** deferred trigger. That's what RESTRICT means. To defer checking
86498         ** the constraint, the FK should specify NO ACTION (represented
86499         ** using OE_None). NO ACTION is the default.  */
86500         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
86501       }
86502       pItem->zName = 0;
86503       sqlite3SrcListDelete(db, pSrc);
86504     }
86505     sqlite3DbFree(db, aiCol);
86506   }
86507 }
86508 
86509 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
86510 
86511 /*
86512 ** This function is called before generating code to update or delete a
86513 ** row contained in table pTab.
86514 */
86515 SQLITE_PRIVATE u32 sqlite3FkOldmask(
86516   Parse *pParse,                  /* Parse context */
86517   Table *pTab                     /* Table being modified */
86518 ){
86519   u32 mask = 0;
86520   if( pParse->db->flags&SQLITE_ForeignKeys ){
86521     FKey *p;
86522     int i;
86523     for(p=pTab->pFKey; p; p=p->pNextFrom){
86524       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
86525     }
86526     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
86527       Index *pIdx = 0;
86528       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
86529       if( pIdx ){
86530         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
86531       }
86532     }
86533   }
86534   return mask;
86535 }
86536 
86537 /*
86538 ** This function is called before generating code to update or delete a
86539 ** row contained in table pTab. If the operation is a DELETE, then
86540 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
86541 ** to an array of size N, where N is the number of columns in table pTab.
86542 ** If the i'th column is not modified by the UPDATE, then the corresponding
86543 ** entry in the aChange[] array is set to -1. If the column is modified,
86544 ** the value is 0 or greater. Parameter chngRowid is set to true if the
86545 ** UPDATE statement modifies the rowid fields of the table.
86546 **
86547 ** If any foreign key processing will be required, this function returns
86548 ** true. If there is no foreign key related processing, this function
86549 ** returns false.
86550 */
86551 SQLITE_PRIVATE int sqlite3FkRequired(
86552   Parse *pParse,                  /* Parse context */
86553   Table *pTab,                    /* Table being modified */
86554   int *aChange,                   /* Non-NULL for UPDATE operations */
86555   int chngRowid                   /* True for UPDATE that affects rowid */
86556 ){
86557   if( pParse->db->flags&SQLITE_ForeignKeys ){
86558     if( !aChange ){
86559       /* A DELETE operation. Foreign key processing is required if the
86560       ** table in question is either the child or parent table for any
86561       ** foreign key constraint.  */
86562       return (sqlite3FkReferences(pTab) || pTab->pFKey);
86563     }else{
86564       /* This is an UPDATE. Foreign key processing is only required if the
86565       ** operation modifies one or more child or parent key columns. */
86566       int i;
86567       FKey *p;
86568 
86569       /* Check if any child key columns are being modified. */
86570       for(p=pTab->pFKey; p; p=p->pNextFrom){
86571         for(i=0; i<p->nCol; i++){
86572           int iChildKey = p->aCol[i].iFrom;
86573           if( aChange[iChildKey]>=0 ) return 1;
86574           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
86575         }
86576       }
86577 
86578       /* Check if any parent key columns are being modified. */
86579       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
86580         for(i=0; i<p->nCol; i++){
86581           char *zKey = p->aCol[i].zCol;
86582           int iKey;
86583           for(iKey=0; iKey<pTab->nCol; iKey++){
86584             Column *pCol = &pTab->aCol[iKey];
86585             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
86586               if( aChange[iKey]>=0 ) return 1;
86587               if( iKey==pTab->iPKey && chngRowid ) return 1;
86588             }
86589           }
86590         }
86591       }
86592     }
86593   }
86594   return 0;
86595 }
86596 
86597 /*
86598 ** This function is called when an UPDATE or DELETE operation is being
86599 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
86600 ** If the current operation is an UPDATE, then the pChanges parameter is
86601 ** passed a pointer to the list of columns being modified. If it is a
86602 ** DELETE, pChanges is passed a NULL pointer.
86603 **
86604 ** It returns a pointer to a Trigger structure containing a trigger
86605 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
86606 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
86607 ** returned (these actions require no special handling by the triggers
86608 ** sub-system, code for them is created by fkScanChildren()).
86609 **
86610 ** For example, if pFKey is the foreign key and pTab is table "p" in
86611 ** the following schema:
86612 **
86613 **   CREATE TABLE p(pk PRIMARY KEY);
86614 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
86615 **
86616 ** then the returned trigger structure is equivalent to:
86617 **
86618 **   CREATE TRIGGER ... DELETE ON p BEGIN
86619 **     DELETE FROM c WHERE ck = old.pk;
86620 **   END;
86621 **
86622 ** The returned pointer is cached as part of the foreign key object. It
86623 ** is eventually freed along with the rest of the foreign key object by
86624 ** sqlite3FkDelete().
86625 */
86626 static Trigger *fkActionTrigger(
86627   Parse *pParse,                  /* Parse context */
86628   Table *pTab,                    /* Table being updated or deleted from */
86629   FKey *pFKey,                    /* Foreign key to get action for */
86630   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
86631 ){
86632   sqlite3 *db = pParse->db;       /* Database handle */
86633   int action;                     /* One of OE_None, OE_Cascade etc. */
86634   Trigger *pTrigger;              /* Trigger definition to return */
86635   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
86636 
86637   action = pFKey->aAction[iAction];
86638   pTrigger = pFKey->apTrigger[iAction];
86639 
86640   if( action!=OE_None && !pTrigger ){
86641     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
86642     char const *zFrom;            /* Name of child table */
86643     int nFrom;                    /* Length in bytes of zFrom */
86644     Index *pIdx = 0;              /* Parent key index for this FK */
86645     int *aiCol = 0;               /* child table cols -> parent key cols */
86646     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
86647     Expr *pWhere = 0;             /* WHERE clause of trigger step */
86648     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
86649     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
86650     int i;                        /* Iterator variable */
86651     Expr *pWhen = 0;              /* WHEN clause for the trigger */
86652 
86653     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
86654     assert( aiCol || pFKey->nCol==1 );
86655 
86656     for(i=0; i<pFKey->nCol; i++){
86657       Token tOld = { "old", 3 };  /* Literal "old" token */
86658       Token tNew = { "new", 3 };  /* Literal "new" token */
86659       Token tFromCol;             /* Name of column in child table */
86660       Token tToCol;               /* Name of column in parent table */
86661       int iFromCol;               /* Idx of column in child table */
86662       Expr *pEq;                  /* tFromCol = OLD.tToCol */
86663 
86664       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
86665       assert( iFromCol>=0 );
86666       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
86667       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
86668 
86669       tToCol.n = sqlite3Strlen30(tToCol.z);
86670       tFromCol.n = sqlite3Strlen30(tFromCol.z);
86671 
86672       /* Create the expression "OLD.zToCol = zFromCol". It is important
86673       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
86674       ** that the affinity and collation sequence associated with the
86675       ** parent table are used for the comparison. */
86676       pEq = sqlite3PExpr(pParse, TK_EQ,
86677           sqlite3PExpr(pParse, TK_DOT,
86678             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
86679             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
86680           , 0),
86681           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
86682       , 0);
86683       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
86684 
86685       /* For ON UPDATE, construct the next term of the WHEN clause.
86686       ** The final WHEN clause will be like this:
86687       **
86688       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
86689       */
86690       if( pChanges ){
86691         pEq = sqlite3PExpr(pParse, TK_IS,
86692             sqlite3PExpr(pParse, TK_DOT,
86693               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
86694               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
86695               0),
86696             sqlite3PExpr(pParse, TK_DOT,
86697               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
86698               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
86699               0),
86700             0);
86701         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
86702       }
86703 
86704       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
86705         Expr *pNew;
86706         if( action==OE_Cascade ){
86707           pNew = sqlite3PExpr(pParse, TK_DOT,
86708             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
86709             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
86710           , 0);
86711         }else if( action==OE_SetDflt ){
86712           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
86713           if( pDflt ){
86714             pNew = sqlite3ExprDup(db, pDflt, 0);
86715           }else{
86716             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
86717           }
86718         }else{
86719           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
86720         }
86721         pList = sqlite3ExprListAppend(pParse, pList, pNew);
86722         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
86723       }
86724     }
86725     sqlite3DbFree(db, aiCol);
86726 
86727     zFrom = pFKey->pFrom->zName;
86728     nFrom = sqlite3Strlen30(zFrom);
86729 
86730     if( action==OE_Restrict ){
86731       Token tFrom;
86732       Expr *pRaise;
86733 
86734       tFrom.z = zFrom;
86735       tFrom.n = nFrom;
86736       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
86737       if( pRaise ){
86738         pRaise->affinity = OE_Abort;
86739       }
86740       pSelect = sqlite3SelectNew(pParse,
86741           sqlite3ExprListAppend(pParse, 0, pRaise),
86742           sqlite3SrcListAppend(db, 0, &tFrom, 0),
86743           pWhere,
86744           0, 0, 0, 0, 0, 0
86745       );
86746       pWhere = 0;
86747     }
86748 
86749     /* Disable lookaside memory allocation */
86750     enableLookaside = db->lookaside.bEnabled;
86751     db->lookaside.bEnabled = 0;
86752 
86753     pTrigger = (Trigger *)sqlite3DbMallocZero(db,
86754         sizeof(Trigger) +         /* struct Trigger */
86755         sizeof(TriggerStep) +     /* Single step in trigger program */
86756         nFrom + 1                 /* Space for pStep->target.z */
86757     );
86758     if( pTrigger ){
86759       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
86760       pStep->target.z = (char *)&pStep[1];
86761       pStep->target.n = nFrom;
86762       memcpy((char *)pStep->target.z, zFrom, nFrom);
86763 
86764       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
86765       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
86766       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
86767       if( pWhen ){
86768         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
86769         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
86770       }
86771     }
86772 
86773     /* Re-enable the lookaside buffer, if it was disabled earlier. */
86774     db->lookaside.bEnabled = enableLookaside;
86775 
86776     sqlite3ExprDelete(db, pWhere);
86777     sqlite3ExprDelete(db, pWhen);
86778     sqlite3ExprListDelete(db, pList);
86779     sqlite3SelectDelete(db, pSelect);
86780     if( db->mallocFailed==1 ){
86781       fkTriggerDelete(db, pTrigger);
86782       return 0;
86783     }
86784 
86785     switch( action ){
86786       case OE_Restrict:
86787         pStep->op = TK_SELECT;
86788         break;
86789       case OE_Cascade:
86790         if( !pChanges ){
86791           pStep->op = TK_DELETE;
86792           break;
86793         }
86794       default:
86795         pStep->op = TK_UPDATE;
86796     }
86797     pStep->pTrig = pTrigger;
86798     pTrigger->pSchema = pTab->pSchema;
86799     pTrigger->pTabSchema = pTab->pSchema;
86800     pFKey->apTrigger[iAction] = pTrigger;
86801     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
86802   }
86803 
86804   return pTrigger;
86805 }
86806 
86807 /*
86808 ** This function is called when deleting or updating a row to implement
86809 ** any required CASCADE, SET NULL or SET DEFAULT actions.
86810 */
86811 SQLITE_PRIVATE void sqlite3FkActions(
86812   Parse *pParse,                  /* Parse context */
86813   Table *pTab,                    /* Table being updated or deleted from */
86814   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
86815   int regOld                      /* Address of array containing old row */
86816 ){
86817   /* If foreign-key support is enabled, iterate through all FKs that
86818   ** refer to table pTab. If there is an action associated with the FK
86819   ** for this operation (either update or delete), invoke the associated
86820   ** trigger sub-program.  */
86821   if( pParse->db->flags&SQLITE_ForeignKeys ){
86822     FKey *pFKey;                  /* Iterator variable */
86823     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
86824       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
86825       if( pAction ){
86826         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
86827       }
86828     }
86829   }
86830 }
86831 
86832 #endif /* ifndef SQLITE_OMIT_TRIGGER */
86833 
86834 /*
86835 ** Free all memory associated with foreign key definitions attached to
86836 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
86837 ** hash table.
86838 */
86839 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
86840   FKey *pFKey;                    /* Iterator variable */
86841   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
86842 
86843   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
86844   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
86845 
86846     /* Remove the FK from the fkeyHash hash table. */
86847     if( !db || db->pnBytesFreed==0 ){
86848       if( pFKey->pPrevTo ){
86849         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
86850       }else{
86851         void *p = (void *)pFKey->pNextTo;
86852         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
86853         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
86854       }
86855       if( pFKey->pNextTo ){
86856         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
86857       }
86858     }
86859 
86860     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
86861     ** classified as either immediate or deferred.
86862     */
86863     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
86864 
86865     /* Delete any triggers created to implement actions for this FK. */
86866 #ifndef SQLITE_OMIT_TRIGGER
86867     fkTriggerDelete(db, pFKey->apTrigger[0]);
86868     fkTriggerDelete(db, pFKey->apTrigger[1]);
86869 #endif
86870 
86871     pNext = pFKey->pNextFrom;
86872     sqlite3DbFree(db, pFKey);
86873   }
86874 }
86875 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
86876 
86877 /************** End of fkey.c ************************************************/
86878 /************** Begin file insert.c ******************************************/
86879 /*
86880 ** 2001 September 15
86881 **
86882 ** The author disclaims copyright to this source code.  In place of
86883 ** a legal notice, here is a blessing:
86884 **
86885 **    May you do good and not evil.
86886 **    May you find forgiveness for yourself and forgive others.
86887 **    May you share freely, never taking more than you give.
86888 **
86889 *************************************************************************
86890 ** This file contains C code routines that are called by the parser
86891 ** to handle INSERT statements in SQLite.
86892 */
86893 
86894 /*
86895 ** Generate code that will open a table for reading.
86896 */
86897 SQLITE_PRIVATE void sqlite3OpenTable(
86898   Parse *p,       /* Generate code into this VDBE */
86899   int iCur,       /* The cursor number of the table */
86900   int iDb,        /* The database index in sqlite3.aDb[] */
86901   Table *pTab,    /* The table to be opened */
86902   int opcode      /* OP_OpenRead or OP_OpenWrite */
86903 ){
86904   Vdbe *v;
86905   if( IsVirtual(pTab) ) return;
86906   v = sqlite3GetVdbe(p);
86907   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
86908   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
86909   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
86910   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
86911   VdbeComment((v, "%s", pTab->zName));
86912 }
86913 
86914 /*
86915 ** Return a pointer to the column affinity string associated with index
86916 ** pIdx. A column affinity string has one character for each column in
86917 ** the table, according to the affinity of the column:
86918 **
86919 **  Character      Column affinity
86920 **  ------------------------------
86921 **  'a'            TEXT
86922 **  'b'            NONE
86923 **  'c'            NUMERIC
86924 **  'd'            INTEGER
86925 **  'e'            REAL
86926 **
86927 ** An extra 'b' is appended to the end of the string to cover the
86928 ** rowid that appears as the last column in every index.
86929 **
86930 ** Memory for the buffer containing the column index affinity string
86931 ** is managed along with the rest of the Index structure. It will be
86932 ** released when sqlite3DeleteIndex() is called.
86933 */
86934 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
86935   if( !pIdx->zColAff ){
86936     /* The first time a column affinity string for a particular index is
86937     ** required, it is allocated and populated here. It is then stored as
86938     ** a member of the Index structure for subsequent use.
86939     **
86940     ** The column affinity string will eventually be deleted by
86941     ** sqliteDeleteIndex() when the Index structure itself is cleaned
86942     ** up.
86943     */
86944     int n;
86945     Table *pTab = pIdx->pTable;
86946     sqlite3 *db = sqlite3VdbeDb(v);
86947     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
86948     if( !pIdx->zColAff ){
86949       db->mallocFailed = 1;
86950       return 0;
86951     }
86952     for(n=0; n<pIdx->nColumn; n++){
86953       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
86954     }
86955     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
86956     pIdx->zColAff[n] = 0;
86957   }
86958 
86959   return pIdx->zColAff;
86960 }
86961 
86962 /*
86963 ** Set P4 of the most recently inserted opcode to a column affinity
86964 ** string for table pTab. A column affinity string has one character
86965 ** for each column indexed by the index, according to the affinity of the
86966 ** column:
86967 **
86968 **  Character      Column affinity
86969 **  ------------------------------
86970 **  'a'            TEXT
86971 **  'b'            NONE
86972 **  'c'            NUMERIC
86973 **  'd'            INTEGER
86974 **  'e'            REAL
86975 */
86976 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
86977   /* The first time a column affinity string for a particular table
86978   ** is required, it is allocated and populated here. It is then
86979   ** stored as a member of the Table structure for subsequent use.
86980   **
86981   ** The column affinity string will eventually be deleted by
86982   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
86983   */
86984   if( !pTab->zColAff ){
86985     char *zColAff;
86986     int i;
86987     sqlite3 *db = sqlite3VdbeDb(v);
86988 
86989     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
86990     if( !zColAff ){
86991       db->mallocFailed = 1;
86992       return;
86993     }
86994 
86995     for(i=0; i<pTab->nCol; i++){
86996       zColAff[i] = pTab->aCol[i].affinity;
86997     }
86998     zColAff[pTab->nCol] = '\0';
86999 
87000     pTab->zColAff = zColAff;
87001   }
87002 
87003   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
87004 }
87005 
87006 /*
87007 ** Return non-zero if the table pTab in database iDb or any of its indices
87008 ** have been opened at any point in the VDBE program beginning at location
87009 ** iStartAddr throught the end of the program.  This is used to see if
87010 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
87011 ** run without using temporary table for the results of the SELECT.
87012 */
87013 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
87014   Vdbe *v = sqlite3GetVdbe(p);
87015   int i;
87016   int iEnd = sqlite3VdbeCurrentAddr(v);
87017 #ifndef SQLITE_OMIT_VIRTUALTABLE
87018   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
87019 #endif
87020 
87021   for(i=iStartAddr; i<iEnd; i++){
87022     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
87023     assert( pOp!=0 );
87024     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
87025       Index *pIndex;
87026       int tnum = pOp->p2;
87027       if( tnum==pTab->tnum ){
87028         return 1;
87029       }
87030       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
87031         if( tnum==pIndex->tnum ){
87032           return 1;
87033         }
87034       }
87035     }
87036 #ifndef SQLITE_OMIT_VIRTUALTABLE
87037     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
87038       assert( pOp->p4.pVtab!=0 );
87039       assert( pOp->p4type==P4_VTAB );
87040       return 1;
87041     }
87042 #endif
87043   }
87044   return 0;
87045 }
87046 
87047 #ifndef SQLITE_OMIT_AUTOINCREMENT
87048 /*
87049 ** Locate or create an AutoincInfo structure associated with table pTab
87050 ** which is in database iDb.  Return the register number for the register
87051 ** that holds the maximum rowid.
87052 **
87053 ** There is at most one AutoincInfo structure per table even if the
87054 ** same table is autoincremented multiple times due to inserts within
87055 ** triggers.  A new AutoincInfo structure is created if this is the
87056 ** first use of table pTab.  On 2nd and subsequent uses, the original
87057 ** AutoincInfo structure is used.
87058 **
87059 ** Three memory locations are allocated:
87060 **
87061 **   (1)  Register to hold the name of the pTab table.
87062 **   (2)  Register to hold the maximum ROWID of pTab.
87063 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
87064 **
87065 ** The 2nd register is the one that is returned.  That is all the
87066 ** insert routine needs to know about.
87067 */
87068 static int autoIncBegin(
87069   Parse *pParse,      /* Parsing context */
87070   int iDb,            /* Index of the database holding pTab */
87071   Table *pTab         /* The table we are writing to */
87072 ){
87073   int memId = 0;      /* Register holding maximum rowid */
87074   if( pTab->tabFlags & TF_Autoincrement ){
87075     Parse *pToplevel = sqlite3ParseToplevel(pParse);
87076     AutoincInfo *pInfo;
87077 
87078     pInfo = pToplevel->pAinc;
87079     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
87080     if( pInfo==0 ){
87081       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
87082       if( pInfo==0 ) return 0;
87083       pInfo->pNext = pToplevel->pAinc;
87084       pToplevel->pAinc = pInfo;
87085       pInfo->pTab = pTab;
87086       pInfo->iDb = iDb;
87087       pToplevel->nMem++;                  /* Register to hold name of table */
87088       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
87089       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
87090     }
87091     memId = pInfo->regCtr;
87092   }
87093   return memId;
87094 }
87095 
87096 /*
87097 ** This routine generates code that will initialize all of the
87098 ** register used by the autoincrement tracker.
87099 */
87100 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
87101   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
87102   sqlite3 *db = pParse->db;  /* The database connection */
87103   Db *pDb;                   /* Database only autoinc table */
87104   int memId;                 /* Register holding max rowid */
87105   int addr;                  /* A VDBE address */
87106   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
87107 
87108   /* This routine is never called during trigger-generation.  It is
87109   ** only called from the top-level */
87110   assert( pParse->pTriggerTab==0 );
87111   assert( pParse==sqlite3ParseToplevel(pParse) );
87112 
87113   assert( v );   /* We failed long ago if this is not so */
87114   for(p = pParse->pAinc; p; p = p->pNext){
87115     pDb = &db->aDb[p->iDb];
87116     memId = p->regCtr;
87117     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
87118     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
87119     addr = sqlite3VdbeCurrentAddr(v);
87120     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
87121     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
87122     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
87123     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
87124     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
87125     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
87126     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
87127     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
87128     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
87129     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
87130     sqlite3VdbeAddOp0(v, OP_Close);
87131   }
87132 }
87133 
87134 /*
87135 ** Update the maximum rowid for an autoincrement calculation.
87136 **
87137 ** This routine should be called when the top of the stack holds a
87138 ** new rowid that is about to be inserted.  If that new rowid is
87139 ** larger than the maximum rowid in the memId memory cell, then the
87140 ** memory cell is updated.  The stack is unchanged.
87141 */
87142 static void autoIncStep(Parse *pParse, int memId, int regRowid){
87143   if( memId>0 ){
87144     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
87145   }
87146 }
87147 
87148 /*
87149 ** This routine generates the code needed to write autoincrement
87150 ** maximum rowid values back into the sqlite_sequence register.
87151 ** Every statement that might do an INSERT into an autoincrement
87152 ** table (either directly or through triggers) needs to call this
87153 ** routine just before the "exit" code.
87154 */
87155 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
87156   AutoincInfo *p;
87157   Vdbe *v = pParse->pVdbe;
87158   sqlite3 *db = pParse->db;
87159 
87160   assert( v );
87161   for(p = pParse->pAinc; p; p = p->pNext){
87162     Db *pDb = &db->aDb[p->iDb];
87163     int j1, j2, j3, j4, j5;
87164     int iRec;
87165     int memId = p->regCtr;
87166 
87167     iRec = sqlite3GetTempReg(pParse);
87168     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
87169     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
87170     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
87171     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
87172     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
87173     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
87174     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
87175     sqlite3VdbeJumpHere(v, j2);
87176     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
87177     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
87178     sqlite3VdbeJumpHere(v, j4);
87179     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
87180     sqlite3VdbeJumpHere(v, j1);
87181     sqlite3VdbeJumpHere(v, j5);
87182     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
87183     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
87184     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
87185     sqlite3VdbeAddOp0(v, OP_Close);
87186     sqlite3ReleaseTempReg(pParse, iRec);
87187   }
87188 }
87189 #else
87190 /*
87191 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
87192 ** above are all no-ops
87193 */
87194 # define autoIncBegin(A,B,C) (0)
87195 # define autoIncStep(A,B,C)
87196 #endif /* SQLITE_OMIT_AUTOINCREMENT */
87197 
87198 
87199 /* Forward declaration */
87200 static int xferOptimization(
87201   Parse *pParse,        /* Parser context */
87202   Table *pDest,         /* The table we are inserting into */
87203   Select *pSelect,      /* A SELECT statement to use as the data source */
87204   int onError,          /* How to handle constraint errors */
87205   int iDbDest           /* The database of pDest */
87206 );
87207 
87208 /*
87209 ** This routine is call to handle SQL of the following forms:
87210 **
87211 **    insert into TABLE (IDLIST) values(EXPRLIST)
87212 **    insert into TABLE (IDLIST) select
87213 **
87214 ** The IDLIST following the table name is always optional.  If omitted,
87215 ** then a list of all columns for the table is substituted.  The IDLIST
87216 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
87217 **
87218 ** The pList parameter holds EXPRLIST in the first form of the INSERT
87219 ** statement above, and pSelect is NULL.  For the second form, pList is
87220 ** NULL and pSelect is a pointer to the select statement used to generate
87221 ** data for the insert.
87222 **
87223 ** The code generated follows one of four templates.  For a simple
87224 ** select with data coming from a VALUES clause, the code executes
87225 ** once straight down through.  Pseudo-code follows (we call this
87226 ** the "1st template"):
87227 **
87228 **         open write cursor to <table> and its indices
87229 **         puts VALUES clause expressions onto the stack
87230 **         write the resulting record into <table>
87231 **         cleanup
87232 **
87233 ** The three remaining templates assume the statement is of the form
87234 **
87235 **   INSERT INTO <table> SELECT ...
87236 **
87237 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
87238 ** in other words if the SELECT pulls all columns from a single table
87239 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
87240 ** if <table2> and <table1> are distinct tables but have identical
87241 ** schemas, including all the same indices, then a special optimization
87242 ** is invoked that copies raw records from <table2> over to <table1>.
87243 ** See the xferOptimization() function for the implementation of this
87244 ** template.  This is the 2nd template.
87245 **
87246 **         open a write cursor to <table>
87247 **         open read cursor on <table2>
87248 **         transfer all records in <table2> over to <table>
87249 **         close cursors
87250 **         foreach index on <table>
87251 **           open a write cursor on the <table> index
87252 **           open a read cursor on the corresponding <table2> index
87253 **           transfer all records from the read to the write cursors
87254 **           close cursors
87255 **         end foreach
87256 **
87257 ** The 3rd template is for when the second template does not apply
87258 ** and the SELECT clause does not read from <table> at any time.
87259 ** The generated code follows this template:
87260 **
87261 **         EOF <- 0
87262 **         X <- A
87263 **         goto B
87264 **      A: setup for the SELECT
87265 **         loop over the rows in the SELECT
87266 **           load values into registers R..R+n
87267 **           yield X
87268 **         end loop
87269 **         cleanup after the SELECT
87270 **         EOF <- 1
87271 **         yield X
87272 **         goto A
87273 **      B: open write cursor to <table> and its indices
87274 **      C: yield X
87275 **         if EOF goto D
87276 **         insert the select result into <table> from R..R+n
87277 **         goto C
87278 **      D: cleanup
87279 **
87280 ** The 4th template is used if the insert statement takes its
87281 ** values from a SELECT but the data is being inserted into a table
87282 ** that is also read as part of the SELECT.  In the third form,
87283 ** we have to use a intermediate table to store the results of
87284 ** the select.  The template is like this:
87285 **
87286 **         EOF <- 0
87287 **         X <- A
87288 **         goto B
87289 **      A: setup for the SELECT
87290 **         loop over the tables in the SELECT
87291 **           load value into register R..R+n
87292 **           yield X
87293 **         end loop
87294 **         cleanup after the SELECT
87295 **         EOF <- 1
87296 **         yield X
87297 **         halt-error
87298 **      B: open temp table
87299 **      L: yield X
87300 **         if EOF goto M
87301 **         insert row from R..R+n into temp table
87302 **         goto L
87303 **      M: open write cursor to <table> and its indices
87304 **         rewind temp table
87305 **      C: loop over rows of intermediate table
87306 **           transfer values form intermediate table into <table>
87307 **         end loop
87308 **      D: cleanup
87309 */
87310 SQLITE_PRIVATE void sqlite3Insert(
87311   Parse *pParse,        /* Parser context */
87312   SrcList *pTabList,    /* Name of table into which we are inserting */
87313   ExprList *pList,      /* List of values to be inserted */
87314   Select *pSelect,      /* A SELECT statement to use as the data source */
87315   IdList *pColumn,      /* Column names corresponding to IDLIST. */
87316   int onError           /* How to handle constraint errors */
87317 ){
87318   sqlite3 *db;          /* The main database structure */
87319   Table *pTab;          /* The table to insert into.  aka TABLE */
87320   char *zTab;           /* Name of the table into which we are inserting */
87321   const char *zDb;      /* Name of the database holding this table */
87322   int i, j, idx;        /* Loop counters */
87323   Vdbe *v;              /* Generate code into this virtual machine */
87324   Index *pIdx;          /* For looping over indices of the table */
87325   int nColumn;          /* Number of columns in the data */
87326   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
87327   int baseCur = 0;      /* VDBE Cursor number for pTab */
87328   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
87329   int endOfLoop;        /* Label for the end of the insertion loop */
87330   int useTempTable = 0; /* Store SELECT results in intermediate table */
87331   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
87332   int addrInsTop = 0;   /* Jump to label "D" */
87333   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
87334   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
87335   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
87336   int iDb;              /* Index of database holding TABLE */
87337   Db *pDb;              /* The database containing table being inserted into */
87338   int appendFlag = 0;   /* True if the insert is likely to be an append */
87339 
87340   /* Register allocations */
87341   int regFromSelect = 0;/* Base register for data coming from SELECT */
87342   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
87343   int regRowCount = 0;  /* Memory cell used for the row counter */
87344   int regIns;           /* Block of regs holding rowid+data being inserted */
87345   int regRowid;         /* registers holding insert rowid */
87346   int regData;          /* register holding first column to insert */
87347   int regEof = 0;       /* Register recording end of SELECT data */
87348   int *aRegIdx = 0;     /* One register allocated to each index */
87349 
87350 #ifndef SQLITE_OMIT_TRIGGER
87351   int isView;                 /* True if attempting to insert into a view */
87352   Trigger *pTrigger;          /* List of triggers on pTab, if required */
87353   int tmask;                  /* Mask of trigger times */
87354 #endif
87355 
87356   db = pParse->db;
87357   memset(&dest, 0, sizeof(dest));
87358   if( pParse->nErr || db->mallocFailed ){
87359     goto insert_cleanup;
87360   }
87361 
87362   /* Locate the table into which we will be inserting new information.
87363   */
87364   assert( pTabList->nSrc==1 );
87365   zTab = pTabList->a[0].zName;
87366   if( NEVER(zTab==0) ) goto insert_cleanup;
87367   pTab = sqlite3SrcListLookup(pParse, pTabList);
87368   if( pTab==0 ){
87369     goto insert_cleanup;
87370   }
87371   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87372   assert( iDb<db->nDb );
87373   pDb = &db->aDb[iDb];
87374   zDb = pDb->zName;
87375   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
87376     goto insert_cleanup;
87377   }
87378 
87379   /* Figure out if we have any triggers and if the table being
87380   ** inserted into is a view
87381   */
87382 #ifndef SQLITE_OMIT_TRIGGER
87383   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
87384   isView = pTab->pSelect!=0;
87385 #else
87386 # define pTrigger 0
87387 # define tmask 0
87388 # define isView 0
87389 #endif
87390 #ifdef SQLITE_OMIT_VIEW
87391 # undef isView
87392 # define isView 0
87393 #endif
87394   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
87395 
87396   /* If pTab is really a view, make sure it has been initialized.
87397   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
87398   ** module table).
87399   */
87400   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87401     goto insert_cleanup;
87402   }
87403 
87404   /* Ensure that:
87405   *  (a) the table is not read-only,
87406   *  (b) that if it is a view then ON INSERT triggers exist
87407   */
87408   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
87409     goto insert_cleanup;
87410   }
87411 
87412   /* Allocate a VDBE
87413   */
87414   v = sqlite3GetVdbe(pParse);
87415   if( v==0 ) goto insert_cleanup;
87416   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
87417   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
87418 
87419 #ifndef SQLITE_OMIT_XFER_OPT
87420   /* If the statement is of the form
87421   **
87422   **       INSERT INTO <table1> SELECT * FROM <table2>;
87423   **
87424   ** Then special optimizations can be applied that make the transfer
87425   ** very fast and which reduce fragmentation of indices.
87426   **
87427   ** This is the 2nd template.
87428   */
87429   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
87430     assert( !pTrigger );
87431     assert( pList==0 );
87432     goto insert_end;
87433   }
87434 #endif /* SQLITE_OMIT_XFER_OPT */
87435 
87436   /* If this is an AUTOINCREMENT table, look up the sequence number in the
87437   ** sqlite_sequence table and store it in memory cell regAutoinc.
87438   */
87439   regAutoinc = autoIncBegin(pParse, iDb, pTab);
87440 
87441   /* Figure out how many columns of data are supplied.  If the data
87442   ** is coming from a SELECT statement, then generate a co-routine that
87443   ** produces a single row of the SELECT on each invocation.  The
87444   ** co-routine is the common header to the 3rd and 4th templates.
87445   */
87446   if( pSelect ){
87447     /* Data is coming from a SELECT.  Generate code to implement that SELECT
87448     ** as a co-routine.  The code is common to both the 3rd and 4th
87449     ** templates:
87450     **
87451     **         EOF <- 0
87452     **         X <- A
87453     **         goto B
87454     **      A: setup for the SELECT
87455     **         loop over the tables in the SELECT
87456     **           load value into register R..R+n
87457     **           yield X
87458     **         end loop
87459     **         cleanup after the SELECT
87460     **         EOF <- 1
87461     **         yield X
87462     **         halt-error
87463     **
87464     ** On each invocation of the co-routine, it puts a single row of the
87465     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
87466     ** (These output registers are allocated by sqlite3Select().)  When
87467     ** the SELECT completes, it sets the EOF flag stored in regEof.
87468     */
87469     int rc, j1;
87470 
87471     regEof = ++pParse->nMem;
87472     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
87473     VdbeComment((v, "SELECT eof flag"));
87474     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
87475     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
87476     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
87477     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
87478     VdbeComment((v, "Jump over SELECT coroutine"));
87479 
87480     /* Resolve the expressions in the SELECT statement and execute it. */
87481     rc = sqlite3Select(pParse, pSelect, &dest);
87482     assert( pParse->nErr==0 || rc );
87483     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
87484       goto insert_cleanup;
87485     }
87486     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
87487     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
87488     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
87489     VdbeComment((v, "End of SELECT coroutine"));
87490     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
87491 
87492     regFromSelect = dest.iMem;
87493     assert( pSelect->pEList );
87494     nColumn = pSelect->pEList->nExpr;
87495     assert( dest.nMem==nColumn );
87496 
87497     /* Set useTempTable to TRUE if the result of the SELECT statement
87498     ** should be written into a temporary table (template 4).  Set to
87499     ** FALSE if each* row of the SELECT can be written directly into
87500     ** the destination table (template 3).
87501     **
87502     ** A temp table must be used if the table being updated is also one
87503     ** of the tables being read by the SELECT statement.  Also use a
87504     ** temp table in the case of row triggers.
87505     */
87506     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
87507       useTempTable = 1;
87508     }
87509 
87510     if( useTempTable ){
87511       /* Invoke the coroutine to extract information from the SELECT
87512       ** and add it to a transient table srcTab.  The code generated
87513       ** here is from the 4th template:
87514       **
87515       **      B: open temp table
87516       **      L: yield X
87517       **         if EOF goto M
87518       **         insert row from R..R+n into temp table
87519       **         goto L
87520       **      M: ...
87521       */
87522       int regRec;          /* Register to hold packed record */
87523       int regTempRowid;    /* Register to hold temp table ROWID */
87524       int addrTop;         /* Label "L" */
87525       int addrIf;          /* Address of jump to M */
87526 
87527       srcTab = pParse->nTab++;
87528       regRec = sqlite3GetTempReg(pParse);
87529       regTempRowid = sqlite3GetTempReg(pParse);
87530       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
87531       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
87532       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
87533       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
87534       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
87535       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
87536       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
87537       sqlite3VdbeJumpHere(v, addrIf);
87538       sqlite3ReleaseTempReg(pParse, regRec);
87539       sqlite3ReleaseTempReg(pParse, regTempRowid);
87540     }
87541   }else{
87542     /* This is the case if the data for the INSERT is coming from a VALUES
87543     ** clause
87544     */
87545     NameContext sNC;
87546     memset(&sNC, 0, sizeof(sNC));
87547     sNC.pParse = pParse;
87548     srcTab = -1;
87549     assert( useTempTable==0 );
87550     nColumn = pList ? pList->nExpr : 0;
87551     for(i=0; i<nColumn; i++){
87552       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
87553         goto insert_cleanup;
87554       }
87555     }
87556   }
87557 
87558   /* Make sure the number of columns in the source data matches the number
87559   ** of columns to be inserted into the table.
87560   */
87561   if( IsVirtual(pTab) ){
87562     for(i=0; i<pTab->nCol; i++){
87563       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
87564     }
87565   }
87566   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
87567     sqlite3ErrorMsg(pParse,
87568        "table %S has %d columns but %d values were supplied",
87569        pTabList, 0, pTab->nCol-nHidden, nColumn);
87570     goto insert_cleanup;
87571   }
87572   if( pColumn!=0 && nColumn!=pColumn->nId ){
87573     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
87574     goto insert_cleanup;
87575   }
87576 
87577   /* If the INSERT statement included an IDLIST term, then make sure
87578   ** all elements of the IDLIST really are columns of the table and
87579   ** remember the column indices.
87580   **
87581   ** If the table has an INTEGER PRIMARY KEY column and that column
87582   ** is named in the IDLIST, then record in the keyColumn variable
87583   ** the index into IDLIST of the primary key column.  keyColumn is
87584   ** the index of the primary key as it appears in IDLIST, not as
87585   ** is appears in the original table.  (The index of the primary
87586   ** key in the original table is pTab->iPKey.)
87587   */
87588   if( pColumn ){
87589     for(i=0; i<pColumn->nId; i++){
87590       pColumn->a[i].idx = -1;
87591     }
87592     for(i=0; i<pColumn->nId; i++){
87593       for(j=0; j<pTab->nCol; j++){
87594         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
87595           pColumn->a[i].idx = j;
87596           if( j==pTab->iPKey ){
87597             keyColumn = i;
87598           }
87599           break;
87600         }
87601       }
87602       if( j>=pTab->nCol ){
87603         if( sqlite3IsRowid(pColumn->a[i].zName) ){
87604           keyColumn = i;
87605         }else{
87606           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
87607               pTabList, 0, pColumn->a[i].zName);
87608           pParse->checkSchema = 1;
87609           goto insert_cleanup;
87610         }
87611       }
87612     }
87613   }
87614 
87615   /* If there is no IDLIST term but the table has an integer primary
87616   ** key, the set the keyColumn variable to the primary key column index
87617   ** in the original table definition.
87618   */
87619   if( pColumn==0 && nColumn>0 ){
87620     keyColumn = pTab->iPKey;
87621   }
87622 
87623   /* Initialize the count of rows to be inserted
87624   */
87625   if( db->flags & SQLITE_CountRows ){
87626     regRowCount = ++pParse->nMem;
87627     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
87628   }
87629 
87630   /* If this is not a view, open the table and and all indices */
87631   if( !isView ){
87632     int nIdx;
87633 
87634     baseCur = pParse->nTab;
87635     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
87636     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
87637     if( aRegIdx==0 ){
87638       goto insert_cleanup;
87639     }
87640     for(i=0; i<nIdx; i++){
87641       aRegIdx[i] = ++pParse->nMem;
87642     }
87643   }
87644 
87645   /* This is the top of the main insertion loop */
87646   if( useTempTable ){
87647     /* This block codes the top of loop only.  The complete loop is the
87648     ** following pseudocode (template 4):
87649     **
87650     **         rewind temp table
87651     **      C: loop over rows of intermediate table
87652     **           transfer values form intermediate table into <table>
87653     **         end loop
87654     **      D: ...
87655     */
87656     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
87657     addrCont = sqlite3VdbeCurrentAddr(v);
87658   }else if( pSelect ){
87659     /* This block codes the top of loop only.  The complete loop is the
87660     ** following pseudocode (template 3):
87661     **
87662     **      C: yield X
87663     **         if EOF goto D
87664     **         insert the select result into <table> from R..R+n
87665     **         goto C
87666     **      D: ...
87667     */
87668     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
87669     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
87670   }
87671 
87672   /* Allocate registers for holding the rowid of the new row,
87673   ** the content of the new row, and the assemblied row record.
87674   */
87675   regRowid = regIns = pParse->nMem+1;
87676   pParse->nMem += pTab->nCol + 1;
87677   if( IsVirtual(pTab) ){
87678     regRowid++;
87679     pParse->nMem++;
87680   }
87681   regData = regRowid+1;
87682 
87683   /* Run the BEFORE and INSTEAD OF triggers, if there are any
87684   */
87685   endOfLoop = sqlite3VdbeMakeLabel(v);
87686   if( tmask & TRIGGER_BEFORE ){
87687     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
87688 
87689     /* build the NEW.* reference row.  Note that if there is an INTEGER
87690     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
87691     ** translated into a unique ID for the row.  But on a BEFORE trigger,
87692     ** we do not know what the unique ID will be (because the insert has
87693     ** not happened yet) so we substitute a rowid of -1
87694     */
87695     if( keyColumn<0 ){
87696       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
87697     }else{
87698       int j1;
87699       if( useTempTable ){
87700         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
87701       }else{
87702         assert( pSelect==0 );  /* Otherwise useTempTable is true */
87703         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
87704       }
87705       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
87706       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
87707       sqlite3VdbeJumpHere(v, j1);
87708       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
87709     }
87710 
87711     /* Cannot have triggers on a virtual table. If it were possible,
87712     ** this block would have to account for hidden column.
87713     */
87714     assert( !IsVirtual(pTab) );
87715 
87716     /* Create the new column data
87717     */
87718     for(i=0; i<pTab->nCol; i++){
87719       if( pColumn==0 ){
87720         j = i;
87721       }else{
87722         for(j=0; j<pColumn->nId; j++){
87723           if( pColumn->a[j].idx==i ) break;
87724         }
87725       }
87726       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
87727         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
87728       }else if( useTempTable ){
87729         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
87730       }else{
87731         assert( pSelect==0 ); /* Otherwise useTempTable is true */
87732         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
87733       }
87734     }
87735 
87736     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
87737     ** do not attempt any conversions before assembling the record.
87738     ** If this is a real table, attempt conversions as required by the
87739     ** table column affinities.
87740     */
87741     if( !isView ){
87742       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
87743       sqlite3TableAffinityStr(v, pTab);
87744     }
87745 
87746     /* Fire BEFORE or INSTEAD OF triggers */
87747     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
87748         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
87749 
87750     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
87751   }
87752 
87753   /* Push the record number for the new entry onto the stack.  The
87754   ** record number is a randomly generate integer created by NewRowid
87755   ** except when the table has an INTEGER PRIMARY KEY column, in which
87756   ** case the record number is the same as that column.
87757   */
87758   if( !isView ){
87759     if( IsVirtual(pTab) ){
87760       /* The row that the VUpdate opcode will delete: none */
87761       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
87762     }
87763     if( keyColumn>=0 ){
87764       if( useTempTable ){
87765         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
87766       }else if( pSelect ){
87767         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
87768       }else{
87769         VdbeOp *pOp;
87770         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
87771         pOp = sqlite3VdbeGetOp(v, -1);
87772         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
87773           appendFlag = 1;
87774           pOp->opcode = OP_NewRowid;
87775           pOp->p1 = baseCur;
87776           pOp->p2 = regRowid;
87777           pOp->p3 = regAutoinc;
87778         }
87779       }
87780       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
87781       ** to generate a unique primary key value.
87782       */
87783       if( !appendFlag ){
87784         int j1;
87785         if( !IsVirtual(pTab) ){
87786           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
87787           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
87788           sqlite3VdbeJumpHere(v, j1);
87789         }else{
87790           j1 = sqlite3VdbeCurrentAddr(v);
87791           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
87792         }
87793         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
87794       }
87795     }else if( IsVirtual(pTab) ){
87796       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
87797     }else{
87798       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
87799       appendFlag = 1;
87800     }
87801     autoIncStep(pParse, regAutoinc, regRowid);
87802 
87803     /* Push onto the stack, data for all columns of the new entry, beginning
87804     ** with the first column.
87805     */
87806     nHidden = 0;
87807     for(i=0; i<pTab->nCol; i++){
87808       int iRegStore = regRowid+1+i;
87809       if( i==pTab->iPKey ){
87810         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
87811         ** Whenever this column is read, the record number will be substituted
87812         ** in its place.  So will fill this column with a NULL to avoid
87813         ** taking up data space with information that will never be used. */
87814         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
87815         continue;
87816       }
87817       if( pColumn==0 ){
87818         if( IsHiddenColumn(&pTab->aCol[i]) ){
87819           assert( IsVirtual(pTab) );
87820           j = -1;
87821           nHidden++;
87822         }else{
87823           j = i - nHidden;
87824         }
87825       }else{
87826         for(j=0; j<pColumn->nId; j++){
87827           if( pColumn->a[j].idx==i ) break;
87828         }
87829       }
87830       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
87831         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
87832       }else if( useTempTable ){
87833         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
87834       }else if( pSelect ){
87835         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
87836       }else{
87837         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
87838       }
87839     }
87840 
87841     /* Generate code to check constraints and generate index keys and
87842     ** do the insertion.
87843     */
87844 #ifndef SQLITE_OMIT_VIRTUALTABLE
87845     if( IsVirtual(pTab) ){
87846       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
87847       sqlite3VtabMakeWritable(pParse, pTab);
87848       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
87849       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
87850       sqlite3MayAbort(pParse);
87851     }else
87852 #endif
87853     {
87854       int isReplace;    /* Set to true if constraints may cause a replace */
87855       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
87856           keyColumn>=0, 0, onError, endOfLoop, &isReplace
87857       );
87858       sqlite3FkCheck(pParse, pTab, 0, regIns);
87859       sqlite3CompleteInsertion(
87860           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
87861       );
87862     }
87863   }
87864 
87865   /* Update the count of rows that are inserted
87866   */
87867   if( (db->flags & SQLITE_CountRows)!=0 ){
87868     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
87869   }
87870 
87871   if( pTrigger ){
87872     /* Code AFTER triggers */
87873     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
87874         pTab, regData-2-pTab->nCol, onError, endOfLoop);
87875   }
87876 
87877   /* The bottom of the main insertion loop, if the data source
87878   ** is a SELECT statement.
87879   */
87880   sqlite3VdbeResolveLabel(v, endOfLoop);
87881   if( useTempTable ){
87882     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
87883     sqlite3VdbeJumpHere(v, addrInsTop);
87884     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
87885   }else if( pSelect ){
87886     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
87887     sqlite3VdbeJumpHere(v, addrInsTop);
87888   }
87889 
87890   if( !IsVirtual(pTab) && !isView ){
87891     /* Close all tables opened */
87892     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
87893     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
87894       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
87895     }
87896   }
87897 
87898 insert_end:
87899   /* Update the sqlite_sequence table by storing the content of the
87900   ** maximum rowid counter values recorded while inserting into
87901   ** autoincrement tables.
87902   */
87903   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
87904     sqlite3AutoincrementEnd(pParse);
87905   }
87906 
87907   /*
87908   ** Return the number of rows inserted. If this routine is
87909   ** generating code because of a call to sqlite3NestedParse(), do not
87910   ** invoke the callback function.
87911   */
87912   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
87913     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
87914     sqlite3VdbeSetNumCols(v, 1);
87915     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
87916   }
87917 
87918 insert_cleanup:
87919   sqlite3SrcListDelete(db, pTabList);
87920   sqlite3ExprListDelete(db, pList);
87921   sqlite3SelectDelete(db, pSelect);
87922   sqlite3IdListDelete(db, pColumn);
87923   sqlite3DbFree(db, aRegIdx);
87924 }
87925 
87926 /* Make sure "isView" and other macros defined above are undefined. Otherwise
87927 ** thely may interfere with compilation of other functions in this file
87928 ** (or in another file, if this file becomes part of the amalgamation).  */
87929 #ifdef isView
87930  #undef isView
87931 #endif
87932 #ifdef pTrigger
87933  #undef pTrigger
87934 #endif
87935 #ifdef tmask
87936  #undef tmask
87937 #endif
87938 
87939 
87940 /*
87941 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
87942 **
87943 ** The input is a range of consecutive registers as follows:
87944 **
87945 **    1.  The rowid of the row after the update.
87946 **
87947 **    2.  The data in the first column of the entry after the update.
87948 **
87949 **    i.  Data from middle columns...
87950 **
87951 **    N.  The data in the last column of the entry after the update.
87952 **
87953 ** The regRowid parameter is the index of the register containing (1).
87954 **
87955 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
87956 ** the address of a register containing the rowid before the update takes
87957 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
87958 ** is false, indicating an INSERT statement, then a non-zero rowidChng
87959 ** indicates that the rowid was explicitly specified as part of the
87960 ** INSERT statement. If rowidChng is false, it means that  the rowid is
87961 ** computed automatically in an insert or that the rowid value is not
87962 ** modified by an update.
87963 **
87964 ** The code generated by this routine store new index entries into
87965 ** registers identified by aRegIdx[].  No index entry is created for
87966 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
87967 ** the same as the order of indices on the linked list of indices
87968 ** attached to the table.
87969 **
87970 ** This routine also generates code to check constraints.  NOT NULL,
87971 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
87972 ** then the appropriate action is performed.  There are five possible
87973 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
87974 **
87975 **  Constraint type  Action       What Happens
87976 **  ---------------  ----------   ----------------------------------------
87977 **  any              ROLLBACK     The current transaction is rolled back and
87978 **                                sqlite3_exec() returns immediately with a
87979 **                                return code of SQLITE_CONSTRAINT.
87980 **
87981 **  any              ABORT        Back out changes from the current command
87982 **                                only (do not do a complete rollback) then
87983 **                                cause sqlite3_exec() to return immediately
87984 **                                with SQLITE_CONSTRAINT.
87985 **
87986 **  any              FAIL         Sqlite_exec() returns immediately with a
87987 **                                return code of SQLITE_CONSTRAINT.  The
87988 **                                transaction is not rolled back and any
87989 **                                prior changes are retained.
87990 **
87991 **  any              IGNORE       The record number and data is popped from
87992 **                                the stack and there is an immediate jump
87993 **                                to label ignoreDest.
87994 **
87995 **  NOT NULL         REPLACE      The NULL value is replace by the default
87996 **                                value for that column.  If the default value
87997 **                                is NULL, the action is the same as ABORT.
87998 **
87999 **  UNIQUE           REPLACE      The other row that conflicts with the row
88000 **                                being inserted is removed.
88001 **
88002 **  CHECK            REPLACE      Illegal.  The results in an exception.
88003 **
88004 ** Which action to take is determined by the overrideError parameter.
88005 ** Or if overrideError==OE_Default, then the pParse->onError parameter
88006 ** is used.  Or if pParse->onError==OE_Default then the onError value
88007 ** for the constraint is used.
88008 **
88009 ** The calling routine must open a read/write cursor for pTab with
88010 ** cursor number "baseCur".  All indices of pTab must also have open
88011 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
88012 ** Except, if there is no possibility of a REPLACE action then
88013 ** cursors do not need to be open for indices where aRegIdx[i]==0.
88014 */
88015 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
88016   Parse *pParse,      /* The parser context */
88017   Table *pTab,        /* the table into which we are inserting */
88018   int baseCur,        /* Index of a read/write cursor pointing at pTab */
88019   int regRowid,       /* Index of the range of input registers */
88020   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
88021   int rowidChng,      /* True if the rowid might collide with existing entry */
88022   int isUpdate,       /* True for UPDATE, False for INSERT */
88023   int overrideError,  /* Override onError to this if not OE_Default */
88024   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
88025   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
88026 ){
88027   int i;              /* loop counter */
88028   Vdbe *v;            /* VDBE under constrution */
88029   int nCol;           /* Number of columns */
88030   int onError;        /* Conflict resolution strategy */
88031   int j1;             /* Addresss of jump instruction */
88032   int j2 = 0, j3;     /* Addresses of jump instructions */
88033   int regData;        /* Register containing first data column */
88034   int iCur;           /* Table cursor number */
88035   Index *pIdx;         /* Pointer to one of the indices */
88036   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
88037   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
88038 
88039   v = sqlite3GetVdbe(pParse);
88040   assert( v!=0 );
88041   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
88042   nCol = pTab->nCol;
88043   regData = regRowid + 1;
88044 
88045   /* Test all NOT NULL constraints.
88046   */
88047   for(i=0; i<nCol; i++){
88048     if( i==pTab->iPKey ){
88049       continue;
88050     }
88051     onError = pTab->aCol[i].notNull;
88052     if( onError==OE_None ) continue;
88053     if( overrideError!=OE_Default ){
88054       onError = overrideError;
88055     }else if( onError==OE_Default ){
88056       onError = OE_Abort;
88057     }
88058     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
88059       onError = OE_Abort;
88060     }
88061     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
88062         || onError==OE_Ignore || onError==OE_Replace );
88063     switch( onError ){
88064       case OE_Abort:
88065         sqlite3MayAbort(pParse);
88066       case OE_Rollback:
88067       case OE_Fail: {
88068         char *zMsg;
88069         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
88070                                   SQLITE_CONSTRAINT, onError, regData+i);
88071         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
88072                               pTab->zName, pTab->aCol[i].zName);
88073         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
88074         break;
88075       }
88076       case OE_Ignore: {
88077         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
88078         break;
88079       }
88080       default: {
88081         assert( onError==OE_Replace );
88082         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
88083         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
88084         sqlite3VdbeJumpHere(v, j1);
88085         break;
88086       }
88087     }
88088   }
88089 
88090   /* Test all CHECK constraints
88091   */
88092 #ifndef SQLITE_OMIT_CHECK
88093   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
88094     int allOk = sqlite3VdbeMakeLabel(v);
88095     pParse->ckBase = regData;
88096     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
88097     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
88098     if( onError==OE_Ignore ){
88099       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88100     }else{
88101       if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
88102       sqlite3HaltConstraint(pParse, onError, 0, 0);
88103     }
88104     sqlite3VdbeResolveLabel(v, allOk);
88105   }
88106 #endif /* !defined(SQLITE_OMIT_CHECK) */
88107 
88108   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
88109   ** of the new record does not previously exist.  Except, if this
88110   ** is an UPDATE and the primary key is not changing, that is OK.
88111   */
88112   if( rowidChng ){
88113     onError = pTab->keyConf;
88114     if( overrideError!=OE_Default ){
88115       onError = overrideError;
88116     }else if( onError==OE_Default ){
88117       onError = OE_Abort;
88118     }
88119 
88120     if( isUpdate ){
88121       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
88122     }
88123     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
88124     switch( onError ){
88125       default: {
88126         onError = OE_Abort;
88127         /* Fall thru into the next case */
88128       }
88129       case OE_Rollback:
88130       case OE_Abort:
88131       case OE_Fail: {
88132         sqlite3HaltConstraint(
88133           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
88134         break;
88135       }
88136       case OE_Replace: {
88137         /* If there are DELETE triggers on this table and the
88138         ** recursive-triggers flag is set, call GenerateRowDelete() to
88139         ** remove the conflicting row from the the table. This will fire
88140         ** the triggers and remove both the table and index b-tree entries.
88141         **
88142         ** Otherwise, if there are no triggers or the recursive-triggers
88143         ** flag is not set, but the table has one or more indexes, call
88144         ** GenerateRowIndexDelete(). This removes the index b-tree entries
88145         ** only. The table b-tree entry will be replaced by the new entry
88146         ** when it is inserted.
88147         **
88148         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
88149         ** also invoke MultiWrite() to indicate that this VDBE may require
88150         ** statement rollback (if the statement is aborted after the delete
88151         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
88152         ** but being more selective here allows statements like:
88153         **
88154         **   REPLACE INTO t(rowid) VALUES($newrowid)
88155         **
88156         ** to run without a statement journal if there are no indexes on the
88157         ** table.
88158         */
88159         Trigger *pTrigger = 0;
88160         if( pParse->db->flags&SQLITE_RecTriggers ){
88161           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
88162         }
88163         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
88164           sqlite3MultiWrite(pParse);
88165           sqlite3GenerateRowDelete(
88166               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
88167           );
88168         }else if( pTab->pIndex ){
88169           sqlite3MultiWrite(pParse);
88170           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
88171         }
88172         seenReplace = 1;
88173         break;
88174       }
88175       case OE_Ignore: {
88176         assert( seenReplace==0 );
88177         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88178         break;
88179       }
88180     }
88181     sqlite3VdbeJumpHere(v, j3);
88182     if( isUpdate ){
88183       sqlite3VdbeJumpHere(v, j2);
88184     }
88185   }
88186 
88187   /* Test all UNIQUE constraints by creating entries for each UNIQUE
88188   ** index and making sure that duplicate entries do not already exist.
88189   ** Add the new records to the indices as we go.
88190   */
88191   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
88192     int regIdx;
88193     int regR;
88194 
88195     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
88196 
88197     /* Create a key for accessing the index entry */
88198     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
88199     for(i=0; i<pIdx->nColumn; i++){
88200       int idx = pIdx->aiColumn[i];
88201       if( idx==pTab->iPKey ){
88202         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
88203       }else{
88204         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
88205       }
88206     }
88207     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
88208     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
88209     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
88210     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
88211 
88212     /* Find out what action to take in case there is an indexing conflict */
88213     onError = pIdx->onError;
88214     if( onError==OE_None ){
88215       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
88216       continue;  /* pIdx is not a UNIQUE index */
88217     }
88218     if( overrideError!=OE_Default ){
88219       onError = overrideError;
88220     }else if( onError==OE_Default ){
88221       onError = OE_Abort;
88222     }
88223     if( seenReplace ){
88224       if( onError==OE_Ignore ) onError = OE_Replace;
88225       else if( onError==OE_Fail ) onError = OE_Abort;
88226     }
88227 
88228     /* Check to see if the new index entry will be unique */
88229     regR = sqlite3GetTempReg(pParse);
88230     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
88231     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
88232                            regR, SQLITE_INT_TO_PTR(regIdx),
88233                            P4_INT32);
88234     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
88235 
88236     /* Generate code that executes if the new index entry is not unique */
88237     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
88238         || onError==OE_Ignore || onError==OE_Replace );
88239     switch( onError ){
88240       case OE_Rollback:
88241       case OE_Abort:
88242       case OE_Fail: {
88243         int j;
88244         StrAccum errMsg;
88245         const char *zSep;
88246         char *zErr;
88247 
88248         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
88249         errMsg.db = pParse->db;
88250         zSep = pIdx->nColumn>1 ? "columns " : "column ";
88251         for(j=0; j<pIdx->nColumn; j++){
88252           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
88253           sqlite3StrAccumAppend(&errMsg, zSep, -1);
88254           zSep = ", ";
88255           sqlite3StrAccumAppend(&errMsg, zCol, -1);
88256         }
88257         sqlite3StrAccumAppend(&errMsg,
88258             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
88259         zErr = sqlite3StrAccumFinish(&errMsg);
88260         sqlite3HaltConstraint(pParse, onError, zErr, 0);
88261         sqlite3DbFree(errMsg.db, zErr);
88262         break;
88263       }
88264       case OE_Ignore: {
88265         assert( seenReplace==0 );
88266         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
88267         break;
88268       }
88269       default: {
88270         Trigger *pTrigger = 0;
88271         assert( onError==OE_Replace );
88272         sqlite3MultiWrite(pParse);
88273         if( pParse->db->flags&SQLITE_RecTriggers ){
88274           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
88275         }
88276         sqlite3GenerateRowDelete(
88277             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
88278         );
88279         seenReplace = 1;
88280         break;
88281       }
88282     }
88283     sqlite3VdbeJumpHere(v, j3);
88284     sqlite3ReleaseTempReg(pParse, regR);
88285   }
88286 
88287   if( pbMayReplace ){
88288     *pbMayReplace = seenReplace;
88289   }
88290 }
88291 
88292 /*
88293 ** This routine generates code to finish the INSERT or UPDATE operation
88294 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
88295 ** A consecutive range of registers starting at regRowid contains the
88296 ** rowid and the content to be inserted.
88297 **
88298 ** The arguments to this routine should be the same as the first six
88299 ** arguments to sqlite3GenerateConstraintChecks.
88300 */
88301 SQLITE_PRIVATE void sqlite3CompleteInsertion(
88302   Parse *pParse,      /* The parser context */
88303   Table *pTab,        /* the table into which we are inserting */
88304   int baseCur,        /* Index of a read/write cursor pointing at pTab */
88305   int regRowid,       /* Range of content */
88306   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
88307   int isUpdate,       /* True for UPDATE, False for INSERT */
88308   int appendBias,     /* True if this is likely to be an append */
88309   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
88310 ){
88311   int i;
88312   Vdbe *v;
88313   int nIdx;
88314   Index *pIdx;
88315   u8 pik_flags;
88316   int regData;
88317   int regRec;
88318 
88319   v = sqlite3GetVdbe(pParse);
88320   assert( v!=0 );
88321   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
88322   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
88323   for(i=nIdx-1; i>=0; i--){
88324     if( aRegIdx[i]==0 ) continue;
88325     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
88326     if( useSeekResult ){
88327       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
88328     }
88329   }
88330   regData = regRowid + 1;
88331   regRec = sqlite3GetTempReg(pParse);
88332   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
88333   sqlite3TableAffinityStr(v, pTab);
88334   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
88335   if( pParse->nested ){
88336     pik_flags = 0;
88337   }else{
88338     pik_flags = OPFLAG_NCHANGE;
88339     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
88340   }
88341   if( appendBias ){
88342     pik_flags |= OPFLAG_APPEND;
88343   }
88344   if( useSeekResult ){
88345     pik_flags |= OPFLAG_USESEEKRESULT;
88346   }
88347   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
88348   if( !pParse->nested ){
88349     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
88350   }
88351   sqlite3VdbeChangeP5(v, pik_flags);
88352 }
88353 
88354 /*
88355 ** Generate code that will open cursors for a table and for all
88356 ** indices of that table.  The "baseCur" parameter is the cursor number used
88357 ** for the table.  Indices are opened on subsequent cursors.
88358 **
88359 ** Return the number of indices on the table.
88360 */
88361 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
88362   Parse *pParse,   /* Parsing context */
88363   Table *pTab,     /* Table to be opened */
88364   int baseCur,     /* Cursor number assigned to the table */
88365   int op           /* OP_OpenRead or OP_OpenWrite */
88366 ){
88367   int i;
88368   int iDb;
88369   Index *pIdx;
88370   Vdbe *v;
88371 
88372   if( IsVirtual(pTab) ) return 0;
88373   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
88374   v = sqlite3GetVdbe(pParse);
88375   assert( v!=0 );
88376   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
88377   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
88378     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88379     assert( pIdx->pSchema==pTab->pSchema );
88380     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
88381                       (char*)pKey, P4_KEYINFO_HANDOFF);
88382     VdbeComment((v, "%s", pIdx->zName));
88383   }
88384   if( pParse->nTab<baseCur+i ){
88385     pParse->nTab = baseCur+i;
88386   }
88387   return i-1;
88388 }
88389 
88390 
88391 #ifdef SQLITE_TEST
88392 /*
88393 ** The following global variable is incremented whenever the
88394 ** transfer optimization is used.  This is used for testing
88395 ** purposes only - to make sure the transfer optimization really
88396 ** is happening when it is suppose to.
88397 */
88398 SQLITE_API int sqlite3_xferopt_count;
88399 #endif /* SQLITE_TEST */
88400 
88401 
88402 #ifndef SQLITE_OMIT_XFER_OPT
88403 /*
88404 ** Check to collation names to see if they are compatible.
88405 */
88406 static int xferCompatibleCollation(const char *z1, const char *z2){
88407   if( z1==0 ){
88408     return z2==0;
88409   }
88410   if( z2==0 ){
88411     return 0;
88412   }
88413   return sqlite3StrICmp(z1, z2)==0;
88414 }
88415 
88416 
88417 /*
88418 ** Check to see if index pSrc is compatible as a source of data
88419 ** for index pDest in an insert transfer optimization.  The rules
88420 ** for a compatible index:
88421 **
88422 **    *   The index is over the same set of columns
88423 **    *   The same DESC and ASC markings occurs on all columns
88424 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
88425 **    *   The same collating sequence on each column
88426 */
88427 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
88428   int i;
88429   assert( pDest && pSrc );
88430   assert( pDest->pTable!=pSrc->pTable );
88431   if( pDest->nColumn!=pSrc->nColumn ){
88432     return 0;   /* Different number of columns */
88433   }
88434   if( pDest->onError!=pSrc->onError ){
88435     return 0;   /* Different conflict resolution strategies */
88436   }
88437   for(i=0; i<pSrc->nColumn; i++){
88438     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
88439       return 0;   /* Different columns indexed */
88440     }
88441     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
88442       return 0;   /* Different sort orders */
88443     }
88444     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
88445       return 0;   /* Different collating sequences */
88446     }
88447   }
88448 
88449   /* If no test above fails then the indices must be compatible */
88450   return 1;
88451 }
88452 
88453 /*
88454 ** Attempt the transfer optimization on INSERTs of the form
88455 **
88456 **     INSERT INTO tab1 SELECT * FROM tab2;
88457 **
88458 ** This optimization is only attempted if
88459 **
88460 **    (1)  tab1 and tab2 have identical schemas including all the
88461 **         same indices and constraints
88462 **
88463 **    (2)  tab1 and tab2 are different tables
88464 **
88465 **    (3)  There must be no triggers on tab1
88466 **
88467 **    (4)  The result set of the SELECT statement is "*"
88468 **
88469 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
88470 **         or LIMIT clause.
88471 **
88472 **    (6)  The SELECT statement is a simple (not a compound) select that
88473 **         contains only tab2 in its FROM clause
88474 **
88475 ** This method for implementing the INSERT transfers raw records from
88476 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
88477 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
88478 ** the resulting tab1 has much less fragmentation.
88479 **
88480 ** This routine returns TRUE if the optimization is attempted.  If any
88481 ** of the conditions above fail so that the optimization should not
88482 ** be attempted, then this routine returns FALSE.
88483 */
88484 static int xferOptimization(
88485   Parse *pParse,        /* Parser context */
88486   Table *pDest,         /* The table we are inserting into */
88487   Select *pSelect,      /* A SELECT statement to use as the data source */
88488   int onError,          /* How to handle constraint errors */
88489   int iDbDest           /* The database of pDest */
88490 ){
88491   ExprList *pEList;                /* The result set of the SELECT */
88492   Table *pSrc;                     /* The table in the FROM clause of SELECT */
88493   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
88494   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
88495   int i;                           /* Loop counter */
88496   int iDbSrc;                      /* The database of pSrc */
88497   int iSrc, iDest;                 /* Cursors from source and destination */
88498   int addr1, addr2;                /* Loop addresses */
88499   int emptyDestTest;               /* Address of test for empty pDest */
88500   int emptySrcTest;                /* Address of test for empty pSrc */
88501   Vdbe *v;                         /* The VDBE we are building */
88502   KeyInfo *pKey;                   /* Key information for an index */
88503   int regAutoinc;                  /* Memory register used by AUTOINC */
88504   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
88505   int regData, regRowid;           /* Registers holding data and rowid */
88506 
88507   if( pSelect==0 ){
88508     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
88509   }
88510   if( sqlite3TriggerList(pParse, pDest) ){
88511     return 0;   /* tab1 must not have triggers */
88512   }
88513 #ifndef SQLITE_OMIT_VIRTUALTABLE
88514   if( pDest->tabFlags & TF_Virtual ){
88515     return 0;   /* tab1 must not be a virtual table */
88516   }
88517 #endif
88518   if( onError==OE_Default ){
88519     onError = OE_Abort;
88520   }
88521   if( onError!=OE_Abort && onError!=OE_Rollback ){
88522     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
88523   }
88524   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
88525   if( pSelect->pSrc->nSrc!=1 ){
88526     return 0;   /* FROM clause must have exactly one term */
88527   }
88528   if( pSelect->pSrc->a[0].pSelect ){
88529     return 0;   /* FROM clause cannot contain a subquery */
88530   }
88531   if( pSelect->pWhere ){
88532     return 0;   /* SELECT may not have a WHERE clause */
88533   }
88534   if( pSelect->pOrderBy ){
88535     return 0;   /* SELECT may not have an ORDER BY clause */
88536   }
88537   /* Do not need to test for a HAVING clause.  If HAVING is present but
88538   ** there is no ORDER BY, we will get an error. */
88539   if( pSelect->pGroupBy ){
88540     return 0;   /* SELECT may not have a GROUP BY clause */
88541   }
88542   if( pSelect->pLimit ){
88543     return 0;   /* SELECT may not have a LIMIT clause */
88544   }
88545   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
88546   if( pSelect->pPrior ){
88547     return 0;   /* SELECT may not be a compound query */
88548   }
88549   if( pSelect->selFlags & SF_Distinct ){
88550     return 0;   /* SELECT may not be DISTINCT */
88551   }
88552   pEList = pSelect->pEList;
88553   assert( pEList!=0 );
88554   if( pEList->nExpr!=1 ){
88555     return 0;   /* The result set must have exactly one column */
88556   }
88557   assert( pEList->a[0].pExpr );
88558   if( pEList->a[0].pExpr->op!=TK_ALL ){
88559     return 0;   /* The result set must be the special operator "*" */
88560   }
88561 
88562   /* At this point we have established that the statement is of the
88563   ** correct syntactic form to participate in this optimization.  Now
88564   ** we have to check the semantics.
88565   */
88566   pItem = pSelect->pSrc->a;
88567   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
88568   if( pSrc==0 ){
88569     return 0;   /* FROM clause does not contain a real table */
88570   }
88571   if( pSrc==pDest ){
88572     return 0;   /* tab1 and tab2 may not be the same table */
88573   }
88574 #ifndef SQLITE_OMIT_VIRTUALTABLE
88575   if( pSrc->tabFlags & TF_Virtual ){
88576     return 0;   /* tab2 must not be a virtual table */
88577   }
88578 #endif
88579   if( pSrc->pSelect ){
88580     return 0;   /* tab2 may not be a view */
88581   }
88582   if( pDest->nCol!=pSrc->nCol ){
88583     return 0;   /* Number of columns must be the same in tab1 and tab2 */
88584   }
88585   if( pDest->iPKey!=pSrc->iPKey ){
88586     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
88587   }
88588   for(i=0; i<pDest->nCol; i++){
88589     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
88590       return 0;    /* Affinity must be the same on all columns */
88591     }
88592     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
88593       return 0;    /* Collating sequence must be the same on all columns */
88594     }
88595     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
88596       return 0;    /* tab2 must be NOT NULL if tab1 is */
88597     }
88598   }
88599   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
88600     if( pDestIdx->onError!=OE_None ){
88601       destHasUniqueIdx = 1;
88602     }
88603     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
88604       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
88605     }
88606     if( pSrcIdx==0 ){
88607       return 0;    /* pDestIdx has no corresponding index in pSrc */
88608     }
88609   }
88610 #ifndef SQLITE_OMIT_CHECK
88611   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
88612     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
88613   }
88614 #endif
88615 #ifndef SQLITE_OMIT_FOREIGN_KEY
88616   /* Disallow the transfer optimization if the destination table constains
88617   ** any foreign key constraints.  This is more restrictive than necessary.
88618   ** But the main beneficiary of the transfer optimization is the VACUUM
88619   ** command, and the VACUUM command disables foreign key constraints.  So
88620   ** the extra complication to make this rule less restrictive is probably
88621   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
88622   */
88623   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
88624     return 0;
88625   }
88626 #endif
88627 
88628   /* If we get this far, it means either:
88629   **
88630   **    *   We can always do the transfer if the table contains an
88631   **        an integer primary key
88632   **
88633   **    *   We can conditionally do the transfer if the destination
88634   **        table is empty.
88635   */
88636 #ifdef SQLITE_TEST
88637   sqlite3_xferopt_count++;
88638 #endif
88639   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
88640   v = sqlite3GetVdbe(pParse);
88641   sqlite3CodeVerifySchema(pParse, iDbSrc);
88642   iSrc = pParse->nTab++;
88643   iDest = pParse->nTab++;
88644   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
88645   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
88646   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
88647     /* If tables do not have an INTEGER PRIMARY KEY and there
88648     ** are indices to be copied and the destination is not empty,
88649     ** we have to disallow the transfer optimization because the
88650     ** the rowids might change which will mess up indexing.
88651     **
88652     ** Or if the destination has a UNIQUE index and is not empty,
88653     ** we also disallow the transfer optimization because we cannot
88654     ** insure that all entries in the union of DEST and SRC will be
88655     ** unique.
88656     */
88657     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
88658     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
88659     sqlite3VdbeJumpHere(v, addr1);
88660   }else{
88661     emptyDestTest = 0;
88662   }
88663   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
88664   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
88665   regData = sqlite3GetTempReg(pParse);
88666   regRowid = sqlite3GetTempReg(pParse);
88667   if( pDest->iPKey>=0 ){
88668     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
88669     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
88670     sqlite3HaltConstraint(
88671         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
88672     sqlite3VdbeJumpHere(v, addr2);
88673     autoIncStep(pParse, regAutoinc, regRowid);
88674   }else if( pDest->pIndex==0 ){
88675     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
88676   }else{
88677     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
88678     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
88679   }
88680   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
88681   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
88682   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
88683   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
88684   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
88685   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
88686     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
88687       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
88688     }
88689     assert( pSrcIdx );
88690     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
88691     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
88692     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
88693     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
88694                       (char*)pKey, P4_KEYINFO_HANDOFF);
88695     VdbeComment((v, "%s", pSrcIdx->zName));
88696     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
88697     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
88698                       (char*)pKey, P4_KEYINFO_HANDOFF);
88699     VdbeComment((v, "%s", pDestIdx->zName));
88700     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
88701     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
88702     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
88703     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
88704     sqlite3VdbeJumpHere(v, addr1);
88705   }
88706   sqlite3VdbeJumpHere(v, emptySrcTest);
88707   sqlite3ReleaseTempReg(pParse, regRowid);
88708   sqlite3ReleaseTempReg(pParse, regData);
88709   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
88710   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
88711   if( emptyDestTest ){
88712     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
88713     sqlite3VdbeJumpHere(v, emptyDestTest);
88714     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
88715     return 0;
88716   }else{
88717     return 1;
88718   }
88719 }
88720 #endif /* SQLITE_OMIT_XFER_OPT */
88721 
88722 /************** End of insert.c **********************************************/
88723 /************** Begin file legacy.c ******************************************/
88724 /*
88725 ** 2001 September 15
88726 **
88727 ** The author disclaims copyright to this source code.  In place of
88728 ** a legal notice, here is a blessing:
88729 **
88730 **    May you do good and not evil.
88731 **    May you find forgiveness for yourself and forgive others.
88732 **    May you share freely, never taking more than you give.
88733 **
88734 *************************************************************************
88735 ** Main file for the SQLite library.  The routines in this file
88736 ** implement the programmer interface to the library.  Routines in
88737 ** other files are for internal use by SQLite and should not be
88738 ** accessed by users of the library.
88739 */
88740 
88741 
88742 /*
88743 ** Execute SQL code.  Return one of the SQLITE_ success/failure
88744 ** codes.  Also write an error message into memory obtained from
88745 ** malloc() and make *pzErrMsg point to that message.
88746 **
88747 ** If the SQL is a query, then for each row in the query result
88748 ** the xCallback() function is called.  pArg becomes the first
88749 ** argument to xCallback().  If xCallback=NULL then no callback
88750 ** is invoked, even for queries.
88751 */
88752 SQLITE_API int sqlite3_exec(
88753   sqlite3 *db,                /* The database on which the SQL executes */
88754   const char *zSql,           /* The SQL to be executed */
88755   sqlite3_callback xCallback, /* Invoke this callback routine */
88756   void *pArg,                 /* First argument to xCallback() */
88757   char **pzErrMsg             /* Write error messages here */
88758 ){
88759   int rc = SQLITE_OK;         /* Return code */
88760   const char *zLeftover;      /* Tail of unprocessed SQL */
88761   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
88762   char **azCols = 0;          /* Names of result columns */
88763   int nRetry = 0;             /* Number of retry attempts */
88764   int callbackIsInit;         /* True if callback data is initialized */
88765 
88766   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
88767   if( zSql==0 ) zSql = "";
88768 
88769   sqlite3_mutex_enter(db->mutex);
88770   sqlite3Error(db, SQLITE_OK, 0);
88771   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
88772     int nCol;
88773     char **azVals = 0;
88774 
88775     pStmt = 0;
88776     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
88777     assert( rc==SQLITE_OK || pStmt==0 );
88778     if( rc!=SQLITE_OK ){
88779       continue;
88780     }
88781     if( !pStmt ){
88782       /* this happens for a comment or white-space */
88783       zSql = zLeftover;
88784       continue;
88785     }
88786 
88787     callbackIsInit = 0;
88788     nCol = sqlite3_column_count(pStmt);
88789 
88790     while( 1 ){
88791       int i;
88792       rc = sqlite3_step(pStmt);
88793 
88794       /* Invoke the callback function if required */
88795       if( xCallback && (SQLITE_ROW==rc ||
88796           (SQLITE_DONE==rc && !callbackIsInit
88797                            && db->flags&SQLITE_NullCallback)) ){
88798         if( !callbackIsInit ){
88799           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
88800           if( azCols==0 ){
88801             goto exec_out;
88802           }
88803           for(i=0; i<nCol; i++){
88804             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
88805             /* sqlite3VdbeSetColName() installs column names as UTF8
88806             ** strings so there is no way for sqlite3_column_name() to fail. */
88807             assert( azCols[i]!=0 );
88808           }
88809           callbackIsInit = 1;
88810         }
88811         if( rc==SQLITE_ROW ){
88812           azVals = &azCols[nCol];
88813           for(i=0; i<nCol; i++){
88814             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
88815             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
88816               db->mallocFailed = 1;
88817               goto exec_out;
88818             }
88819           }
88820         }
88821         if( xCallback(pArg, nCol, azVals, azCols) ){
88822           rc = SQLITE_ABORT;
88823           sqlite3VdbeFinalize((Vdbe *)pStmt);
88824           pStmt = 0;
88825           sqlite3Error(db, SQLITE_ABORT, 0);
88826           goto exec_out;
88827         }
88828       }
88829 
88830       if( rc!=SQLITE_ROW ){
88831         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
88832         pStmt = 0;
88833         if( rc!=SQLITE_SCHEMA ){
88834           nRetry = 0;
88835           zSql = zLeftover;
88836           while( sqlite3Isspace(zSql[0]) ) zSql++;
88837         }
88838         break;
88839       }
88840     }
88841 
88842     sqlite3DbFree(db, azCols);
88843     azCols = 0;
88844   }
88845 
88846 exec_out:
88847   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
88848   sqlite3DbFree(db, azCols);
88849 
88850   rc = sqlite3ApiExit(db, rc);
88851   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
88852     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
88853     *pzErrMsg = sqlite3Malloc(nErrMsg);
88854     if( *pzErrMsg ){
88855       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
88856     }else{
88857       rc = SQLITE_NOMEM;
88858       sqlite3Error(db, SQLITE_NOMEM, 0);
88859     }
88860   }else if( pzErrMsg ){
88861     *pzErrMsg = 0;
88862   }
88863 
88864   assert( (rc&db->errMask)==rc );
88865   sqlite3_mutex_leave(db->mutex);
88866   return rc;
88867 }
88868 
88869 /************** End of legacy.c **********************************************/
88870 /************** Begin file loadext.c *****************************************/
88871 /*
88872 ** 2006 June 7
88873 **
88874 ** The author disclaims copyright to this source code.  In place of
88875 ** a legal notice, here is a blessing:
88876 **
88877 **    May you do good and not evil.
88878 **    May you find forgiveness for yourself and forgive others.
88879 **    May you share freely, never taking more than you give.
88880 **
88881 *************************************************************************
88882 ** This file contains code used to dynamically load extensions into
88883 ** the SQLite library.
88884 */
88885 
88886 #ifndef SQLITE_CORE
88887   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
88888 #endif
88889 /************** Include sqlite3ext.h in the middle of loadext.c **************/
88890 /************** Begin file sqlite3ext.h **************************************/
88891 /*
88892 ** 2006 June 7
88893 **
88894 ** The author disclaims copyright to this source code.  In place of
88895 ** a legal notice, here is a blessing:
88896 **
88897 **    May you do good and not evil.
88898 **    May you find forgiveness for yourself and forgive others.
88899 **    May you share freely, never taking more than you give.
88900 **
88901 *************************************************************************
88902 ** This header file defines the SQLite interface for use by
88903 ** shared libraries that want to be imported as extensions into
88904 ** an SQLite instance.  Shared libraries that intend to be loaded
88905 ** as extensions by SQLite should #include this file instead of
88906 ** sqlite3.h.
88907 */
88908 #ifndef _SQLITE3EXT_H_
88909 #define _SQLITE3EXT_H_
88910 
88911 typedef struct sqlite3_api_routines sqlite3_api_routines;
88912 
88913 /*
88914 ** The following structure holds pointers to all of the SQLite API
88915 ** routines.
88916 **
88917 ** WARNING:  In order to maintain backwards compatibility, add new
88918 ** interfaces to the end of this structure only.  If you insert new
88919 ** interfaces in the middle of this structure, then older different
88920 ** versions of SQLite will not be able to load each others' shared
88921 ** libraries!
88922 */
88923 struct sqlite3_api_routines {
88924   void * (*aggregate_context)(sqlite3_context*,int nBytes);
88925   int  (*aggregate_count)(sqlite3_context*);
88926   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
88927   int  (*bind_double)(sqlite3_stmt*,int,double);
88928   int  (*bind_int)(sqlite3_stmt*,int,int);
88929   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
88930   int  (*bind_null)(sqlite3_stmt*,int);
88931   int  (*bind_parameter_count)(sqlite3_stmt*);
88932   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
88933   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
88934   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
88935   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
88936   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
88937   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
88938   int  (*busy_timeout)(sqlite3*,int ms);
88939   int  (*changes)(sqlite3*);
88940   int  (*close)(sqlite3*);
88941   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
88942   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
88943   const void * (*column_blob)(sqlite3_stmt*,int iCol);
88944   int  (*column_bytes)(sqlite3_stmt*,int iCol);
88945   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
88946   int  (*column_count)(sqlite3_stmt*pStmt);
88947   const char * (*column_database_name)(sqlite3_stmt*,int);
88948   const void * (*column_database_name16)(sqlite3_stmt*,int);
88949   const char * (*column_decltype)(sqlite3_stmt*,int i);
88950   const void * (*column_decltype16)(sqlite3_stmt*,int);
88951   double  (*column_double)(sqlite3_stmt*,int iCol);
88952   int  (*column_int)(sqlite3_stmt*,int iCol);
88953   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
88954   const char * (*column_name)(sqlite3_stmt*,int);
88955   const void * (*column_name16)(sqlite3_stmt*,int);
88956   const char * (*column_origin_name)(sqlite3_stmt*,int);
88957   const void * (*column_origin_name16)(sqlite3_stmt*,int);
88958   const char * (*column_table_name)(sqlite3_stmt*,int);
88959   const void * (*column_table_name16)(sqlite3_stmt*,int);
88960   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
88961   const void * (*column_text16)(sqlite3_stmt*,int iCol);
88962   int  (*column_type)(sqlite3_stmt*,int iCol);
88963   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
88964   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
88965   int  (*complete)(const char*sql);
88966   int  (*complete16)(const void*sql);
88967   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
88968   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
88969   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*));
88970   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*));
88971   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
88972   int  (*data_count)(sqlite3_stmt*pStmt);
88973   sqlite3 * (*db_handle)(sqlite3_stmt*);
88974   int (*declare_vtab)(sqlite3*,const char*);
88975   int  (*enable_shared_cache)(int);
88976   int  (*errcode)(sqlite3*db);
88977   const char * (*errmsg)(sqlite3*);
88978   const void * (*errmsg16)(sqlite3*);
88979   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
88980   int  (*expired)(sqlite3_stmt*);
88981   int  (*finalize)(sqlite3_stmt*pStmt);
88982   void  (*free)(void*);
88983   void  (*free_table)(char**result);
88984   int  (*get_autocommit)(sqlite3*);
88985   void * (*get_auxdata)(sqlite3_context*,int);
88986   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
88987   int  (*global_recover)(void);
88988   void  (*interruptx)(sqlite3*);
88989   sqlite_int64  (*last_insert_rowid)(sqlite3*);
88990   const char * (*libversion)(void);
88991   int  (*libversion_number)(void);
88992   void *(*malloc)(int);
88993   char * (*mprintf)(const char*,...);
88994   int  (*open)(const char*,sqlite3**);
88995   int  (*open16)(const void*,sqlite3**);
88996   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
88997   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
88998   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
88999   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
89000   void *(*realloc)(void*,int);
89001   int  (*reset)(sqlite3_stmt*pStmt);
89002   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
89003   void  (*result_double)(sqlite3_context*,double);
89004   void  (*result_error)(sqlite3_context*,const char*,int);
89005   void  (*result_error16)(sqlite3_context*,const void*,int);
89006   void  (*result_int)(sqlite3_context*,int);
89007   void  (*result_int64)(sqlite3_context*,sqlite_int64);
89008   void  (*result_null)(sqlite3_context*);
89009   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
89010   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
89011   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
89012   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
89013   void  (*result_value)(sqlite3_context*,sqlite3_value*);
89014   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
89015   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
89016   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
89017   char * (*snprintf)(int,char*,const char*,...);
89018   int  (*step)(sqlite3_stmt*);
89019   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
89020   void  (*thread_cleanup)(void);
89021   int  (*total_changes)(sqlite3*);
89022   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
89023   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
89024   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
89025   void * (*user_data)(sqlite3_context*);
89026   const void * (*value_blob)(sqlite3_value*);
89027   int  (*value_bytes)(sqlite3_value*);
89028   int  (*value_bytes16)(sqlite3_value*);
89029   double  (*value_double)(sqlite3_value*);
89030   int  (*value_int)(sqlite3_value*);
89031   sqlite_int64  (*value_int64)(sqlite3_value*);
89032   int  (*value_numeric_type)(sqlite3_value*);
89033   const unsigned char * (*value_text)(sqlite3_value*);
89034   const void * (*value_text16)(sqlite3_value*);
89035   const void * (*value_text16be)(sqlite3_value*);
89036   const void * (*value_text16le)(sqlite3_value*);
89037   int  (*value_type)(sqlite3_value*);
89038   char *(*vmprintf)(const char*,va_list);
89039   /* Added ??? */
89040   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
89041   /* Added by 3.3.13 */
89042   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
89043   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
89044   int (*clear_bindings)(sqlite3_stmt*);
89045   /* Added by 3.4.1 */
89046   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
89047   /* Added by 3.5.0 */
89048   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
89049   int (*blob_bytes)(sqlite3_blob*);
89050   int (*blob_close)(sqlite3_blob*);
89051   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
89052   int (*blob_read)(sqlite3_blob*,void*,int,int);
89053   int (*blob_write)(sqlite3_blob*,const void*,int,int);
89054   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
89055   int (*file_control)(sqlite3*,const char*,int,void*);
89056   sqlite3_int64 (*memory_highwater)(int);
89057   sqlite3_int64 (*memory_used)(void);
89058   sqlite3_mutex *(*mutex_alloc)(int);
89059   void (*mutex_enter)(sqlite3_mutex*);
89060   void (*mutex_free)(sqlite3_mutex*);
89061   void (*mutex_leave)(sqlite3_mutex*);
89062   int (*mutex_try)(sqlite3_mutex*);
89063   int (*open_v2)(const char*,sqlite3**,int,const char*);
89064   int (*release_memory)(int);
89065   void (*result_error_nomem)(sqlite3_context*);
89066   void (*result_error_toobig)(sqlite3_context*);
89067   int (*sleep)(int);
89068   void (*soft_heap_limit)(int);
89069   sqlite3_vfs *(*vfs_find)(const char*);
89070   int (*vfs_register)(sqlite3_vfs*,int);
89071   int (*vfs_unregister)(sqlite3_vfs*);
89072   int (*xthreadsafe)(void);
89073   void (*result_zeroblob)(sqlite3_context*,int);
89074   void (*result_error_code)(sqlite3_context*,int);
89075   int (*test_control)(int, ...);
89076   void (*randomness)(int,void*);
89077   sqlite3 *(*context_db_handle)(sqlite3_context*);
89078   int (*extended_result_codes)(sqlite3*,int);
89079   int (*limit)(sqlite3*,int,int);
89080   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
89081   const char *(*sql)(sqlite3_stmt*);
89082   int (*status)(int,int*,int*,int);
89083   int (*backup_finish)(sqlite3_backup*);
89084   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
89085   int (*backup_pagecount)(sqlite3_backup*);
89086   int (*backup_remaining)(sqlite3_backup*);
89087   int (*backup_step)(sqlite3_backup*,int);
89088   const char *(*compileoption_get)(int);
89089   int (*compileoption_used)(const char*);
89090   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*),void(*xDestroy)(void*));
89091   int (*db_config)(sqlite3*,int,...);
89092   sqlite3_mutex *(*db_mutex)(sqlite3*);
89093   int (*db_status)(sqlite3*,int,int*,int*,int);
89094   int (*extended_errcode)(sqlite3*);
89095   void (*log)(int,const char*,...);
89096   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
89097   const char *(*sourceid)(void);
89098   int (*stmt_status)(sqlite3_stmt*,int,int);
89099   int (*strnicmp)(const char*,const char*,int);
89100   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
89101   int (*wal_autocheckpoint)(sqlite3*,int);
89102   int (*wal_checkpoint)(sqlite3*,const char*);
89103   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
89104   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
89105   int (*vtab_config)(sqlite3*,int op,...);
89106   int (*vtab_on_conflict)(sqlite3*);
89107 };
89108 
89109 /*
89110 ** The following macros redefine the API routines so that they are
89111 ** redirected throught the global sqlite3_api structure.
89112 **
89113 ** This header file is also used by the loadext.c source file
89114 ** (part of the main SQLite library - not an extension) so that
89115 ** it can get access to the sqlite3_api_routines structure
89116 ** definition.  But the main library does not want to redefine
89117 ** the API.  So the redefinition macros are only valid if the
89118 ** SQLITE_CORE macros is undefined.
89119 */
89120 #ifndef SQLITE_CORE
89121 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
89122 #ifndef SQLITE_OMIT_DEPRECATED
89123 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
89124 #endif
89125 #define sqlite3_bind_blob              sqlite3_api->bind_blob
89126 #define sqlite3_bind_double            sqlite3_api->bind_double
89127 #define sqlite3_bind_int               sqlite3_api->bind_int
89128 #define sqlite3_bind_int64             sqlite3_api->bind_int64
89129 #define sqlite3_bind_null              sqlite3_api->bind_null
89130 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
89131 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
89132 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
89133 #define sqlite3_bind_text              sqlite3_api->bind_text
89134 #define sqlite3_bind_text16            sqlite3_api->bind_text16
89135 #define sqlite3_bind_value             sqlite3_api->bind_value
89136 #define sqlite3_busy_handler           sqlite3_api->busy_handler
89137 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
89138 #define sqlite3_changes                sqlite3_api->changes
89139 #define sqlite3_close                  sqlite3_api->close
89140 #define sqlite3_collation_needed       sqlite3_api->collation_needed
89141 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
89142 #define sqlite3_column_blob            sqlite3_api->column_blob
89143 #define sqlite3_column_bytes           sqlite3_api->column_bytes
89144 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
89145 #define sqlite3_column_count           sqlite3_api->column_count
89146 #define sqlite3_column_database_name   sqlite3_api->column_database_name
89147 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
89148 #define sqlite3_column_decltype        sqlite3_api->column_decltype
89149 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
89150 #define sqlite3_column_double          sqlite3_api->column_double
89151 #define sqlite3_column_int             sqlite3_api->column_int
89152 #define sqlite3_column_int64           sqlite3_api->column_int64
89153 #define sqlite3_column_name            sqlite3_api->column_name
89154 #define sqlite3_column_name16          sqlite3_api->column_name16
89155 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
89156 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
89157 #define sqlite3_column_table_name      sqlite3_api->column_table_name
89158 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
89159 #define sqlite3_column_text            sqlite3_api->column_text
89160 #define sqlite3_column_text16          sqlite3_api->column_text16
89161 #define sqlite3_column_type            sqlite3_api->column_type
89162 #define sqlite3_column_value           sqlite3_api->column_value
89163 #define sqlite3_commit_hook            sqlite3_api->commit_hook
89164 #define sqlite3_complete               sqlite3_api->complete
89165 #define sqlite3_complete16             sqlite3_api->complete16
89166 #define sqlite3_create_collation       sqlite3_api->create_collation
89167 #define sqlite3_create_collation16     sqlite3_api->create_collation16
89168 #define sqlite3_create_function        sqlite3_api->create_function
89169 #define sqlite3_create_function16      sqlite3_api->create_function16
89170 #define sqlite3_create_module          sqlite3_api->create_module
89171 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
89172 #define sqlite3_data_count             sqlite3_api->data_count
89173 #define sqlite3_db_handle              sqlite3_api->db_handle
89174 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
89175 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
89176 #define sqlite3_errcode                sqlite3_api->errcode
89177 #define sqlite3_errmsg                 sqlite3_api->errmsg
89178 #define sqlite3_errmsg16               sqlite3_api->errmsg16
89179 #define sqlite3_exec                   sqlite3_api->exec
89180 #ifndef SQLITE_OMIT_DEPRECATED
89181 #define sqlite3_expired                sqlite3_api->expired
89182 #endif
89183 #define sqlite3_finalize               sqlite3_api->finalize
89184 #define sqlite3_free                   sqlite3_api->free
89185 #define sqlite3_free_table             sqlite3_api->free_table
89186 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
89187 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
89188 #define sqlite3_get_table              sqlite3_api->get_table
89189 #ifndef SQLITE_OMIT_DEPRECATED
89190 #define sqlite3_global_recover         sqlite3_api->global_recover
89191 #endif
89192 #define sqlite3_interrupt              sqlite3_api->interruptx
89193 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
89194 #define sqlite3_libversion             sqlite3_api->libversion
89195 #define sqlite3_libversion_number      sqlite3_api->libversion_number
89196 #define sqlite3_malloc                 sqlite3_api->malloc
89197 #define sqlite3_mprintf                sqlite3_api->mprintf
89198 #define sqlite3_open                   sqlite3_api->open
89199 #define sqlite3_open16                 sqlite3_api->open16
89200 #define sqlite3_prepare                sqlite3_api->prepare
89201 #define sqlite3_prepare16              sqlite3_api->prepare16
89202 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
89203 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
89204 #define sqlite3_profile                sqlite3_api->profile
89205 #define sqlite3_progress_handler       sqlite3_api->progress_handler
89206 #define sqlite3_realloc                sqlite3_api->realloc
89207 #define sqlite3_reset                  sqlite3_api->reset
89208 #define sqlite3_result_blob            sqlite3_api->result_blob
89209 #define sqlite3_result_double          sqlite3_api->result_double
89210 #define sqlite3_result_error           sqlite3_api->result_error
89211 #define sqlite3_result_error16         sqlite3_api->result_error16
89212 #define sqlite3_result_int             sqlite3_api->result_int
89213 #define sqlite3_result_int64           sqlite3_api->result_int64
89214 #define sqlite3_result_null            sqlite3_api->result_null
89215 #define sqlite3_result_text            sqlite3_api->result_text
89216 #define sqlite3_result_text16          sqlite3_api->result_text16
89217 #define sqlite3_result_text16be        sqlite3_api->result_text16be
89218 #define sqlite3_result_text16le        sqlite3_api->result_text16le
89219 #define sqlite3_result_value           sqlite3_api->result_value
89220 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
89221 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
89222 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
89223 #define sqlite3_snprintf               sqlite3_api->snprintf
89224 #define sqlite3_step                   sqlite3_api->step
89225 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
89226 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
89227 #define sqlite3_total_changes          sqlite3_api->total_changes
89228 #define sqlite3_trace                  sqlite3_api->trace
89229 #ifndef SQLITE_OMIT_DEPRECATED
89230 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
89231 #endif
89232 #define sqlite3_update_hook            sqlite3_api->update_hook
89233 #define sqlite3_user_data              sqlite3_api->user_data
89234 #define sqlite3_value_blob             sqlite3_api->value_blob
89235 #define sqlite3_value_bytes            sqlite3_api->value_bytes
89236 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
89237 #define sqlite3_value_double           sqlite3_api->value_double
89238 #define sqlite3_value_int              sqlite3_api->value_int
89239 #define sqlite3_value_int64            sqlite3_api->value_int64
89240 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
89241 #define sqlite3_value_text             sqlite3_api->value_text
89242 #define sqlite3_value_text16           sqlite3_api->value_text16
89243 #define sqlite3_value_text16be         sqlite3_api->value_text16be
89244 #define sqlite3_value_text16le         sqlite3_api->value_text16le
89245 #define sqlite3_value_type             sqlite3_api->value_type
89246 #define sqlite3_vmprintf               sqlite3_api->vmprintf
89247 #define sqlite3_overload_function      sqlite3_api->overload_function
89248 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
89249 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
89250 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
89251 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
89252 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
89253 #define sqlite3_blob_close             sqlite3_api->blob_close
89254 #define sqlite3_blob_open              sqlite3_api->blob_open
89255 #define sqlite3_blob_read              sqlite3_api->blob_read
89256 #define sqlite3_blob_write             sqlite3_api->blob_write
89257 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
89258 #define sqlite3_file_control           sqlite3_api->file_control
89259 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
89260 #define sqlite3_memory_used            sqlite3_api->memory_used
89261 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
89262 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
89263 #define sqlite3_mutex_free             sqlite3_api->mutex_free
89264 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
89265 #define sqlite3_mutex_try              sqlite3_api->mutex_try
89266 #define sqlite3_open_v2                sqlite3_api->open_v2
89267 #define sqlite3_release_memory         sqlite3_api->release_memory
89268 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
89269 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
89270 #define sqlite3_sleep                  sqlite3_api->sleep
89271 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
89272 #define sqlite3_vfs_find               sqlite3_api->vfs_find
89273 #define sqlite3_vfs_register           sqlite3_api->vfs_register
89274 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
89275 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
89276 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
89277 #define sqlite3_result_error_code      sqlite3_api->result_error_code
89278 #define sqlite3_test_control           sqlite3_api->test_control
89279 #define sqlite3_randomness             sqlite3_api->randomness
89280 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
89281 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
89282 #define sqlite3_limit                  sqlite3_api->limit
89283 #define sqlite3_next_stmt              sqlite3_api->next_stmt
89284 #define sqlite3_sql                    sqlite3_api->sql
89285 #define sqlite3_status                 sqlite3_api->status
89286 #define sqlite3_backup_finish          sqlite3_api->backup_finish
89287 #define sqlite3_backup_init            sqlite3_api->backup_init
89288 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
89289 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
89290 #define sqlite3_backup_step            sqlite3_api->backup_step
89291 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
89292 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
89293 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
89294 #define sqlite3_db_config              sqlite3_api->db_config
89295 #define sqlite3_db_mutex               sqlite3_api->db_mutex
89296 #define sqlite3_db_status              sqlite3_api->db_status
89297 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
89298 #define sqlite3_log                    sqlite3_api->log
89299 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
89300 #define sqlite3_sourceid               sqlite3_api->sourceid
89301 #define sqlite3_stmt_status            sqlite3_api->stmt_status
89302 #define sqlite3_strnicmp               sqlite3_api->strnicmp
89303 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
89304 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
89305 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
89306 #define sqlite3_wal_hook               sqlite3_api->wal_hook
89307 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
89308 #define sqlite3_vtab_config            sqlite3_api->vtab_config
89309 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
89310 #endif /* SQLITE_CORE */
89311 
89312 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
89313 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
89314 
89315 #endif /* _SQLITE3EXT_H_ */
89316 
89317 /************** End of sqlite3ext.h ******************************************/
89318 /************** Continuing where we left off in loadext.c ********************/
89319 /* #include <string.h> */
89320 
89321 #ifndef SQLITE_OMIT_LOAD_EXTENSION
89322 
89323 /*
89324 ** Some API routines are omitted when various features are
89325 ** excluded from a build of SQLite.  Substitute a NULL pointer
89326 ** for any missing APIs.
89327 */
89328 #ifndef SQLITE_ENABLE_COLUMN_METADATA
89329 # define sqlite3_column_database_name   0
89330 # define sqlite3_column_database_name16 0
89331 # define sqlite3_column_table_name      0
89332 # define sqlite3_column_table_name16    0
89333 # define sqlite3_column_origin_name     0
89334 # define sqlite3_column_origin_name16   0
89335 # define sqlite3_table_column_metadata  0
89336 #endif
89337 
89338 #ifdef SQLITE_OMIT_AUTHORIZATION
89339 # define sqlite3_set_authorizer         0
89340 #endif
89341 
89342 #ifdef SQLITE_OMIT_UTF16
89343 # define sqlite3_bind_text16            0
89344 # define sqlite3_collation_needed16     0
89345 # define sqlite3_column_decltype16      0
89346 # define sqlite3_column_name16          0
89347 # define sqlite3_column_text16          0
89348 # define sqlite3_complete16             0
89349 # define sqlite3_create_collation16     0
89350 # define sqlite3_create_function16      0
89351 # define sqlite3_errmsg16               0
89352 # define sqlite3_open16                 0
89353 # define sqlite3_prepare16              0
89354 # define sqlite3_prepare16_v2           0
89355 # define sqlite3_result_error16         0
89356 # define sqlite3_result_text16          0
89357 # define sqlite3_result_text16be        0
89358 # define sqlite3_result_text16le        0
89359 # define sqlite3_value_text16           0
89360 # define sqlite3_value_text16be         0
89361 # define sqlite3_value_text16le         0
89362 # define sqlite3_column_database_name16 0
89363 # define sqlite3_column_table_name16    0
89364 # define sqlite3_column_origin_name16   0
89365 #endif
89366 
89367 #ifdef SQLITE_OMIT_COMPLETE
89368 # define sqlite3_complete 0
89369 # define sqlite3_complete16 0
89370 #endif
89371 
89372 #ifdef SQLITE_OMIT_DECLTYPE
89373 # define sqlite3_column_decltype16      0
89374 # define sqlite3_column_decltype        0
89375 #endif
89376 
89377 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
89378 # define sqlite3_progress_handler 0
89379 #endif
89380 
89381 #ifdef SQLITE_OMIT_VIRTUALTABLE
89382 # define sqlite3_create_module 0
89383 # define sqlite3_create_module_v2 0
89384 # define sqlite3_declare_vtab 0
89385 # define sqlite3_vtab_config 0
89386 # define sqlite3_vtab_on_conflict 0
89387 #endif
89388 
89389 #ifdef SQLITE_OMIT_SHARED_CACHE
89390 # define sqlite3_enable_shared_cache 0
89391 #endif
89392 
89393 #ifdef SQLITE_OMIT_TRACE
89394 # define sqlite3_profile       0
89395 # define sqlite3_trace         0
89396 #endif
89397 
89398 #ifdef SQLITE_OMIT_GET_TABLE
89399 # define sqlite3_free_table    0
89400 # define sqlite3_get_table     0
89401 #endif
89402 
89403 #ifdef SQLITE_OMIT_INCRBLOB
89404 #define sqlite3_bind_zeroblob  0
89405 #define sqlite3_blob_bytes     0
89406 #define sqlite3_blob_close     0
89407 #define sqlite3_blob_open      0
89408 #define sqlite3_blob_read      0
89409 #define sqlite3_blob_write     0
89410 #define sqlite3_blob_reopen    0
89411 #endif
89412 
89413 /*
89414 ** The following structure contains pointers to all SQLite API routines.
89415 ** A pointer to this structure is passed into extensions when they are
89416 ** loaded so that the extension can make calls back into the SQLite
89417 ** library.
89418 **
89419 ** When adding new APIs, add them to the bottom of this structure
89420 ** in order to preserve backwards compatibility.
89421 **
89422 ** Extensions that use newer APIs should first call the
89423 ** sqlite3_libversion_number() to make sure that the API they
89424 ** intend to use is supported by the library.  Extensions should
89425 ** also check to make sure that the pointer to the function is
89426 ** not NULL before calling it.
89427 */
89428 static const sqlite3_api_routines sqlite3Apis = {
89429   sqlite3_aggregate_context,
89430 #ifndef SQLITE_OMIT_DEPRECATED
89431   sqlite3_aggregate_count,
89432 #else
89433   0,
89434 #endif
89435   sqlite3_bind_blob,
89436   sqlite3_bind_double,
89437   sqlite3_bind_int,
89438   sqlite3_bind_int64,
89439   sqlite3_bind_null,
89440   sqlite3_bind_parameter_count,
89441   sqlite3_bind_parameter_index,
89442   sqlite3_bind_parameter_name,
89443   sqlite3_bind_text,
89444   sqlite3_bind_text16,
89445   sqlite3_bind_value,
89446   sqlite3_busy_handler,
89447   sqlite3_busy_timeout,
89448   sqlite3_changes,
89449   sqlite3_close,
89450   sqlite3_collation_needed,
89451   sqlite3_collation_needed16,
89452   sqlite3_column_blob,
89453   sqlite3_column_bytes,
89454   sqlite3_column_bytes16,
89455   sqlite3_column_count,
89456   sqlite3_column_database_name,
89457   sqlite3_column_database_name16,
89458   sqlite3_column_decltype,
89459   sqlite3_column_decltype16,
89460   sqlite3_column_double,
89461   sqlite3_column_int,
89462   sqlite3_column_int64,
89463   sqlite3_column_name,
89464   sqlite3_column_name16,
89465   sqlite3_column_origin_name,
89466   sqlite3_column_origin_name16,
89467   sqlite3_column_table_name,
89468   sqlite3_column_table_name16,
89469   sqlite3_column_text,
89470   sqlite3_column_text16,
89471   sqlite3_column_type,
89472   sqlite3_column_value,
89473   sqlite3_commit_hook,
89474   sqlite3_complete,
89475   sqlite3_complete16,
89476   sqlite3_create_collation,
89477   sqlite3_create_collation16,
89478   sqlite3_create_function,
89479   sqlite3_create_function16,
89480   sqlite3_create_module,
89481   sqlite3_data_count,
89482   sqlite3_db_handle,
89483   sqlite3_declare_vtab,
89484   sqlite3_enable_shared_cache,
89485   sqlite3_errcode,
89486   sqlite3_errmsg,
89487   sqlite3_errmsg16,
89488   sqlite3_exec,
89489 #ifndef SQLITE_OMIT_DEPRECATED
89490   sqlite3_expired,
89491 #else
89492   0,
89493 #endif
89494   sqlite3_finalize,
89495   sqlite3_free,
89496   sqlite3_free_table,
89497   sqlite3_get_autocommit,
89498   sqlite3_get_auxdata,
89499   sqlite3_get_table,
89500   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
89501   sqlite3_interrupt,
89502   sqlite3_last_insert_rowid,
89503   sqlite3_libversion,
89504   sqlite3_libversion_number,
89505   sqlite3_malloc,
89506   sqlite3_mprintf,
89507   sqlite3_open,
89508   sqlite3_open16,
89509   sqlite3_prepare,
89510   sqlite3_prepare16,
89511   sqlite3_profile,
89512   sqlite3_progress_handler,
89513   sqlite3_realloc,
89514   sqlite3_reset,
89515   sqlite3_result_blob,
89516   sqlite3_result_double,
89517   sqlite3_result_error,
89518   sqlite3_result_error16,
89519   sqlite3_result_int,
89520   sqlite3_result_int64,
89521   sqlite3_result_null,
89522   sqlite3_result_text,
89523   sqlite3_result_text16,
89524   sqlite3_result_text16be,
89525   sqlite3_result_text16le,
89526   sqlite3_result_value,
89527   sqlite3_rollback_hook,
89528   sqlite3_set_authorizer,
89529   sqlite3_set_auxdata,
89530   sqlite3_snprintf,
89531   sqlite3_step,
89532   sqlite3_table_column_metadata,
89533 #ifndef SQLITE_OMIT_DEPRECATED
89534   sqlite3_thread_cleanup,
89535 #else
89536   0,
89537 #endif
89538   sqlite3_total_changes,
89539   sqlite3_trace,
89540 #ifndef SQLITE_OMIT_DEPRECATED
89541   sqlite3_transfer_bindings,
89542 #else
89543   0,
89544 #endif
89545   sqlite3_update_hook,
89546   sqlite3_user_data,
89547   sqlite3_value_blob,
89548   sqlite3_value_bytes,
89549   sqlite3_value_bytes16,
89550   sqlite3_value_double,
89551   sqlite3_value_int,
89552   sqlite3_value_int64,
89553   sqlite3_value_numeric_type,
89554   sqlite3_value_text,
89555   sqlite3_value_text16,
89556   sqlite3_value_text16be,
89557   sqlite3_value_text16le,
89558   sqlite3_value_type,
89559   sqlite3_vmprintf,
89560   /*
89561   ** The original API set ends here.  All extensions can call any
89562   ** of the APIs above provided that the pointer is not NULL.  But
89563   ** before calling APIs that follow, extension should check the
89564   ** sqlite3_libversion_number() to make sure they are dealing with
89565   ** a library that is new enough to support that API.
89566   *************************************************************************
89567   */
89568   sqlite3_overload_function,
89569 
89570   /*
89571   ** Added after 3.3.13
89572   */
89573   sqlite3_prepare_v2,
89574   sqlite3_prepare16_v2,
89575   sqlite3_clear_bindings,
89576 
89577   /*
89578   ** Added for 3.4.1
89579   */
89580   sqlite3_create_module_v2,
89581 
89582   /*
89583   ** Added for 3.5.0
89584   */
89585   sqlite3_bind_zeroblob,
89586   sqlite3_blob_bytes,
89587   sqlite3_blob_close,
89588   sqlite3_blob_open,
89589   sqlite3_blob_read,
89590   sqlite3_blob_write,
89591   sqlite3_create_collation_v2,
89592   sqlite3_file_control,
89593   sqlite3_memory_highwater,
89594   sqlite3_memory_used,
89595 #ifdef SQLITE_MUTEX_OMIT
89596   0,
89597   0,
89598   0,
89599   0,
89600   0,
89601 #else
89602   sqlite3_mutex_alloc,
89603   sqlite3_mutex_enter,
89604   sqlite3_mutex_free,
89605   sqlite3_mutex_leave,
89606   sqlite3_mutex_try,
89607 #endif
89608   sqlite3_open_v2,
89609   sqlite3_release_memory,
89610   sqlite3_result_error_nomem,
89611   sqlite3_result_error_toobig,
89612   sqlite3_sleep,
89613   sqlite3_soft_heap_limit,
89614   sqlite3_vfs_find,
89615   sqlite3_vfs_register,
89616   sqlite3_vfs_unregister,
89617 
89618   /*
89619   ** Added for 3.5.8
89620   */
89621   sqlite3_threadsafe,
89622   sqlite3_result_zeroblob,
89623   sqlite3_result_error_code,
89624   sqlite3_test_control,
89625   sqlite3_randomness,
89626   sqlite3_context_db_handle,
89627 
89628   /*
89629   ** Added for 3.6.0
89630   */
89631   sqlite3_extended_result_codes,
89632   sqlite3_limit,
89633   sqlite3_next_stmt,
89634   sqlite3_sql,
89635   sqlite3_status,
89636 
89637   /*
89638   ** Added for 3.7.4
89639   */
89640   sqlite3_backup_finish,
89641   sqlite3_backup_init,
89642   sqlite3_backup_pagecount,
89643   sqlite3_backup_remaining,
89644   sqlite3_backup_step,
89645 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
89646   sqlite3_compileoption_get,
89647   sqlite3_compileoption_used,
89648 #else
89649   0,
89650   0,
89651 #endif
89652   sqlite3_create_function_v2,
89653   sqlite3_db_config,
89654   sqlite3_db_mutex,
89655   sqlite3_db_status,
89656   sqlite3_extended_errcode,
89657   sqlite3_log,
89658   sqlite3_soft_heap_limit64,
89659   sqlite3_sourceid,
89660   sqlite3_stmt_status,
89661   sqlite3_strnicmp,
89662 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
89663   sqlite3_unlock_notify,
89664 #else
89665   0,
89666 #endif
89667 #ifndef SQLITE_OMIT_WAL
89668   sqlite3_wal_autocheckpoint,
89669   sqlite3_wal_checkpoint,
89670   sqlite3_wal_hook,
89671 #else
89672   0,
89673   0,
89674   0,
89675 #endif
89676   sqlite3_blob_reopen,
89677   sqlite3_vtab_config,
89678   sqlite3_vtab_on_conflict,
89679 };
89680 
89681 /*
89682 ** Attempt to load an SQLite extension library contained in the file
89683 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
89684 ** default entry point name (sqlite3_extension_init) is used.  Use
89685 ** of the default name is recommended.
89686 **
89687 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
89688 **
89689 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
89690 ** error message text.  The calling function should free this memory
89691 ** by calling sqlite3DbFree(db, ).
89692 */
89693 static int sqlite3LoadExtension(
89694   sqlite3 *db,          /* Load the extension into this database connection */
89695   const char *zFile,    /* Name of the shared library containing extension */
89696   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
89697   char **pzErrMsg       /* Put error message here if not 0 */
89698 ){
89699   sqlite3_vfs *pVfs = db->pVfs;
89700   void *handle;
89701   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
89702   char *zErrmsg = 0;
89703   void **aHandle;
89704   const int nMsg = 300;
89705 
89706   if( pzErrMsg ) *pzErrMsg = 0;
89707 
89708   /* Ticket #1863.  To avoid a creating security problems for older
89709   ** applications that relink against newer versions of SQLite, the
89710   ** ability to run load_extension is turned off by default.  One
89711   ** must call sqlite3_enable_load_extension() to turn on extension
89712   ** loading.  Otherwise you get the following error.
89713   */
89714   if( (db->flags & SQLITE_LoadExtension)==0 ){
89715     if( pzErrMsg ){
89716       *pzErrMsg = sqlite3_mprintf("not authorized");
89717     }
89718     return SQLITE_ERROR;
89719   }
89720 
89721   if( zProc==0 ){
89722     zProc = "sqlite3_extension_init";
89723   }
89724 
89725   handle = sqlite3OsDlOpen(pVfs, zFile);
89726   if( handle==0 ){
89727     if( pzErrMsg ){
89728       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
89729       if( zErrmsg ){
89730         sqlite3_snprintf(nMsg, zErrmsg,
89731             "unable to open shared library [%s]", zFile);
89732         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
89733       }
89734     }
89735     return SQLITE_ERROR;
89736   }
89737   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
89738                    sqlite3OsDlSym(pVfs, handle, zProc);
89739   if( xInit==0 ){
89740     if( pzErrMsg ){
89741       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
89742       if( zErrmsg ){
89743         sqlite3_snprintf(nMsg, zErrmsg,
89744             "no entry point [%s] in shared library [%s]", zProc,zFile);
89745         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
89746       }
89747       sqlite3OsDlClose(pVfs, handle);
89748     }
89749     return SQLITE_ERROR;
89750   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
89751     if( pzErrMsg ){
89752       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
89753     }
89754     sqlite3_free(zErrmsg);
89755     sqlite3OsDlClose(pVfs, handle);
89756     return SQLITE_ERROR;
89757   }
89758 
89759   /* Append the new shared library handle to the db->aExtension array. */
89760   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
89761   if( aHandle==0 ){
89762     return SQLITE_NOMEM;
89763   }
89764   if( db->nExtension>0 ){
89765     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
89766   }
89767   sqlite3DbFree(db, db->aExtension);
89768   db->aExtension = aHandle;
89769 
89770   db->aExtension[db->nExtension++] = handle;
89771   return SQLITE_OK;
89772 }
89773 SQLITE_API int sqlite3_load_extension(
89774   sqlite3 *db,          /* Load the extension into this database connection */
89775   const char *zFile,    /* Name of the shared library containing extension */
89776   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
89777   char **pzErrMsg       /* Put error message here if not 0 */
89778 ){
89779   int rc;
89780   sqlite3_mutex_enter(db->mutex);
89781   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
89782   rc = sqlite3ApiExit(db, rc);
89783   sqlite3_mutex_leave(db->mutex);
89784   return rc;
89785 }
89786 
89787 /*
89788 ** Call this routine when the database connection is closing in order
89789 ** to clean up loaded extensions
89790 */
89791 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
89792   int i;
89793   assert( sqlite3_mutex_held(db->mutex) );
89794   for(i=0; i<db->nExtension; i++){
89795     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
89796   }
89797   sqlite3DbFree(db, db->aExtension);
89798 }
89799 
89800 /*
89801 ** Enable or disable extension loading.  Extension loading is disabled by
89802 ** default so as not to open security holes in older applications.
89803 */
89804 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
89805   sqlite3_mutex_enter(db->mutex);
89806   if( onoff ){
89807     db->flags |= SQLITE_LoadExtension;
89808   }else{
89809     db->flags &= ~SQLITE_LoadExtension;
89810   }
89811   sqlite3_mutex_leave(db->mutex);
89812   return SQLITE_OK;
89813 }
89814 
89815 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
89816 
89817 /*
89818 ** The auto-extension code added regardless of whether or not extension
89819 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
89820 ** code if regular extension loading is not available.  This is that
89821 ** dummy pointer.
89822 */
89823 #ifdef SQLITE_OMIT_LOAD_EXTENSION
89824 static const sqlite3_api_routines sqlite3Apis = { 0 };
89825 #endif
89826 
89827 
89828 /*
89829 ** The following object holds the list of automatically loaded
89830 ** extensions.
89831 **
89832 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
89833 ** mutex must be held while accessing this list.
89834 */
89835 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
89836 static SQLITE_WSD struct sqlite3AutoExtList {
89837   int nExt;              /* Number of entries in aExt[] */
89838   void (**aExt)(void);   /* Pointers to the extension init functions */
89839 } sqlite3Autoext = { 0, 0 };
89840 
89841 /* The "wsdAutoext" macro will resolve to the autoextension
89842 ** state vector.  If writable static data is unsupported on the target,
89843 ** we have to locate the state vector at run-time.  In the more common
89844 ** case where writable static data is supported, wsdStat can refer directly
89845 ** to the "sqlite3Autoext" state vector declared above.
89846 */
89847 #ifdef SQLITE_OMIT_WSD
89848 # define wsdAutoextInit \
89849   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
89850 # define wsdAutoext x[0]
89851 #else
89852 # define wsdAutoextInit
89853 # define wsdAutoext sqlite3Autoext
89854 #endif
89855 
89856 
89857 /*
89858 ** Register a statically linked extension that is automatically
89859 ** loaded by every new database connection.
89860 */
89861 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
89862   int rc = SQLITE_OK;
89863 #ifndef SQLITE_OMIT_AUTOINIT
89864   rc = sqlite3_initialize();
89865   if( rc ){
89866     return rc;
89867   }else
89868 #endif
89869   {
89870     int i;
89871 #if SQLITE_THREADSAFE
89872     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
89873 #endif
89874     wsdAutoextInit;
89875     sqlite3_mutex_enter(mutex);
89876     for(i=0; i<wsdAutoext.nExt; i++){
89877       if( wsdAutoext.aExt[i]==xInit ) break;
89878     }
89879     if( i==wsdAutoext.nExt ){
89880       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
89881       void (**aNew)(void);
89882       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
89883       if( aNew==0 ){
89884         rc = SQLITE_NOMEM;
89885       }else{
89886         wsdAutoext.aExt = aNew;
89887         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
89888         wsdAutoext.nExt++;
89889       }
89890     }
89891     sqlite3_mutex_leave(mutex);
89892     assert( (rc&0xff)==rc );
89893     return rc;
89894   }
89895 }
89896 
89897 /*
89898 ** Reset the automatic extension loading mechanism.
89899 */
89900 SQLITE_API void sqlite3_reset_auto_extension(void){
89901 #ifndef SQLITE_OMIT_AUTOINIT
89902   if( sqlite3_initialize()==SQLITE_OK )
89903 #endif
89904   {
89905 #if SQLITE_THREADSAFE
89906     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
89907 #endif
89908     wsdAutoextInit;
89909     sqlite3_mutex_enter(mutex);
89910     sqlite3_free(wsdAutoext.aExt);
89911     wsdAutoext.aExt = 0;
89912     wsdAutoext.nExt = 0;
89913     sqlite3_mutex_leave(mutex);
89914   }
89915 }
89916 
89917 /*
89918 ** Load all automatic extensions.
89919 **
89920 ** If anything goes wrong, set an error in the database connection.
89921 */
89922 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
89923   int i;
89924   int go = 1;
89925   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
89926 
89927   wsdAutoextInit;
89928   if( wsdAutoext.nExt==0 ){
89929     /* Common case: early out without every having to acquire a mutex */
89930     return;
89931   }
89932   for(i=0; go; i++){
89933     char *zErrmsg;
89934 #if SQLITE_THREADSAFE
89935     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
89936 #endif
89937     sqlite3_mutex_enter(mutex);
89938     if( i>=wsdAutoext.nExt ){
89939       xInit = 0;
89940       go = 0;
89941     }else{
89942       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
89943               ((uintptr_t)wsdAutoext.aExt[i]);
89944     }
89945     sqlite3_mutex_leave(mutex);
89946     zErrmsg = 0;
89947     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
89948       sqlite3Error(db, SQLITE_ERROR,
89949             "automatic extension loading failed: %s", zErrmsg);
89950       go = 0;
89951     }
89952     sqlite3_free(zErrmsg);
89953   }
89954 }
89955 
89956 /************** End of loadext.c *********************************************/
89957 /************** Begin file pragma.c ******************************************/
89958 /*
89959 ** 2003 April 6
89960 **
89961 ** The author disclaims copyright to this source code.  In place of
89962 ** a legal notice, here is a blessing:
89963 **
89964 **    May you do good and not evil.
89965 **    May you find forgiveness for yourself and forgive others.
89966 **    May you share freely, never taking more than you give.
89967 **
89968 *************************************************************************
89969 ** This file contains code used to implement the PRAGMA command.
89970 */
89971 
89972 /*
89973 ** Interpret the given string as a safety level.  Return 0 for OFF,
89974 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
89975 ** unrecognized string argument.
89976 **
89977 ** Note that the values returned are one less that the values that
89978 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
89979 ** to support legacy SQL code.  The safety level used to be boolean
89980 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
89981 */
89982 static u8 getSafetyLevel(const char *z){
89983                              /* 123456789 123456789 */
89984   static const char zText[] = "onoffalseyestruefull";
89985   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
89986   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
89987   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
89988   int i, n;
89989   if( sqlite3Isdigit(*z) ){
89990     return (u8)sqlite3Atoi(z);
89991   }
89992   n = sqlite3Strlen30(z);
89993   for(i=0; i<ArraySize(iLength); i++){
89994     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
89995       return iValue[i];
89996     }
89997   }
89998   return 1;
89999 }
90000 
90001 /*
90002 ** Interpret the given string as a boolean value.
90003 */
90004 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z){
90005   return getSafetyLevel(z)&1;
90006 }
90007 
90008 /* The sqlite3GetBoolean() function is used by other modules but the
90009 ** remainder of this file is specific to PRAGMA processing.  So omit
90010 ** the rest of the file if PRAGMAs are omitted from the build.
90011 */
90012 #if !defined(SQLITE_OMIT_PRAGMA)
90013 
90014 /*
90015 ** Interpret the given string as a locking mode value.
90016 */
90017 static int getLockingMode(const char *z){
90018   if( z ){
90019     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
90020     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
90021   }
90022   return PAGER_LOCKINGMODE_QUERY;
90023 }
90024 
90025 #ifndef SQLITE_OMIT_AUTOVACUUM
90026 /*
90027 ** Interpret the given string as an auto-vacuum mode value.
90028 **
90029 ** The following strings, "none", "full" and "incremental" are
90030 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
90031 */
90032 static int getAutoVacuum(const char *z){
90033   int i;
90034   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
90035   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
90036   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
90037   i = sqlite3Atoi(z);
90038   return (u8)((i>=0&&i<=2)?i:0);
90039 }
90040 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
90041 
90042 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90043 /*
90044 ** Interpret the given string as a temp db location. Return 1 for file
90045 ** backed temporary databases, 2 for the Red-Black tree in memory database
90046 ** and 0 to use the compile-time default.
90047 */
90048 static int getTempStore(const char *z){
90049   if( z[0]>='0' && z[0]<='2' ){
90050     return z[0] - '0';
90051   }else if( sqlite3StrICmp(z, "file")==0 ){
90052     return 1;
90053   }else if( sqlite3StrICmp(z, "memory")==0 ){
90054     return 2;
90055   }else{
90056     return 0;
90057   }
90058 }
90059 #endif /* SQLITE_PAGER_PRAGMAS */
90060 
90061 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90062 /*
90063 ** Invalidate temp storage, either when the temp storage is changed
90064 ** from default, or when 'file' and the temp_store_directory has changed
90065 */
90066 static int invalidateTempStorage(Parse *pParse){
90067   sqlite3 *db = pParse->db;
90068   if( db->aDb[1].pBt!=0 ){
90069     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
90070       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
90071         "from within a transaction");
90072       return SQLITE_ERROR;
90073     }
90074     sqlite3BtreeClose(db->aDb[1].pBt);
90075     db->aDb[1].pBt = 0;
90076     sqlite3ResetInternalSchema(db, -1);
90077   }
90078   return SQLITE_OK;
90079 }
90080 #endif /* SQLITE_PAGER_PRAGMAS */
90081 
90082 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90083 /*
90084 ** If the TEMP database is open, close it and mark the database schema
90085 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
90086 ** or DEFAULT_TEMP_STORE pragmas.
90087 */
90088 static int changeTempStorage(Parse *pParse, const char *zStorageType){
90089   int ts = getTempStore(zStorageType);
90090   sqlite3 *db = pParse->db;
90091   if( db->temp_store==ts ) return SQLITE_OK;
90092   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
90093     return SQLITE_ERROR;
90094   }
90095   db->temp_store = (u8)ts;
90096   return SQLITE_OK;
90097 }
90098 #endif /* SQLITE_PAGER_PRAGMAS */
90099 
90100 /*
90101 ** Generate code to return a single integer value.
90102 */
90103 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
90104   Vdbe *v = sqlite3GetVdbe(pParse);
90105   int mem = ++pParse->nMem;
90106   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
90107   if( pI64 ){
90108     memcpy(pI64, &value, sizeof(value));
90109   }
90110   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
90111   sqlite3VdbeSetNumCols(v, 1);
90112   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
90113   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
90114 }
90115 
90116 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
90117 /*
90118 ** Check to see if zRight and zLeft refer to a pragma that queries
90119 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
90120 ** Also, implement the pragma.
90121 */
90122 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
90123   static const struct sPragmaType {
90124     const char *zName;  /* Name of the pragma */
90125     int mask;           /* Mask for the db->flags value */
90126   } aPragma[] = {
90127     { "full_column_names",        SQLITE_FullColNames  },
90128     { "short_column_names",       SQLITE_ShortColNames },
90129     { "count_changes",            SQLITE_CountRows     },
90130     { "empty_result_callbacks",   SQLITE_NullCallback  },
90131     { "legacy_file_format",       SQLITE_LegacyFileFmt },
90132     { "fullfsync",                SQLITE_FullFSync     },
90133     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
90134     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
90135 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
90136     { "automatic_index",          SQLITE_AutoIndex     },
90137 #endif
90138 #ifdef SQLITE_DEBUG
90139     { "sql_trace",                SQLITE_SqlTrace      },
90140     { "vdbe_listing",             SQLITE_VdbeListing   },
90141     { "vdbe_trace",               SQLITE_VdbeTrace     },
90142 #endif
90143 #ifndef SQLITE_OMIT_CHECK
90144     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
90145 #endif
90146     /* The following is VERY experimental */
90147     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
90148     { "omit_readlock",            SQLITE_NoReadlock    },
90149 
90150     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
90151     ** flag if there are any active statements. */
90152     { "read_uncommitted",         SQLITE_ReadUncommitted },
90153     { "recursive_triggers",       SQLITE_RecTriggers },
90154 
90155     /* This flag may only be set if both foreign-key and trigger support
90156     ** are present in the build.  */
90157 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
90158     { "foreign_keys",             SQLITE_ForeignKeys },
90159 #endif
90160   };
90161   int i;
90162   const struct sPragmaType *p;
90163   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
90164     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
90165       sqlite3 *db = pParse->db;
90166       Vdbe *v;
90167       v = sqlite3GetVdbe(pParse);
90168       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
90169       if( ALWAYS(v) ){
90170         if( zRight==0 ){
90171           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
90172         }else{
90173           int mask = p->mask;          /* Mask of bits to set or clear. */
90174           if( db->autoCommit==0 ){
90175             /* Foreign key support may not be enabled or disabled while not
90176             ** in auto-commit mode.  */
90177             mask &= ~(SQLITE_ForeignKeys);
90178           }
90179 
90180           if( sqlite3GetBoolean(zRight) ){
90181             db->flags |= mask;
90182           }else{
90183             db->flags &= ~mask;
90184           }
90185 
90186           /* Many of the flag-pragmas modify the code generated by the SQL
90187           ** compiler (eg. count_changes). So add an opcode to expire all
90188           ** compiled SQL statements after modifying a pragma value.
90189           */
90190           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
90191         }
90192       }
90193 
90194       return 1;
90195     }
90196   }
90197   return 0;
90198 }
90199 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
90200 
90201 /*
90202 ** Return a human-readable name for a constraint resolution action.
90203 */
90204 #ifndef SQLITE_OMIT_FOREIGN_KEY
90205 static const char *actionName(u8 action){
90206   const char *zName;
90207   switch( action ){
90208     case OE_SetNull:  zName = "SET NULL";        break;
90209     case OE_SetDflt:  zName = "SET DEFAULT";     break;
90210     case OE_Cascade:  zName = "CASCADE";         break;
90211     case OE_Restrict: zName = "RESTRICT";        break;
90212     default:          zName = "NO ACTION";
90213                       assert( action==OE_None ); break;
90214   }
90215   return zName;
90216 }
90217 #endif
90218 
90219 
90220 /*
90221 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
90222 ** defined in pager.h. This function returns the associated lowercase
90223 ** journal-mode name.
90224 */
90225 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
90226   static char * const azModeName[] = {
90227     "delete", "persist", "off", "truncate", "memory"
90228 #ifndef SQLITE_OMIT_WAL
90229      , "wal"
90230 #endif
90231   };
90232   assert( PAGER_JOURNALMODE_DELETE==0 );
90233   assert( PAGER_JOURNALMODE_PERSIST==1 );
90234   assert( PAGER_JOURNALMODE_OFF==2 );
90235   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
90236   assert( PAGER_JOURNALMODE_MEMORY==4 );
90237   assert( PAGER_JOURNALMODE_WAL==5 );
90238   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
90239 
90240   if( eMode==ArraySize(azModeName) ) return 0;
90241   return azModeName[eMode];
90242 }
90243 
90244 /*
90245 ** Process a pragma statement.
90246 **
90247 ** Pragmas are of this form:
90248 **
90249 **      PRAGMA [database.]id [= value]
90250 **
90251 ** The identifier might also be a string.  The value is a string, and
90252 ** identifier, or a number.  If minusFlag is true, then the value is
90253 ** a number that was preceded by a minus sign.
90254 **
90255 ** If the left side is "database.id" then pId1 is the database name
90256 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
90257 ** id and pId2 is any empty string.
90258 */
90259 SQLITE_PRIVATE void sqlite3Pragma(
90260   Parse *pParse,
90261   Token *pId1,        /* First part of [database.]id field */
90262   Token *pId2,        /* Second part of [database.]id field, or NULL */
90263   Token *pValue,      /* Token for <value>, or NULL */
90264   int minusFlag       /* True if a '-' sign preceded <value> */
90265 ){
90266   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
90267   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
90268   const char *zDb = 0;   /* The database name */
90269   Token *pId;            /* Pointer to <id> token */
90270   int iDb;               /* Database index for <database> */
90271   sqlite3 *db = pParse->db;
90272   Db *pDb;
90273   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
90274   if( v==0 ) return;
90275   sqlite3VdbeRunOnlyOnce(v);
90276   pParse->nMem = 2;
90277 
90278   /* Interpret the [database.] part of the pragma statement. iDb is the
90279   ** index of the database this pragma is being applied to in db.aDb[]. */
90280   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
90281   if( iDb<0 ) return;
90282   pDb = &db->aDb[iDb];
90283 
90284   /* If the temp database has been explicitly named as part of the
90285   ** pragma, make sure it is open.
90286   */
90287   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
90288     return;
90289   }
90290 
90291   zLeft = sqlite3NameFromToken(db, pId);
90292   if( !zLeft ) return;
90293   if( minusFlag ){
90294     zRight = sqlite3MPrintf(db, "-%T", pValue);
90295   }else{
90296     zRight = sqlite3NameFromToken(db, pValue);
90297   }
90298 
90299   assert( pId2 );
90300   zDb = pId2->n>0 ? pDb->zName : 0;
90301   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
90302     goto pragma_out;
90303   }
90304 
90305 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90306   /*
90307   **  PRAGMA [database.]default_cache_size
90308   **  PRAGMA [database.]default_cache_size=N
90309   **
90310   ** The first form reports the current persistent setting for the
90311   ** page cache size.  The value returned is the maximum number of
90312   ** pages in the page cache.  The second form sets both the current
90313   ** page cache size value and the persistent page cache size value
90314   ** stored in the database file.
90315   **
90316   ** Older versions of SQLite would set the default cache size to a
90317   ** negative number to indicate synchronous=OFF.  These days, synchronous
90318   ** is always on by default regardless of the sign of the default cache
90319   ** size.  But continue to take the absolute value of the default cache
90320   ** size of historical compatibility.
90321   */
90322   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
90323     static const VdbeOpList getCacheSize[] = {
90324       { OP_Transaction, 0, 0,        0},                         /* 0 */
90325       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
90326       { OP_IfPos,       1, 7,        0},
90327       { OP_Integer,     0, 2,        0},
90328       { OP_Subtract,    1, 2,        1},
90329       { OP_IfPos,       1, 7,        0},
90330       { OP_Integer,     0, 1,        0},                         /* 6 */
90331       { OP_ResultRow,   1, 1,        0},
90332     };
90333     int addr;
90334     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90335     sqlite3VdbeUsesBtree(v, iDb);
90336     if( !zRight ){
90337       sqlite3VdbeSetNumCols(v, 1);
90338       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
90339       pParse->nMem += 2;
90340       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
90341       sqlite3VdbeChangeP1(v, addr, iDb);
90342       sqlite3VdbeChangeP1(v, addr+1, iDb);
90343       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
90344     }else{
90345       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
90346       sqlite3BeginWriteOperation(pParse, 0, iDb);
90347       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
90348       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
90349       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90350       pDb->pSchema->cache_size = size;
90351       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
90352     }
90353   }else
90354 
90355   /*
90356   **  PRAGMA [database.]page_size
90357   **  PRAGMA [database.]page_size=N
90358   **
90359   ** The first form reports the current setting for the
90360   ** database page size in bytes.  The second form sets the
90361   ** database page size value.  The value can only be set if
90362   ** the database has not yet been created.
90363   */
90364   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
90365     Btree *pBt = pDb->pBt;
90366     assert( pBt!=0 );
90367     if( !zRight ){
90368       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
90369       returnSingleInt(pParse, "page_size", size);
90370     }else{
90371       /* Malloc may fail when setting the page-size, as there is an internal
90372       ** buffer that the pager module resizes using sqlite3_realloc().
90373       */
90374       db->nextPagesize = sqlite3Atoi(zRight);
90375       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
90376         db->mallocFailed = 1;
90377       }
90378     }
90379   }else
90380 
90381   /*
90382   **  PRAGMA [database.]secure_delete
90383   **  PRAGMA [database.]secure_delete=ON/OFF
90384   **
90385   ** The first form reports the current setting for the
90386   ** secure_delete flag.  The second form changes the secure_delete
90387   ** flag setting and reports thenew value.
90388   */
90389   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
90390     Btree *pBt = pDb->pBt;
90391     int b = -1;
90392     assert( pBt!=0 );
90393     if( zRight ){
90394       b = sqlite3GetBoolean(zRight);
90395     }
90396     if( pId2->n==0 && b>=0 ){
90397       int ii;
90398       for(ii=0; ii<db->nDb; ii++){
90399         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
90400       }
90401     }
90402     b = sqlite3BtreeSecureDelete(pBt, b);
90403     returnSingleInt(pParse, "secure_delete", b);
90404   }else
90405 
90406   /*
90407   **  PRAGMA [database.]max_page_count
90408   **  PRAGMA [database.]max_page_count=N
90409   **
90410   ** The first form reports the current setting for the
90411   ** maximum number of pages in the database file.  The
90412   ** second form attempts to change this setting.  Both
90413   ** forms return the current setting.
90414   **
90415   **  PRAGMA [database.]page_count
90416   **
90417   ** Return the number of pages in the specified database.
90418   */
90419   if( sqlite3StrICmp(zLeft,"page_count")==0
90420    || sqlite3StrICmp(zLeft,"max_page_count")==0
90421   ){
90422     int iReg;
90423     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90424     sqlite3CodeVerifySchema(pParse, iDb);
90425     iReg = ++pParse->nMem;
90426     if( zLeft[0]=='p' ){
90427       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
90428     }else{
90429       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3Atoi(zRight));
90430     }
90431     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
90432     sqlite3VdbeSetNumCols(v, 1);
90433     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
90434   }else
90435 
90436   /*
90437   **  PRAGMA [database.]locking_mode
90438   **  PRAGMA [database.]locking_mode = (normal|exclusive)
90439   */
90440   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
90441     const char *zRet = "normal";
90442     int eMode = getLockingMode(zRight);
90443 
90444     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
90445       /* Simple "PRAGMA locking_mode;" statement. This is a query for
90446       ** the current default locking mode (which may be different to
90447       ** the locking-mode of the main database).
90448       */
90449       eMode = db->dfltLockMode;
90450     }else{
90451       Pager *pPager;
90452       if( pId2->n==0 ){
90453         /* This indicates that no database name was specified as part
90454         ** of the PRAGMA command. In this case the locking-mode must be
90455         ** set on all attached databases, as well as the main db file.
90456         **
90457         ** Also, the sqlite3.dfltLockMode variable is set so that
90458         ** any subsequently attached databases also use the specified
90459         ** locking mode.
90460         */
90461         int ii;
90462         assert(pDb==&db->aDb[0]);
90463         for(ii=2; ii<db->nDb; ii++){
90464           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
90465           sqlite3PagerLockingMode(pPager, eMode);
90466         }
90467         db->dfltLockMode = (u8)eMode;
90468       }
90469       pPager = sqlite3BtreePager(pDb->pBt);
90470       eMode = sqlite3PagerLockingMode(pPager, eMode);
90471     }
90472 
90473     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
90474     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
90475       zRet = "exclusive";
90476     }
90477     sqlite3VdbeSetNumCols(v, 1);
90478     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
90479     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
90480     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90481   }else
90482 
90483   /*
90484   **  PRAGMA [database.]journal_mode
90485   **  PRAGMA [database.]journal_mode =
90486   **                      (delete|persist|off|truncate|memory|wal|off)
90487   */
90488   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
90489     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
90490     int ii;           /* Loop counter */
90491 
90492     /* Force the schema to be loaded on all databases.  This cases all
90493     ** database files to be opened and the journal_modes set. */
90494     if( sqlite3ReadSchema(pParse) ){
90495       goto pragma_out;
90496     }
90497 
90498     sqlite3VdbeSetNumCols(v, 1);
90499     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
90500 
90501     if( zRight==0 ){
90502       /* If there is no "=MODE" part of the pragma, do a query for the
90503       ** current mode */
90504       eMode = PAGER_JOURNALMODE_QUERY;
90505     }else{
90506       const char *zMode;
90507       int n = sqlite3Strlen30(zRight);
90508       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
90509         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
90510       }
90511       if( !zMode ){
90512         /* If the "=MODE" part does not match any known journal mode,
90513         ** then do a query */
90514         eMode = PAGER_JOURNALMODE_QUERY;
90515       }
90516     }
90517     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
90518       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
90519       iDb = 0;
90520       pId2->n = 1;
90521     }
90522     for(ii=db->nDb-1; ii>=0; ii--){
90523       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
90524         sqlite3VdbeUsesBtree(v, ii);
90525         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
90526       }
90527     }
90528     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90529   }else
90530 
90531   /*
90532   **  PRAGMA [database.]journal_size_limit
90533   **  PRAGMA [database.]journal_size_limit=N
90534   **
90535   ** Get or set the size limit on rollback journal files.
90536   */
90537   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
90538     Pager *pPager = sqlite3BtreePager(pDb->pBt);
90539     i64 iLimit = -2;
90540     if( zRight ){
90541       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
90542       if( iLimit<-1 ) iLimit = -1;
90543     }
90544     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
90545     returnSingleInt(pParse, "journal_size_limit", iLimit);
90546   }else
90547 
90548 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
90549 
90550   /*
90551   **  PRAGMA [database.]auto_vacuum
90552   **  PRAGMA [database.]auto_vacuum=N
90553   **
90554   ** Get or set the value of the database 'auto-vacuum' parameter.
90555   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
90556   */
90557 #ifndef SQLITE_OMIT_AUTOVACUUM
90558   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
90559     Btree *pBt = pDb->pBt;
90560     assert( pBt!=0 );
90561     if( sqlite3ReadSchema(pParse) ){
90562       goto pragma_out;
90563     }
90564     if( !zRight ){
90565       int auto_vacuum;
90566       if( ALWAYS(pBt) ){
90567          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
90568       }else{
90569          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
90570       }
90571       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
90572     }else{
90573       int eAuto = getAutoVacuum(zRight);
90574       assert( eAuto>=0 && eAuto<=2 );
90575       db->nextAutovac = (u8)eAuto;
90576       if( ALWAYS(eAuto>=0) ){
90577         /* Call SetAutoVacuum() to set initialize the internal auto and
90578         ** incr-vacuum flags. This is required in case this connection
90579         ** creates the database file. It is important that it is created
90580         ** as an auto-vacuum capable db.
90581         */
90582         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
90583         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
90584           /* When setting the auto_vacuum mode to either "full" or
90585           ** "incremental", write the value of meta[6] in the database
90586           ** file. Before writing to meta[6], check that meta[3] indicates
90587           ** that this really is an auto-vacuum capable database.
90588           */
90589           static const VdbeOpList setMeta6[] = {
90590             { OP_Transaction,    0,         1,                 0},    /* 0 */
90591             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
90592             { OP_If,             1,         0,                 0},    /* 2 */
90593             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
90594             { OP_Integer,        0,         1,                 0},    /* 4 */
90595             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
90596           };
90597           int iAddr;
90598           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
90599           sqlite3VdbeChangeP1(v, iAddr, iDb);
90600           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
90601           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
90602           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
90603           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
90604           sqlite3VdbeUsesBtree(v, iDb);
90605         }
90606       }
90607     }
90608   }else
90609 #endif
90610 
90611   /*
90612   **  PRAGMA [database.]incremental_vacuum(N)
90613   **
90614   ** Do N steps of incremental vacuuming on a database.
90615   */
90616 #ifndef SQLITE_OMIT_AUTOVACUUM
90617   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
90618     int iLimit, addr;
90619     if( sqlite3ReadSchema(pParse) ){
90620       goto pragma_out;
90621     }
90622     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
90623       iLimit = 0x7fffffff;
90624     }
90625     sqlite3BeginWriteOperation(pParse, 0, iDb);
90626     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
90627     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
90628     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
90629     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
90630     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
90631     sqlite3VdbeJumpHere(v, addr);
90632   }else
90633 #endif
90634 
90635 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
90636   /*
90637   **  PRAGMA [database.]cache_size
90638   **  PRAGMA [database.]cache_size=N
90639   **
90640   ** The first form reports the current local setting for the
90641   ** page cache size.  The local setting can be different from
90642   ** the persistent cache size value that is stored in the database
90643   ** file itself.  The value returned is the maximum number of
90644   ** pages in the page cache.  The second form sets the local
90645   ** page cache size value.  It does not change the persistent
90646   ** cache size stored on the disk so the cache size will revert
90647   ** to its default value when the database is closed and reopened.
90648   ** N should be a positive integer.
90649   */
90650   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
90651     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90652     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90653     if( !zRight ){
90654       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
90655     }else{
90656       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
90657       pDb->pSchema->cache_size = size;
90658       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
90659     }
90660   }else
90661 
90662   /*
90663   **   PRAGMA temp_store
90664   **   PRAGMA temp_store = "default"|"memory"|"file"
90665   **
90666   ** Return or set the local value of the temp_store flag.  Changing
90667   ** the local value does not make changes to the disk file and the default
90668   ** value will be restored the next time the database is opened.
90669   **
90670   ** Note that it is possible for the library compile-time options to
90671   ** override this setting
90672   */
90673   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
90674     if( !zRight ){
90675       returnSingleInt(pParse, "temp_store", db->temp_store);
90676     }else{
90677       changeTempStorage(pParse, zRight);
90678     }
90679   }else
90680 
90681   /*
90682   **   PRAGMA temp_store_directory
90683   **   PRAGMA temp_store_directory = ""|"directory_name"
90684   **
90685   ** Return or set the local value of the temp_store_directory flag.  Changing
90686   ** the value sets a specific directory to be used for temporary files.
90687   ** Setting to a null string reverts to the default temporary directory search.
90688   ** If temporary directory is changed, then invalidateTempStorage.
90689   **
90690   */
90691   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
90692     if( !zRight ){
90693       if( sqlite3_temp_directory ){
90694         sqlite3VdbeSetNumCols(v, 1);
90695         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
90696             "temp_store_directory", SQLITE_STATIC);
90697         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
90698         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90699       }
90700     }else{
90701 #ifndef SQLITE_OMIT_WSD
90702       if( zRight[0] ){
90703         int rc;
90704         int res;
90705         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
90706         if( rc!=SQLITE_OK || res==0 ){
90707           sqlite3ErrorMsg(pParse, "not a writable directory");
90708           goto pragma_out;
90709         }
90710       }
90711       if( SQLITE_TEMP_STORE==0
90712        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
90713        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
90714       ){
90715         invalidateTempStorage(pParse);
90716       }
90717       sqlite3_free(sqlite3_temp_directory);
90718       if( zRight[0] ){
90719         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
90720       }else{
90721         sqlite3_temp_directory = 0;
90722       }
90723 #endif /* SQLITE_OMIT_WSD */
90724     }
90725   }else
90726 
90727 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
90728 #  if defined(__APPLE__)
90729 #    define SQLITE_ENABLE_LOCKING_STYLE 1
90730 #  else
90731 #    define SQLITE_ENABLE_LOCKING_STYLE 0
90732 #  endif
90733 #endif
90734 #if SQLITE_ENABLE_LOCKING_STYLE
90735   /*
90736    **   PRAGMA [database.]lock_proxy_file
90737    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
90738    **
90739    ** Return or set the value of the lock_proxy_file flag.  Changing
90740    ** the value sets a specific file to be used for database access locks.
90741    **
90742    */
90743   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
90744     if( !zRight ){
90745       Pager *pPager = sqlite3BtreePager(pDb->pBt);
90746       char *proxy_file_path = NULL;
90747       sqlite3_file *pFile = sqlite3PagerFile(pPager);
90748       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
90749                            &proxy_file_path);
90750 
90751       if( proxy_file_path ){
90752         sqlite3VdbeSetNumCols(v, 1);
90753         sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
90754                               "lock_proxy_file", SQLITE_STATIC);
90755         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
90756         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
90757       }
90758     }else{
90759       Pager *pPager = sqlite3BtreePager(pDb->pBt);
90760       sqlite3_file *pFile = sqlite3PagerFile(pPager);
90761       int res;
90762       if( zRight[0] ){
90763         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
90764                                      zRight);
90765       } else {
90766         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
90767                                      NULL);
90768       }
90769       if( res!=SQLITE_OK ){
90770         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
90771         goto pragma_out;
90772       }
90773     }
90774   }else
90775 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
90776 
90777   /*
90778   **   PRAGMA [database.]synchronous
90779   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
90780   **
90781   ** Return or set the local value of the synchronous flag.  Changing
90782   ** the local value does not make changes to the disk file and the
90783   ** default value will be restored the next time the database is
90784   ** opened.
90785   */
90786   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
90787     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90788     if( !zRight ){
90789       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
90790     }else{
90791       if( !db->autoCommit ){
90792         sqlite3ErrorMsg(pParse,
90793             "Safety level may not be changed inside a transaction");
90794       }else{
90795         pDb->safety_level = getSafetyLevel(zRight)+1;
90796       }
90797     }
90798   }else
90799 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
90800 
90801 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
90802   if( flagPragma(pParse, zLeft, zRight) ){
90803     /* The flagPragma() subroutine also generates any necessary code
90804     ** there is nothing more to do here */
90805   }else
90806 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
90807 
90808 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
90809   /*
90810   **   PRAGMA table_info(<table>)
90811   **
90812   ** Return a single row for each column of the named table. The columns of
90813   ** the returned data set are:
90814   **
90815   ** cid:        Column id (numbered from left to right, starting at 0)
90816   ** name:       Column name
90817   ** type:       Column declaration type.
90818   ** notnull:    True if 'NOT NULL' is part of column declaration
90819   ** dflt_value: The default value for the column, if any.
90820   */
90821   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
90822     Table *pTab;
90823     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90824     pTab = sqlite3FindTable(db, zRight, zDb);
90825     if( pTab ){
90826       int i;
90827       int nHidden = 0;
90828       Column *pCol;
90829       sqlite3VdbeSetNumCols(v, 6);
90830       pParse->nMem = 6;
90831       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
90832       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
90833       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
90834       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
90835       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
90836       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
90837       sqlite3ViewGetColumnNames(pParse, pTab);
90838       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
90839         if( IsHiddenColumn(pCol) ){
90840           nHidden++;
90841           continue;
90842         }
90843         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
90844         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
90845         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
90846            pCol->zType ? pCol->zType : "", 0);
90847         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
90848         if( pCol->zDflt ){
90849           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
90850         }else{
90851           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
90852         }
90853         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
90854         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
90855       }
90856     }
90857   }else
90858 
90859   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
90860     Index *pIdx;
90861     Table *pTab;
90862     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90863     pIdx = sqlite3FindIndex(db, zRight, zDb);
90864     if( pIdx ){
90865       int i;
90866       pTab = pIdx->pTable;
90867       sqlite3VdbeSetNumCols(v, 3);
90868       pParse->nMem = 3;
90869       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
90870       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
90871       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
90872       for(i=0; i<pIdx->nColumn; i++){
90873         int cnum = pIdx->aiColumn[i];
90874         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
90875         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
90876         assert( pTab->nCol>cnum );
90877         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
90878         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
90879       }
90880     }
90881   }else
90882 
90883   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
90884     Index *pIdx;
90885     Table *pTab;
90886     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90887     pTab = sqlite3FindTable(db, zRight, zDb);
90888     if( pTab ){
90889       v = sqlite3GetVdbe(pParse);
90890       pIdx = pTab->pIndex;
90891       if( pIdx ){
90892         int i = 0;
90893         sqlite3VdbeSetNumCols(v, 3);
90894         pParse->nMem = 3;
90895         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
90896         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
90897         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
90898         while(pIdx){
90899           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
90900           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
90901           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
90902           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
90903           ++i;
90904           pIdx = pIdx->pNext;
90905         }
90906       }
90907     }
90908   }else
90909 
90910   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
90911     int i;
90912     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90913     sqlite3VdbeSetNumCols(v, 3);
90914     pParse->nMem = 3;
90915     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
90916     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
90917     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
90918     for(i=0; i<db->nDb; i++){
90919       if( db->aDb[i].pBt==0 ) continue;
90920       assert( db->aDb[i].zName!=0 );
90921       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
90922       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
90923       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
90924            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
90925       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
90926     }
90927   }else
90928 
90929   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
90930     int i = 0;
90931     HashElem *p;
90932     sqlite3VdbeSetNumCols(v, 2);
90933     pParse->nMem = 2;
90934     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
90935     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
90936     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
90937       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
90938       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
90939       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
90940       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
90941     }
90942   }else
90943 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
90944 
90945 #ifndef SQLITE_OMIT_FOREIGN_KEY
90946   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
90947     FKey *pFK;
90948     Table *pTab;
90949     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
90950     pTab = sqlite3FindTable(db, zRight, zDb);
90951     if( pTab ){
90952       v = sqlite3GetVdbe(pParse);
90953       pFK = pTab->pFKey;
90954       if( pFK ){
90955         int i = 0;
90956         sqlite3VdbeSetNumCols(v, 8);
90957         pParse->nMem = 8;
90958         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
90959         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
90960         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
90961         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
90962         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
90963         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
90964         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
90965         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
90966         while(pFK){
90967           int j;
90968           for(j=0; j<pFK->nCol; j++){
90969             char *zCol = pFK->aCol[j].zCol;
90970             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
90971             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
90972             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
90973             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
90974             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
90975             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
90976                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
90977             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
90978             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
90979             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
90980             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
90981             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
90982           }
90983           ++i;
90984           pFK = pFK->pNextFrom;
90985         }
90986       }
90987     }
90988   }else
90989 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
90990 
90991 #ifndef NDEBUG
90992   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
90993     if( zRight ){
90994       if( sqlite3GetBoolean(zRight) ){
90995         sqlite3ParserTrace(stderr, "parser: ");
90996       }else{
90997         sqlite3ParserTrace(0, 0);
90998       }
90999     }
91000   }else
91001 #endif
91002 
91003   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
91004   ** used will be case sensitive or not depending on the RHS.
91005   */
91006   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
91007     if( zRight ){
91008       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight));
91009     }
91010   }else
91011 
91012 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
91013 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
91014 #endif
91015 
91016 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
91017   /* Pragma "quick_check" is an experimental reduced version of
91018   ** integrity_check designed to detect most database corruption
91019   ** without most of the overhead of a full integrity-check.
91020   */
91021   if( sqlite3StrICmp(zLeft, "integrity_check")==0
91022    || sqlite3StrICmp(zLeft, "quick_check")==0
91023   ){
91024     int i, j, addr, mxErr;
91025 
91026     /* Code that appears at the end of the integrity check.  If no error
91027     ** messages have been generated, output OK.  Otherwise output the
91028     ** error message
91029     */
91030     static const VdbeOpList endCode[] = {
91031       { OP_AddImm,      1, 0,        0},    /* 0 */
91032       { OP_IfNeg,       1, 0,        0},    /* 1 */
91033       { OP_String8,     0, 3,        0},    /* 2 */
91034       { OP_ResultRow,   3, 1,        0},
91035     };
91036 
91037     int isQuick = (zLeft[0]=='q');
91038 
91039     /* Initialize the VDBE program */
91040     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91041     pParse->nMem = 6;
91042     sqlite3VdbeSetNumCols(v, 1);
91043     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
91044 
91045     /* Set the maximum error count */
91046     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
91047     if( zRight ){
91048       sqlite3GetInt32(zRight, &mxErr);
91049       if( mxErr<=0 ){
91050         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
91051       }
91052     }
91053     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
91054 
91055     /* Do an integrity check on each database file */
91056     for(i=0; i<db->nDb; i++){
91057       HashElem *x;
91058       Hash *pTbls;
91059       int cnt = 0;
91060 
91061       if( OMIT_TEMPDB && i==1 ) continue;
91062 
91063       sqlite3CodeVerifySchema(pParse, i);
91064       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
91065       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91066       sqlite3VdbeJumpHere(v, addr);
91067 
91068       /* Do an integrity check of the B-Tree
91069       **
91070       ** Begin by filling registers 2, 3, ... with the root pages numbers
91071       ** for all tables and indices in the database.
91072       */
91073       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91074       pTbls = &db->aDb[i].pSchema->tblHash;
91075       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
91076         Table *pTab = sqliteHashData(x);
91077         Index *pIdx;
91078         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
91079         cnt++;
91080         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
91081           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
91082           cnt++;
91083         }
91084       }
91085 
91086       /* Make sure sufficient number of registers have been allocated */
91087       if( pParse->nMem < cnt+4 ){
91088         pParse->nMem = cnt+4;
91089       }
91090 
91091       /* Do the b-tree integrity checks */
91092       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
91093       sqlite3VdbeChangeP5(v, (u8)i);
91094       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
91095       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
91096          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
91097          P4_DYNAMIC);
91098       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
91099       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
91100       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
91101       sqlite3VdbeJumpHere(v, addr);
91102 
91103       /* Make sure all the indices are constructed correctly.
91104       */
91105       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
91106         Table *pTab = sqliteHashData(x);
91107         Index *pIdx;
91108         int loopTop;
91109 
91110         if( pTab->pIndex==0 ) continue;
91111         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
91112         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91113         sqlite3VdbeJumpHere(v, addr);
91114         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
91115         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
91116         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
91117         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
91118         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91119           int jmp2;
91120           int r1;
91121           static const VdbeOpList idxErr[] = {
91122             { OP_AddImm,      1, -1,  0},
91123             { OP_String8,     0,  3,  0},    /* 1 */
91124             { OP_Rowid,       1,  4,  0},
91125             { OP_String8,     0,  5,  0},    /* 3 */
91126             { OP_String8,     0,  6,  0},    /* 4 */
91127             { OP_Concat,      4,  3,  3},
91128             { OP_Concat,      5,  3,  3},
91129             { OP_Concat,      6,  3,  3},
91130             { OP_ResultRow,   3,  1,  0},
91131             { OP_IfPos,       1,  0,  0},    /* 9 */
91132             { OP_Halt,        0,  0,  0},
91133           };
91134           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
91135           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
91136           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
91137           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
91138           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
91139           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
91140           sqlite3VdbeJumpHere(v, addr+9);
91141           sqlite3VdbeJumpHere(v, jmp2);
91142         }
91143         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
91144         sqlite3VdbeJumpHere(v, loopTop);
91145         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
91146           static const VdbeOpList cntIdx[] = {
91147              { OP_Integer,      0,  3,  0},
91148              { OP_Rewind,       0,  0,  0},  /* 1 */
91149              { OP_AddImm,       3,  1,  0},
91150              { OP_Next,         0,  0,  0},  /* 3 */
91151              { OP_Eq,           2,  0,  3},  /* 4 */
91152              { OP_AddImm,       1, -1,  0},
91153              { OP_String8,      0,  2,  0},  /* 6 */
91154              { OP_String8,      0,  3,  0},  /* 7 */
91155              { OP_Concat,       3,  2,  2},
91156              { OP_ResultRow,    2,  1,  0},
91157           };
91158           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
91159           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
91160           sqlite3VdbeJumpHere(v, addr);
91161           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
91162           sqlite3VdbeChangeP1(v, addr+1, j+2);
91163           sqlite3VdbeChangeP2(v, addr+1, addr+4);
91164           sqlite3VdbeChangeP1(v, addr+3, j+2);
91165           sqlite3VdbeChangeP2(v, addr+3, addr+2);
91166           sqlite3VdbeJumpHere(v, addr+4);
91167           sqlite3VdbeChangeP4(v, addr+6,
91168                      "wrong # of entries in index ", P4_STATIC);
91169           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
91170         }
91171       }
91172     }
91173     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
91174     sqlite3VdbeChangeP2(v, addr, -mxErr);
91175     sqlite3VdbeJumpHere(v, addr+1);
91176     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
91177   }else
91178 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
91179 
91180 #ifndef SQLITE_OMIT_UTF16
91181   /*
91182   **   PRAGMA encoding
91183   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
91184   **
91185   ** In its first form, this pragma returns the encoding of the main
91186   ** database. If the database is not initialized, it is initialized now.
91187   **
91188   ** The second form of this pragma is a no-op if the main database file
91189   ** has not already been initialized. In this case it sets the default
91190   ** encoding that will be used for the main database file if a new file
91191   ** is created. If an existing main database file is opened, then the
91192   ** default text encoding for the existing database is used.
91193   **
91194   ** In all cases new databases created using the ATTACH command are
91195   ** created to use the same default text encoding as the main database. If
91196   ** the main database has not been initialized and/or created when ATTACH
91197   ** is executed, this is done before the ATTACH operation.
91198   **
91199   ** In the second form this pragma sets the text encoding to be used in
91200   ** new database files created using this database handle. It is only
91201   ** useful if invoked immediately after the main database i
91202   */
91203   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
91204     static const struct EncName {
91205       char *zName;
91206       u8 enc;
91207     } encnames[] = {
91208       { "UTF8",     SQLITE_UTF8        },
91209       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
91210       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
91211       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
91212       { "UTF16le",  SQLITE_UTF16LE     },
91213       { "UTF16be",  SQLITE_UTF16BE     },
91214       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
91215       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
91216       { 0, 0 }
91217     };
91218     const struct EncName *pEnc;
91219     if( !zRight ){    /* "PRAGMA encoding" */
91220       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91221       sqlite3VdbeSetNumCols(v, 1);
91222       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
91223       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
91224       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
91225       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
91226       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
91227       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
91228       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91229     }else{                        /* "PRAGMA encoding = XXX" */
91230       /* Only change the value of sqlite.enc if the database handle is not
91231       ** initialized. If the main database exists, the new sqlite.enc value
91232       ** will be overwritten when the schema is next loaded. If it does not
91233       ** already exists, it will be created to use the new encoding value.
91234       */
91235       if(
91236         !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
91237         DbHasProperty(db, 0, DB_Empty)
91238       ){
91239         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
91240           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
91241             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
91242             break;
91243           }
91244         }
91245         if( !pEnc->zName ){
91246           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
91247         }
91248       }
91249     }
91250   }else
91251 #endif /* SQLITE_OMIT_UTF16 */
91252 
91253 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
91254   /*
91255   **   PRAGMA [database.]schema_version
91256   **   PRAGMA [database.]schema_version = <integer>
91257   **
91258   **   PRAGMA [database.]user_version
91259   **   PRAGMA [database.]user_version = <integer>
91260   **
91261   ** The pragma's schema_version and user_version are used to set or get
91262   ** the value of the schema-version and user-version, respectively. Both
91263   ** the schema-version and the user-version are 32-bit signed integers
91264   ** stored in the database header.
91265   **
91266   ** The schema-cookie is usually only manipulated internally by SQLite. It
91267   ** is incremented by SQLite whenever the database schema is modified (by
91268   ** creating or dropping a table or index). The schema version is used by
91269   ** SQLite each time a query is executed to ensure that the internal cache
91270   ** of the schema used when compiling the SQL query matches the schema of
91271   ** the database against which the compiled query is actually executed.
91272   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
91273   ** the schema-version is potentially dangerous and may lead to program
91274   ** crashes or database corruption. Use with caution!
91275   **
91276   ** The user-version is not used internally by SQLite. It may be used by
91277   ** applications for any purpose.
91278   */
91279   if( sqlite3StrICmp(zLeft, "schema_version")==0
91280    || sqlite3StrICmp(zLeft, "user_version")==0
91281    || sqlite3StrICmp(zLeft, "freelist_count")==0
91282   ){
91283     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
91284     sqlite3VdbeUsesBtree(v, iDb);
91285     switch( zLeft[0] ){
91286       case 'f': case 'F':
91287         iCookie = BTREE_FREE_PAGE_COUNT;
91288         break;
91289       case 's': case 'S':
91290         iCookie = BTREE_SCHEMA_VERSION;
91291         break;
91292       default:
91293         iCookie = BTREE_USER_VERSION;
91294         break;
91295     }
91296 
91297     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
91298       /* Write the specified cookie value */
91299       static const VdbeOpList setCookie[] = {
91300         { OP_Transaction,    0,  1,  0},    /* 0 */
91301         { OP_Integer,        0,  1,  0},    /* 1 */
91302         { OP_SetCookie,      0,  0,  1},    /* 2 */
91303       };
91304       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
91305       sqlite3VdbeChangeP1(v, addr, iDb);
91306       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
91307       sqlite3VdbeChangeP1(v, addr+2, iDb);
91308       sqlite3VdbeChangeP2(v, addr+2, iCookie);
91309     }else{
91310       /* Read the specified cookie value */
91311       static const VdbeOpList readCookie[] = {
91312         { OP_Transaction,     0,  0,  0},    /* 0 */
91313         { OP_ReadCookie,      0,  1,  0},    /* 1 */
91314         { OP_ResultRow,       1,  1,  0}
91315       };
91316       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
91317       sqlite3VdbeChangeP1(v, addr, iDb);
91318       sqlite3VdbeChangeP1(v, addr+1, iDb);
91319       sqlite3VdbeChangeP3(v, addr+1, iCookie);
91320       sqlite3VdbeSetNumCols(v, 1);
91321       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
91322     }
91323   }else
91324 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
91325 
91326 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91327   /*
91328   **   PRAGMA compile_options
91329   **
91330   ** Return the names of all compile-time options used in this build,
91331   ** one option per row.
91332   */
91333   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
91334     int i = 0;
91335     const char *zOpt;
91336     sqlite3VdbeSetNumCols(v, 1);
91337     pParse->nMem = 1;
91338     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
91339     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
91340       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
91341       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
91342     }
91343   }else
91344 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
91345 
91346 #ifndef SQLITE_OMIT_WAL
91347   /*
91348   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
91349   **
91350   ** Checkpoint the database.
91351   */
91352   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
91353     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
91354     int eMode = SQLITE_CHECKPOINT_PASSIVE;
91355     if( zRight ){
91356       if( sqlite3StrICmp(zRight, "full")==0 ){
91357         eMode = SQLITE_CHECKPOINT_FULL;
91358       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
91359         eMode = SQLITE_CHECKPOINT_RESTART;
91360       }
91361     }
91362     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
91363     sqlite3VdbeSetNumCols(v, 3);
91364     pParse->nMem = 3;
91365     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
91366     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
91367     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
91368 
91369     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
91370     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
91371   }else
91372 
91373   /*
91374   **   PRAGMA wal_autocheckpoint
91375   **   PRAGMA wal_autocheckpoint = N
91376   **
91377   ** Configure a database connection to automatically checkpoint a database
91378   ** after accumulating N frames in the log. Or query for the current value
91379   ** of N.
91380   */
91381   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
91382     if( zRight ){
91383       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
91384     }
91385     returnSingleInt(pParse, "wal_autocheckpoint",
91386        db->xWalCallback==sqlite3WalDefaultHook ?
91387            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
91388   }else
91389 #endif
91390 
91391 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
91392   /*
91393   ** Report the current state of file logs for all databases
91394   */
91395   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
91396     static const char *const azLockName[] = {
91397       "unlocked", "shared", "reserved", "pending", "exclusive"
91398     };
91399     int i;
91400     sqlite3VdbeSetNumCols(v, 2);
91401     pParse->nMem = 2;
91402     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
91403     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
91404     for(i=0; i<db->nDb; i++){
91405       Btree *pBt;
91406       Pager *pPager;
91407       const char *zState = "unknown";
91408       int j;
91409       if( db->aDb[i].zName==0 ) continue;
91410       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
91411       pBt = db->aDb[i].pBt;
91412       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
91413         zState = "closed";
91414       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
91415                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
91416          zState = azLockName[j];
91417       }
91418       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
91419       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
91420     }
91421 
91422   }else
91423 #endif
91424 
91425 #ifdef SQLITE_HAS_CODEC
91426   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
91427     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
91428   }else
91429   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
91430     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
91431   }else
91432   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
91433                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
91434     int i, h1, h2;
91435     char zKey[40];
91436     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
91437       h1 += 9*(1&(h1>>6));
91438       h2 += 9*(1&(h2>>6));
91439       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
91440     }
91441     if( (zLeft[3] & 0xf)==0xb ){
91442       sqlite3_key(db, zKey, i/2);
91443     }else{
91444       sqlite3_rekey(db, zKey, i/2);
91445     }
91446   }else
91447 #endif
91448 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
91449   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
91450 #ifdef SQLITE_HAS_CODEC
91451     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
91452       sqlite3_activate_see(&zRight[4]);
91453     }
91454 #endif
91455 #ifdef SQLITE_ENABLE_CEROD
91456     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
91457       sqlite3_activate_cerod(&zRight[6]);
91458     }
91459 #endif
91460   }else
91461 #endif
91462 
91463 
91464   {/* Empty ELSE clause */}
91465 
91466   /*
91467   ** Reset the safety level, in case the fullfsync flag or synchronous
91468   ** setting changed.
91469   */
91470 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
91471   if( db->autoCommit ){
91472     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
91473                (db->flags&SQLITE_FullFSync)!=0,
91474                (db->flags&SQLITE_CkptFullFSync)!=0);
91475   }
91476 #endif
91477 pragma_out:
91478   sqlite3DbFree(db, zLeft);
91479   sqlite3DbFree(db, zRight);
91480 }
91481 
91482 #endif /* SQLITE_OMIT_PRAGMA */
91483 
91484 /************** End of pragma.c **********************************************/
91485 /************** Begin file prepare.c *****************************************/
91486 /*
91487 ** 2005 May 25
91488 **
91489 ** The author disclaims copyright to this source code.  In place of
91490 ** a legal notice, here is a blessing:
91491 **
91492 **    May you do good and not evil.
91493 **    May you find forgiveness for yourself and forgive others.
91494 **    May you share freely, never taking more than you give.
91495 **
91496 *************************************************************************
91497 ** This file contains the implementation of the sqlite3_prepare()
91498 ** interface, and routines that contribute to loading the database schema
91499 ** from disk.
91500 */
91501 
91502 /*
91503 ** Fill the InitData structure with an error message that indicates
91504 ** that the database is corrupt.
91505 */
91506 static void corruptSchema(
91507   InitData *pData,     /* Initialization context */
91508   const char *zObj,    /* Object being parsed at the point of error */
91509   const char *zExtra   /* Error information */
91510 ){
91511   sqlite3 *db = pData->db;
91512   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
91513     if( zObj==0 ) zObj = "?";
91514     sqlite3SetString(pData->pzErrMsg, db,
91515       "malformed database schema (%s)", zObj);
91516     if( zExtra ){
91517       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
91518                                  "%s - %s", *pData->pzErrMsg, zExtra);
91519     }
91520   }
91521   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
91522 }
91523 
91524 /*
91525 ** This is the callback routine for the code that initializes the
91526 ** database.  See sqlite3Init() below for additional information.
91527 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
91528 **
91529 ** Each callback contains the following information:
91530 **
91531 **     argv[0] = name of thing being created
91532 **     argv[1] = root page number for table or index. 0 for trigger or view.
91533 **     argv[2] = SQL text for the CREATE statement.
91534 **
91535 */
91536 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
91537   InitData *pData = (InitData*)pInit;
91538   sqlite3 *db = pData->db;
91539   int iDb = pData->iDb;
91540 
91541   assert( argc==3 );
91542   UNUSED_PARAMETER2(NotUsed, argc);
91543   assert( sqlite3_mutex_held(db->mutex) );
91544   DbClearProperty(db, iDb, DB_Empty);
91545   if( db->mallocFailed ){
91546     corruptSchema(pData, argv[0], 0);
91547     return 1;
91548   }
91549 
91550   assert( iDb>=0 && iDb<db->nDb );
91551   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
91552   if( argv[1]==0 ){
91553     corruptSchema(pData, argv[0], 0);
91554   }else if( argv[2] && argv[2][0] ){
91555     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
91556     ** But because db->init.busy is set to 1, no VDBE code is generated
91557     ** or executed.  All the parser does is build the internal data
91558     ** structures that describe the table, index, or view.
91559     */
91560     int rc;
91561     sqlite3_stmt *pStmt;
91562     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
91563 
91564     assert( db->init.busy );
91565     db->init.iDb = iDb;
91566     db->init.newTnum = sqlite3Atoi(argv[1]);
91567     db->init.orphanTrigger = 0;
91568     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
91569     rc = db->errCode;
91570     assert( (rc&0xFF)==(rcp&0xFF) );
91571     db->init.iDb = 0;
91572     if( SQLITE_OK!=rc ){
91573       if( db->init.orphanTrigger ){
91574         assert( iDb==1 );
91575       }else{
91576         pData->rc = rc;
91577         if( rc==SQLITE_NOMEM ){
91578           db->mallocFailed = 1;
91579         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
91580           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
91581         }
91582       }
91583     }
91584     sqlite3_finalize(pStmt);
91585   }else if( argv[0]==0 ){
91586     corruptSchema(pData, 0, 0);
91587   }else{
91588     /* If the SQL column is blank it means this is an index that
91589     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
91590     ** constraint for a CREATE TABLE.  The index should have already
91591     ** been created when we processed the CREATE TABLE.  All we have
91592     ** to do here is record the root page number for that index.
91593     */
91594     Index *pIndex;
91595     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
91596     if( pIndex==0 ){
91597       /* This can occur if there exists an index on a TEMP table which
91598       ** has the same name as another index on a permanent index.  Since
91599       ** the permanent table is hidden by the TEMP table, we can also
91600       ** safely ignore the index on the permanent table.
91601       */
91602       /* Do Nothing */;
91603     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
91604       corruptSchema(pData, argv[0], "invalid rootpage");
91605     }
91606   }
91607   return 0;
91608 }
91609 
91610 /*
91611 ** Attempt to read the database schema and initialize internal
91612 ** data structures for a single database file.  The index of the
91613 ** database file is given by iDb.  iDb==0 is used for the main
91614 ** database.  iDb==1 should never be used.  iDb>=2 is used for
91615 ** auxiliary databases.  Return one of the SQLITE_ error codes to
91616 ** indicate success or failure.
91617 */
91618 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
91619   int rc;
91620   int i;
91621   int size;
91622   Table *pTab;
91623   Db *pDb;
91624   char const *azArg[4];
91625   int meta[5];
91626   InitData initData;
91627   char const *zMasterSchema;
91628   char const *zMasterName;
91629   int openedTransaction = 0;
91630 
91631   /*
91632   ** The master database table has a structure like this
91633   */
91634   static const char master_schema[] =
91635      "CREATE TABLE sqlite_master(\n"
91636      "  type text,\n"
91637      "  name text,\n"
91638      "  tbl_name text,\n"
91639      "  rootpage integer,\n"
91640      "  sql text\n"
91641      ")"
91642   ;
91643 #ifndef SQLITE_OMIT_TEMPDB
91644   static const char temp_master_schema[] =
91645      "CREATE TEMP TABLE sqlite_temp_master(\n"
91646      "  type text,\n"
91647      "  name text,\n"
91648      "  tbl_name text,\n"
91649      "  rootpage integer,\n"
91650      "  sql text\n"
91651      ")"
91652   ;
91653 #else
91654   #define temp_master_schema 0
91655 #endif
91656 
91657   assert( iDb>=0 && iDb<db->nDb );
91658   assert( db->aDb[iDb].pSchema );
91659   assert( sqlite3_mutex_held(db->mutex) );
91660   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
91661 
91662   /* zMasterSchema and zInitScript are set to point at the master schema
91663   ** and initialisation script appropriate for the database being
91664   ** initialised. zMasterName is the name of the master table.
91665   */
91666   if( !OMIT_TEMPDB && iDb==1 ){
91667     zMasterSchema = temp_master_schema;
91668   }else{
91669     zMasterSchema = master_schema;
91670   }
91671   zMasterName = SCHEMA_TABLE(iDb);
91672 
91673   /* Construct the schema tables.  */
91674   azArg[0] = zMasterName;
91675   azArg[1] = "1";
91676   azArg[2] = zMasterSchema;
91677   azArg[3] = 0;
91678   initData.db = db;
91679   initData.iDb = iDb;
91680   initData.rc = SQLITE_OK;
91681   initData.pzErrMsg = pzErrMsg;
91682   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
91683   if( initData.rc ){
91684     rc = initData.rc;
91685     goto error_out;
91686   }
91687   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
91688   if( ALWAYS(pTab) ){
91689     pTab->tabFlags |= TF_Readonly;
91690   }
91691 
91692   /* Create a cursor to hold the database open
91693   */
91694   pDb = &db->aDb[iDb];
91695   if( pDb->pBt==0 ){
91696     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
91697       DbSetProperty(db, 1, DB_SchemaLoaded);
91698     }
91699     return SQLITE_OK;
91700   }
91701 
91702   /* If there is not already a read-only (or read-write) transaction opened
91703   ** on the b-tree database, open one now. If a transaction is opened, it
91704   ** will be closed before this function returns.  */
91705   sqlite3BtreeEnter(pDb->pBt);
91706   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
91707     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
91708     if( rc!=SQLITE_OK ){
91709       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
91710       goto initone_error_out;
91711     }
91712     openedTransaction = 1;
91713   }
91714 
91715   /* Get the database meta information.
91716   **
91717   ** Meta values are as follows:
91718   **    meta[0]   Schema cookie.  Changes with each schema change.
91719   **    meta[1]   File format of schema layer.
91720   **    meta[2]   Size of the page cache.
91721   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
91722   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
91723   **    meta[5]   User version
91724   **    meta[6]   Incremental vacuum mode
91725   **    meta[7]   unused
91726   **    meta[8]   unused
91727   **    meta[9]   unused
91728   **
91729   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
91730   ** the possible values of meta[4].
91731   */
91732   for(i=0; i<ArraySize(meta); i++){
91733     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
91734   }
91735   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
91736 
91737   /* If opening a non-empty database, check the text encoding. For the
91738   ** main database, set sqlite3.enc to the encoding of the main database.
91739   ** For an attached db, it is an error if the encoding is not the same
91740   ** as sqlite3.enc.
91741   */
91742   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
91743     if( iDb==0 ){
91744       u8 encoding;
91745       /* If opening the main database, set ENC(db). */
91746       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
91747       if( encoding==0 ) encoding = SQLITE_UTF8;
91748       ENC(db) = encoding;
91749       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
91750     }else{
91751       /* If opening an attached database, the encoding much match ENC(db) */
91752       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
91753         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
91754             " text encoding as main database");
91755         rc = SQLITE_ERROR;
91756         goto initone_error_out;
91757       }
91758     }
91759   }else{
91760     DbSetProperty(db, iDb, DB_Empty);
91761   }
91762   pDb->pSchema->enc = ENC(db);
91763 
91764   if( pDb->pSchema->cache_size==0 ){
91765     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
91766     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
91767     pDb->pSchema->cache_size = size;
91768     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
91769   }
91770 
91771   /*
91772   ** file_format==1    Version 3.0.0.
91773   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
91774   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
91775   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
91776   */
91777   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
91778   if( pDb->pSchema->file_format==0 ){
91779     pDb->pSchema->file_format = 1;
91780   }
91781   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
91782     sqlite3SetString(pzErrMsg, db, "unsupported file format");
91783     rc = SQLITE_ERROR;
91784     goto initone_error_out;
91785   }
91786 
91787   /* Ticket #2804:  When we open a database in the newer file format,
91788   ** clear the legacy_file_format pragma flag so that a VACUUM will
91789   ** not downgrade the database and thus invalidate any descending
91790   ** indices that the user might have created.
91791   */
91792   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
91793     db->flags &= ~SQLITE_LegacyFileFmt;
91794   }
91795 
91796   /* Read the schema information out of the schema tables
91797   */
91798   assert( db->init.busy );
91799   {
91800     char *zSql;
91801     zSql = sqlite3MPrintf(db,
91802         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
91803         db->aDb[iDb].zName, zMasterName);
91804 #ifndef SQLITE_OMIT_AUTHORIZATION
91805     {
91806       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
91807       xAuth = db->xAuth;
91808       db->xAuth = 0;
91809 #endif
91810       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
91811 #ifndef SQLITE_OMIT_AUTHORIZATION
91812       db->xAuth = xAuth;
91813     }
91814 #endif
91815     if( rc==SQLITE_OK ) rc = initData.rc;
91816     sqlite3DbFree(db, zSql);
91817 #ifndef SQLITE_OMIT_ANALYZE
91818     if( rc==SQLITE_OK ){
91819       sqlite3AnalysisLoad(db, iDb);
91820     }
91821 #endif
91822   }
91823   if( db->mallocFailed ){
91824     rc = SQLITE_NOMEM;
91825     sqlite3ResetInternalSchema(db, -1);
91826   }
91827   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
91828     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
91829     ** the schema loaded, even if errors occurred. In this situation the
91830     ** current sqlite3_prepare() operation will fail, but the following one
91831     ** will attempt to compile the supplied statement against whatever subset
91832     ** of the schema was loaded before the error occurred. The primary
91833     ** purpose of this is to allow access to the sqlite_master table
91834     ** even when its contents have been corrupted.
91835     */
91836     DbSetProperty(db, iDb, DB_SchemaLoaded);
91837     rc = SQLITE_OK;
91838   }
91839 
91840   /* Jump here for an error that occurs after successfully allocating
91841   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
91842   ** before that point, jump to error_out.
91843   */
91844 initone_error_out:
91845   if( openedTransaction ){
91846     sqlite3BtreeCommit(pDb->pBt);
91847   }
91848   sqlite3BtreeLeave(pDb->pBt);
91849 
91850 error_out:
91851   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
91852     db->mallocFailed = 1;
91853   }
91854   return rc;
91855 }
91856 
91857 /*
91858 ** Initialize all database files - the main database file, the file
91859 ** used to store temporary tables, and any additional database files
91860 ** created using ATTACH statements.  Return a success code.  If an
91861 ** error occurs, write an error message into *pzErrMsg.
91862 **
91863 ** After a database is initialized, the DB_SchemaLoaded bit is set
91864 ** bit is set in the flags field of the Db structure. If the database
91865 ** file was of zero-length, then the DB_Empty flag is also set.
91866 */
91867 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
91868   int i, rc;
91869   int commit_internal = !(db->flags&SQLITE_InternChanges);
91870 
91871   assert( sqlite3_mutex_held(db->mutex) );
91872   rc = SQLITE_OK;
91873   db->init.busy = 1;
91874   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
91875     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
91876     rc = sqlite3InitOne(db, i, pzErrMsg);
91877     if( rc ){
91878       sqlite3ResetInternalSchema(db, i);
91879     }
91880   }
91881 
91882   /* Once all the other databases have been initialised, load the schema
91883   ** for the TEMP database. This is loaded last, as the TEMP database
91884   ** schema may contain references to objects in other databases.
91885   */
91886 #ifndef SQLITE_OMIT_TEMPDB
91887   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
91888                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
91889     rc = sqlite3InitOne(db, 1, pzErrMsg);
91890     if( rc ){
91891       sqlite3ResetInternalSchema(db, 1);
91892     }
91893   }
91894 #endif
91895 
91896   db->init.busy = 0;
91897   if( rc==SQLITE_OK && commit_internal ){
91898     sqlite3CommitInternalChanges(db);
91899   }
91900 
91901   return rc;
91902 }
91903 
91904 /*
91905 ** This routine is a no-op if the database schema is already initialised.
91906 ** Otherwise, the schema is loaded. An error code is returned.
91907 */
91908 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
91909   int rc = SQLITE_OK;
91910   sqlite3 *db = pParse->db;
91911   assert( sqlite3_mutex_held(db->mutex) );
91912   if( !db->init.busy ){
91913     rc = sqlite3Init(db, &pParse->zErrMsg);
91914   }
91915   if( rc!=SQLITE_OK ){
91916     pParse->rc = rc;
91917     pParse->nErr++;
91918   }
91919   return rc;
91920 }
91921 
91922 
91923 /*
91924 ** Check schema cookies in all databases.  If any cookie is out
91925 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
91926 ** make no changes to pParse->rc.
91927 */
91928 static void schemaIsValid(Parse *pParse){
91929   sqlite3 *db = pParse->db;
91930   int iDb;
91931   int rc;
91932   int cookie;
91933 
91934   assert( pParse->checkSchema );
91935   assert( sqlite3_mutex_held(db->mutex) );
91936   for(iDb=0; iDb<db->nDb; iDb++){
91937     int openedTransaction = 0;         /* True if a transaction is opened */
91938     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
91939     if( pBt==0 ) continue;
91940 
91941     /* If there is not already a read-only (or read-write) transaction opened
91942     ** on the b-tree database, open one now. If a transaction is opened, it
91943     ** will be closed immediately after reading the meta-value. */
91944     if( !sqlite3BtreeIsInReadTrans(pBt) ){
91945       rc = sqlite3BtreeBeginTrans(pBt, 0);
91946       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
91947         db->mallocFailed = 1;
91948       }
91949       if( rc!=SQLITE_OK ) return;
91950       openedTransaction = 1;
91951     }
91952 
91953     /* Read the schema cookie from the database. If it does not match the
91954     ** value stored as part of the in-memory schema representation,
91955     ** set Parse.rc to SQLITE_SCHEMA. */
91956     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
91957     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91958     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
91959       sqlite3ResetInternalSchema(db, iDb);
91960       pParse->rc = SQLITE_SCHEMA;
91961     }
91962 
91963     /* Close the transaction, if one was opened. */
91964     if( openedTransaction ){
91965       sqlite3BtreeCommit(pBt);
91966     }
91967   }
91968 }
91969 
91970 /*
91971 ** Convert a schema pointer into the iDb index that indicates
91972 ** which database file in db->aDb[] the schema refers to.
91973 **
91974 ** If the same database is attached more than once, the first
91975 ** attached database is returned.
91976 */
91977 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
91978   int i = -1000000;
91979 
91980   /* If pSchema is NULL, then return -1000000. This happens when code in
91981   ** expr.c is trying to resolve a reference to a transient table (i.e. one
91982   ** created by a sub-select). In this case the return value of this
91983   ** function should never be used.
91984   **
91985   ** We return -1000000 instead of the more usual -1 simply because using
91986   ** -1000000 as the incorrect index into db->aDb[] is much
91987   ** more likely to cause a segfault than -1 (of course there are assert()
91988   ** statements too, but it never hurts to play the odds).
91989   */
91990   assert( sqlite3_mutex_held(db->mutex) );
91991   if( pSchema ){
91992     for(i=0; ALWAYS(i<db->nDb); i++){
91993       if( db->aDb[i].pSchema==pSchema ){
91994         break;
91995       }
91996     }
91997     assert( i>=0 && i<db->nDb );
91998   }
91999   return i;
92000 }
92001 
92002 /*
92003 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
92004 */
92005 static int sqlite3Prepare(
92006   sqlite3 *db,              /* Database handle. */
92007   const char *zSql,         /* UTF-8 encoded SQL statement. */
92008   int nBytes,               /* Length of zSql in bytes. */
92009   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
92010   Vdbe *pReprepare,         /* VM being reprepared */
92011   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92012   const char **pzTail       /* OUT: End of parsed string */
92013 ){
92014   Parse *pParse;            /* Parsing context */
92015   char *zErrMsg = 0;        /* Error message */
92016   int rc = SQLITE_OK;       /* Result code */
92017   int i;                    /* Loop counter */
92018 
92019   /* Allocate the parsing context */
92020   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
92021   if( pParse==0 ){
92022     rc = SQLITE_NOMEM;
92023     goto end_prepare;
92024   }
92025   pParse->pReprepare = pReprepare;
92026   assert( ppStmt && *ppStmt==0 );
92027   assert( !db->mallocFailed );
92028   assert( sqlite3_mutex_held(db->mutex) );
92029 
92030   /* Check to verify that it is possible to get a read lock on all
92031   ** database schemas.  The inability to get a read lock indicates that
92032   ** some other database connection is holding a write-lock, which in
92033   ** turn means that the other connection has made uncommitted changes
92034   ** to the schema.
92035   **
92036   ** Were we to proceed and prepare the statement against the uncommitted
92037   ** schema changes and if those schema changes are subsequently rolled
92038   ** back and different changes are made in their place, then when this
92039   ** prepared statement goes to run the schema cookie would fail to detect
92040   ** the schema change.  Disaster would follow.
92041   **
92042   ** This thread is currently holding mutexes on all Btrees (because
92043   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
92044   ** is not possible for another thread to start a new schema change
92045   ** while this routine is running.  Hence, we do not need to hold
92046   ** locks on the schema, we just need to make sure nobody else is
92047   ** holding them.
92048   **
92049   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
92050   ** but it does *not* override schema lock detection, so this all still
92051   ** works even if READ_UNCOMMITTED is set.
92052   */
92053   for(i=0; i<db->nDb; i++) {
92054     Btree *pBt = db->aDb[i].pBt;
92055     if( pBt ){
92056       assert( sqlite3BtreeHoldsMutex(pBt) );
92057       rc = sqlite3BtreeSchemaLocked(pBt);
92058       if( rc ){
92059         const char *zDb = db->aDb[i].zName;
92060         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
92061         testcase( db->flags & SQLITE_ReadUncommitted );
92062         goto end_prepare;
92063       }
92064     }
92065   }
92066 
92067   sqlite3VtabUnlockList(db);
92068 
92069   pParse->db = db;
92070   pParse->nQueryLoop = (double)1;
92071   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
92072     char *zSqlCopy;
92073     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
92074     testcase( nBytes==mxLen );
92075     testcase( nBytes==mxLen+1 );
92076     if( nBytes>mxLen ){
92077       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
92078       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
92079       goto end_prepare;
92080     }
92081     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
92082     if( zSqlCopy ){
92083       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
92084       sqlite3DbFree(db, zSqlCopy);
92085       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
92086     }else{
92087       pParse->zTail = &zSql[nBytes];
92088     }
92089   }else{
92090     sqlite3RunParser(pParse, zSql, &zErrMsg);
92091   }
92092   assert( 1==(int)pParse->nQueryLoop );
92093 
92094   if( db->mallocFailed ){
92095     pParse->rc = SQLITE_NOMEM;
92096   }
92097   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
92098   if( pParse->checkSchema ){
92099     schemaIsValid(pParse);
92100   }
92101   if( db->mallocFailed ){
92102     pParse->rc = SQLITE_NOMEM;
92103   }
92104   if( pzTail ){
92105     *pzTail = pParse->zTail;
92106   }
92107   rc = pParse->rc;
92108 
92109 #ifndef SQLITE_OMIT_EXPLAIN
92110   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
92111     static const char * const azColName[] = {
92112        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
92113        "selectid", "order", "from", "detail"
92114     };
92115     int iFirst, mx;
92116     if( pParse->explain==2 ){
92117       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
92118       iFirst = 8;
92119       mx = 12;
92120     }else{
92121       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
92122       iFirst = 0;
92123       mx = 8;
92124     }
92125     for(i=iFirst; i<mx; i++){
92126       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
92127                             azColName[i], SQLITE_STATIC);
92128     }
92129   }
92130 #endif
92131 
92132   assert( db->init.busy==0 || saveSqlFlag==0 );
92133   if( db->init.busy==0 ){
92134     Vdbe *pVdbe = pParse->pVdbe;
92135     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
92136   }
92137   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
92138     sqlite3VdbeFinalize(pParse->pVdbe);
92139     assert(!(*ppStmt));
92140   }else{
92141     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
92142   }
92143 
92144   if( zErrMsg ){
92145     sqlite3Error(db, rc, "%s", zErrMsg);
92146     sqlite3DbFree(db, zErrMsg);
92147   }else{
92148     sqlite3Error(db, rc, 0);
92149   }
92150 
92151   /* Delete any TriggerPrg structures allocated while parsing this statement. */
92152   while( pParse->pTriggerPrg ){
92153     TriggerPrg *pT = pParse->pTriggerPrg;
92154     pParse->pTriggerPrg = pT->pNext;
92155     sqlite3DbFree(db, pT);
92156   }
92157 
92158 end_prepare:
92159 
92160   sqlite3StackFree(db, pParse);
92161   rc = sqlite3ApiExit(db, rc);
92162   assert( (rc&db->errMask)==rc );
92163   return rc;
92164 }
92165 static int sqlite3LockAndPrepare(
92166   sqlite3 *db,              /* Database handle. */
92167   const char *zSql,         /* UTF-8 encoded SQL statement. */
92168   int nBytes,               /* Length of zSql in bytes. */
92169   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
92170   Vdbe *pOld,               /* VM being reprepared */
92171   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92172   const char **pzTail       /* OUT: End of parsed string */
92173 ){
92174   int rc;
92175   assert( ppStmt!=0 );
92176   *ppStmt = 0;
92177   if( !sqlite3SafetyCheckOk(db) ){
92178     return SQLITE_MISUSE_BKPT;
92179   }
92180   sqlite3_mutex_enter(db->mutex);
92181   sqlite3BtreeEnterAll(db);
92182   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
92183   if( rc==SQLITE_SCHEMA ){
92184     sqlite3_finalize(*ppStmt);
92185     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
92186   }
92187   sqlite3BtreeLeaveAll(db);
92188   sqlite3_mutex_leave(db->mutex);
92189   return rc;
92190 }
92191 
92192 /*
92193 ** Rerun the compilation of a statement after a schema change.
92194 **
92195 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
92196 ** if the statement cannot be recompiled because another connection has
92197 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
92198 ** occurs, return SQLITE_SCHEMA.
92199 */
92200 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
92201   int rc;
92202   sqlite3_stmt *pNew;
92203   const char *zSql;
92204   sqlite3 *db;
92205 
92206   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
92207   zSql = sqlite3_sql((sqlite3_stmt *)p);
92208   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
92209   db = sqlite3VdbeDb(p);
92210   assert( sqlite3_mutex_held(db->mutex) );
92211   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
92212   if( rc ){
92213     if( rc==SQLITE_NOMEM ){
92214       db->mallocFailed = 1;
92215     }
92216     assert( pNew==0 );
92217     return rc;
92218   }else{
92219     assert( pNew!=0 );
92220   }
92221   sqlite3VdbeSwap((Vdbe*)pNew, p);
92222   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
92223   sqlite3VdbeResetStepResult((Vdbe*)pNew);
92224   sqlite3VdbeFinalize((Vdbe*)pNew);
92225   return SQLITE_OK;
92226 }
92227 
92228 
92229 /*
92230 ** Two versions of the official API.  Legacy and new use.  In the legacy
92231 ** version, the original SQL text is not saved in the prepared statement
92232 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
92233 ** sqlite3_step().  In the new version, the original SQL text is retained
92234 ** and the statement is automatically recompiled if an schema change
92235 ** occurs.
92236 */
92237 SQLITE_API int sqlite3_prepare(
92238   sqlite3 *db,              /* Database handle. */
92239   const char *zSql,         /* UTF-8 encoded SQL statement. */
92240   int nBytes,               /* Length of zSql in bytes. */
92241   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92242   const char **pzTail       /* OUT: End of parsed string */
92243 ){
92244   int rc;
92245   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
92246   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
92247   return rc;
92248 }
92249 SQLITE_API int sqlite3_prepare_v2(
92250   sqlite3 *db,              /* Database handle. */
92251   const char *zSql,         /* UTF-8 encoded SQL statement. */
92252   int nBytes,               /* Length of zSql in bytes. */
92253   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92254   const char **pzTail       /* OUT: End of parsed string */
92255 ){
92256   int rc;
92257   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
92258   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
92259   return rc;
92260 }
92261 
92262 
92263 #ifndef SQLITE_OMIT_UTF16
92264 /*
92265 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
92266 */
92267 static int sqlite3Prepare16(
92268   sqlite3 *db,              /* Database handle. */
92269   const void *zSql,         /* UTF-16 encoded SQL statement. */
92270   int nBytes,               /* Length of zSql in bytes. */
92271   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
92272   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92273   const void **pzTail       /* OUT: End of parsed string */
92274 ){
92275   /* This function currently works by first transforming the UTF-16
92276   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
92277   ** tricky bit is figuring out the pointer to return in *pzTail.
92278   */
92279   char *zSql8;
92280   const char *zTail8 = 0;
92281   int rc = SQLITE_OK;
92282 
92283   assert( ppStmt );
92284   *ppStmt = 0;
92285   if( !sqlite3SafetyCheckOk(db) ){
92286     return SQLITE_MISUSE_BKPT;
92287   }
92288   sqlite3_mutex_enter(db->mutex);
92289   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
92290   if( zSql8 ){
92291     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
92292   }
92293 
92294   if( zTail8 && pzTail ){
92295     /* If sqlite3_prepare returns a tail pointer, we calculate the
92296     ** equivalent pointer into the UTF-16 string by counting the unicode
92297     ** characters between zSql8 and zTail8, and then returning a pointer
92298     ** the same number of characters into the UTF-16 string.
92299     */
92300     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
92301     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
92302   }
92303   sqlite3DbFree(db, zSql8);
92304   rc = sqlite3ApiExit(db, rc);
92305   sqlite3_mutex_leave(db->mutex);
92306   return rc;
92307 }
92308 
92309 /*
92310 ** Two versions of the official API.  Legacy and new use.  In the legacy
92311 ** version, the original SQL text is not saved in the prepared statement
92312 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
92313 ** sqlite3_step().  In the new version, the original SQL text is retained
92314 ** and the statement is automatically recompiled if an schema change
92315 ** occurs.
92316 */
92317 SQLITE_API int sqlite3_prepare16(
92318   sqlite3 *db,              /* Database handle. */
92319   const void *zSql,         /* UTF-16 encoded SQL statement. */
92320   int nBytes,               /* Length of zSql in bytes. */
92321   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92322   const void **pzTail       /* OUT: End of parsed string */
92323 ){
92324   int rc;
92325   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
92326   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
92327   return rc;
92328 }
92329 SQLITE_API int sqlite3_prepare16_v2(
92330   sqlite3 *db,              /* Database handle. */
92331   const void *zSql,         /* UTF-16 encoded SQL statement. */
92332   int nBytes,               /* Length of zSql in bytes. */
92333   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
92334   const void **pzTail       /* OUT: End of parsed string */
92335 ){
92336   int rc;
92337   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
92338   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
92339   return rc;
92340 }
92341 
92342 #endif /* SQLITE_OMIT_UTF16 */
92343 
92344 /************** End of prepare.c *********************************************/
92345 /************** Begin file select.c ******************************************/
92346 /*
92347 ** 2001 September 15
92348 **
92349 ** The author disclaims copyright to this source code.  In place of
92350 ** a legal notice, here is a blessing:
92351 **
92352 **    May you do good and not evil.
92353 **    May you find forgiveness for yourself and forgive others.
92354 **    May you share freely, never taking more than you give.
92355 **
92356 *************************************************************************
92357 ** This file contains C code routines that are called by the parser
92358 ** to handle SELECT statements in SQLite.
92359 */
92360 
92361 
92362 /*
92363 ** Delete all the content of a Select structure but do not deallocate
92364 ** the select structure itself.
92365 */
92366 static void clearSelect(sqlite3 *db, Select *p){
92367   sqlite3ExprListDelete(db, p->pEList);
92368   sqlite3SrcListDelete(db, p->pSrc);
92369   sqlite3ExprDelete(db, p->pWhere);
92370   sqlite3ExprListDelete(db, p->pGroupBy);
92371   sqlite3ExprDelete(db, p->pHaving);
92372   sqlite3ExprListDelete(db, p->pOrderBy);
92373   sqlite3SelectDelete(db, p->pPrior);
92374   sqlite3ExprDelete(db, p->pLimit);
92375   sqlite3ExprDelete(db, p->pOffset);
92376 }
92377 
92378 /*
92379 ** Initialize a SelectDest structure.
92380 */
92381 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
92382   pDest->eDest = (u8)eDest;
92383   pDest->iParm = iParm;
92384   pDest->affinity = 0;
92385   pDest->iMem = 0;
92386   pDest->nMem = 0;
92387 }
92388 
92389 
92390 /*
92391 ** Allocate a new Select structure and return a pointer to that
92392 ** structure.
92393 */
92394 SQLITE_PRIVATE Select *sqlite3SelectNew(
92395   Parse *pParse,        /* Parsing context */
92396   ExprList *pEList,     /* which columns to include in the result */
92397   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
92398   Expr *pWhere,         /* the WHERE clause */
92399   ExprList *pGroupBy,   /* the GROUP BY clause */
92400   Expr *pHaving,        /* the HAVING clause */
92401   ExprList *pOrderBy,   /* the ORDER BY clause */
92402   int isDistinct,       /* true if the DISTINCT keyword is present */
92403   Expr *pLimit,         /* LIMIT value.  NULL means not used */
92404   Expr *pOffset         /* OFFSET value.  NULL means no offset */
92405 ){
92406   Select *pNew;
92407   Select standin;
92408   sqlite3 *db = pParse->db;
92409   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
92410   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
92411   if( pNew==0 ){
92412     pNew = &standin;
92413     memset(pNew, 0, sizeof(*pNew));
92414   }
92415   if( pEList==0 ){
92416     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
92417   }
92418   pNew->pEList = pEList;
92419   pNew->pSrc = pSrc;
92420   pNew->pWhere = pWhere;
92421   pNew->pGroupBy = pGroupBy;
92422   pNew->pHaving = pHaving;
92423   pNew->pOrderBy = pOrderBy;
92424   pNew->selFlags = isDistinct ? SF_Distinct : 0;
92425   pNew->op = TK_SELECT;
92426   pNew->pLimit = pLimit;
92427   pNew->pOffset = pOffset;
92428   assert( pOffset==0 || pLimit!=0 );
92429   pNew->addrOpenEphm[0] = -1;
92430   pNew->addrOpenEphm[1] = -1;
92431   pNew->addrOpenEphm[2] = -1;
92432   if( db->mallocFailed ) {
92433     clearSelect(db, pNew);
92434     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
92435     pNew = 0;
92436   }else{
92437     assert( pNew->pSrc!=0 || pParse->nErr>0 );
92438   }
92439   return pNew;
92440 }
92441 
92442 /*
92443 ** Delete the given Select structure and all of its substructures.
92444 */
92445 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
92446   if( p ){
92447     clearSelect(db, p);
92448     sqlite3DbFree(db, p);
92449   }
92450 }
92451 
92452 /*
92453 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
92454 ** type of join.  Return an integer constant that expresses that type
92455 ** in terms of the following bit values:
92456 **
92457 **     JT_INNER
92458 **     JT_CROSS
92459 **     JT_OUTER
92460 **     JT_NATURAL
92461 **     JT_LEFT
92462 **     JT_RIGHT
92463 **
92464 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
92465 **
92466 ** If an illegal or unsupported join type is seen, then still return
92467 ** a join type, but put an error in the pParse structure.
92468 */
92469 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
92470   int jointype = 0;
92471   Token *apAll[3];
92472   Token *p;
92473                              /*   0123456789 123456789 123456789 123 */
92474   static const char zKeyText[] = "naturaleftouterightfullinnercross";
92475   static const struct {
92476     u8 i;        /* Beginning of keyword text in zKeyText[] */
92477     u8 nChar;    /* Length of the keyword in characters */
92478     u8 code;     /* Join type mask */
92479   } aKeyword[] = {
92480     /* natural */ { 0,  7, JT_NATURAL                },
92481     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
92482     /* outer   */ { 10, 5, JT_OUTER                  },
92483     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
92484     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
92485     /* inner   */ { 23, 5, JT_INNER                  },
92486     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
92487   };
92488   int i, j;
92489   apAll[0] = pA;
92490   apAll[1] = pB;
92491   apAll[2] = pC;
92492   for(i=0; i<3 && apAll[i]; i++){
92493     p = apAll[i];
92494     for(j=0; j<ArraySize(aKeyword); j++){
92495       if( p->n==aKeyword[j].nChar
92496           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
92497         jointype |= aKeyword[j].code;
92498         break;
92499       }
92500     }
92501     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
92502     if( j>=ArraySize(aKeyword) ){
92503       jointype |= JT_ERROR;
92504       break;
92505     }
92506   }
92507   if(
92508      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
92509      (jointype & JT_ERROR)!=0
92510   ){
92511     const char *zSp = " ";
92512     assert( pB!=0 );
92513     if( pC==0 ){ zSp++; }
92514     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
92515        "%T %T%s%T", pA, pB, zSp, pC);
92516     jointype = JT_INNER;
92517   }else if( (jointype & JT_OUTER)!=0
92518          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
92519     sqlite3ErrorMsg(pParse,
92520       "RIGHT and FULL OUTER JOINs are not currently supported");
92521     jointype = JT_INNER;
92522   }
92523   return jointype;
92524 }
92525 
92526 /*
92527 ** Return the index of a column in a table.  Return -1 if the column
92528 ** is not contained in the table.
92529 */
92530 static int columnIndex(Table *pTab, const char *zCol){
92531   int i;
92532   for(i=0; i<pTab->nCol; i++){
92533     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
92534   }
92535   return -1;
92536 }
92537 
92538 /*
92539 ** Search the first N tables in pSrc, from left to right, looking for a
92540 ** table that has a column named zCol.
92541 **
92542 ** When found, set *piTab and *piCol to the table index and column index
92543 ** of the matching column and return TRUE.
92544 **
92545 ** If not found, return FALSE.
92546 */
92547 static int tableAndColumnIndex(
92548   SrcList *pSrc,       /* Array of tables to search */
92549   int N,               /* Number of tables in pSrc->a[] to search */
92550   const char *zCol,    /* Name of the column we are looking for */
92551   int *piTab,          /* Write index of pSrc->a[] here */
92552   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
92553 ){
92554   int i;               /* For looping over tables in pSrc */
92555   int iCol;            /* Index of column matching zCol */
92556 
92557   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
92558   for(i=0; i<N; i++){
92559     iCol = columnIndex(pSrc->a[i].pTab, zCol);
92560     if( iCol>=0 ){
92561       if( piTab ){
92562         *piTab = i;
92563         *piCol = iCol;
92564       }
92565       return 1;
92566     }
92567   }
92568   return 0;
92569 }
92570 
92571 /*
92572 ** This function is used to add terms implied by JOIN syntax to the
92573 ** WHERE clause expression of a SELECT statement. The new term, which
92574 ** is ANDed with the existing WHERE clause, is of the form:
92575 **
92576 **    (tab1.col1 = tab2.col2)
92577 **
92578 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
92579 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
92580 ** column iColRight of tab2.
92581 */
92582 static void addWhereTerm(
92583   Parse *pParse,                  /* Parsing context */
92584   SrcList *pSrc,                  /* List of tables in FROM clause */
92585   int iLeft,                      /* Index of first table to join in pSrc */
92586   int iColLeft,                   /* Index of column in first table */
92587   int iRight,                     /* Index of second table in pSrc */
92588   int iColRight,                  /* Index of column in second table */
92589   int isOuterJoin,                /* True if this is an OUTER join */
92590   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
92591 ){
92592   sqlite3 *db = pParse->db;
92593   Expr *pE1;
92594   Expr *pE2;
92595   Expr *pEq;
92596 
92597   assert( iLeft<iRight );
92598   assert( pSrc->nSrc>iRight );
92599   assert( pSrc->a[iLeft].pTab );
92600   assert( pSrc->a[iRight].pTab );
92601 
92602   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
92603   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
92604 
92605   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
92606   if( pEq && isOuterJoin ){
92607     ExprSetProperty(pEq, EP_FromJoin);
92608     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
92609     ExprSetIrreducible(pEq);
92610     pEq->iRightJoinTable = (i16)pE2->iTable;
92611   }
92612   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
92613 }
92614 
92615 /*
92616 ** Set the EP_FromJoin property on all terms of the given expression.
92617 ** And set the Expr.iRightJoinTable to iTable for every term in the
92618 ** expression.
92619 **
92620 ** The EP_FromJoin property is used on terms of an expression to tell
92621 ** the LEFT OUTER JOIN processing logic that this term is part of the
92622 ** join restriction specified in the ON or USING clause and not a part
92623 ** of the more general WHERE clause.  These terms are moved over to the
92624 ** WHERE clause during join processing but we need to remember that they
92625 ** originated in the ON or USING clause.
92626 **
92627 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
92628 ** expression depends on table iRightJoinTable even if that table is not
92629 ** explicitly mentioned in the expression.  That information is needed
92630 ** for cases like this:
92631 **
92632 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
92633 **
92634 ** The where clause needs to defer the handling of the t1.x=5
92635 ** term until after the t2 loop of the join.  In that way, a
92636 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
92637 ** defer the handling of t1.x=5, it will be processed immediately
92638 ** after the t1 loop and rows with t1.x!=5 will never appear in
92639 ** the output, which is incorrect.
92640 */
92641 static void setJoinExpr(Expr *p, int iTable){
92642   while( p ){
92643     ExprSetProperty(p, EP_FromJoin);
92644     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
92645     ExprSetIrreducible(p);
92646     p->iRightJoinTable = (i16)iTable;
92647     setJoinExpr(p->pLeft, iTable);
92648     p = p->pRight;
92649   }
92650 }
92651 
92652 /*
92653 ** This routine processes the join information for a SELECT statement.
92654 ** ON and USING clauses are converted into extra terms of the WHERE clause.
92655 ** NATURAL joins also create extra WHERE clause terms.
92656 **
92657 ** The terms of a FROM clause are contained in the Select.pSrc structure.
92658 ** The left most table is the first entry in Select.pSrc.  The right-most
92659 ** table is the last entry.  The join operator is held in the entry to
92660 ** the left.  Thus entry 0 contains the join operator for the join between
92661 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
92662 ** also attached to the left entry.
92663 **
92664 ** This routine returns the number of errors encountered.
92665 */
92666 static int sqliteProcessJoin(Parse *pParse, Select *p){
92667   SrcList *pSrc;                  /* All tables in the FROM clause */
92668   int i, j;                       /* Loop counters */
92669   struct SrcList_item *pLeft;     /* Left table being joined */
92670   struct SrcList_item *pRight;    /* Right table being joined */
92671 
92672   pSrc = p->pSrc;
92673   pLeft = &pSrc->a[0];
92674   pRight = &pLeft[1];
92675   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
92676     Table *pLeftTab = pLeft->pTab;
92677     Table *pRightTab = pRight->pTab;
92678     int isOuter;
92679 
92680     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
92681     isOuter = (pRight->jointype & JT_OUTER)!=0;
92682 
92683     /* When the NATURAL keyword is present, add WHERE clause terms for
92684     ** every column that the two tables have in common.
92685     */
92686     if( pRight->jointype & JT_NATURAL ){
92687       if( pRight->pOn || pRight->pUsing ){
92688         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
92689            "an ON or USING clause", 0);
92690         return 1;
92691       }
92692       for(j=0; j<pRightTab->nCol; j++){
92693         char *zName;   /* Name of column in the right table */
92694         int iLeft;     /* Matching left table */
92695         int iLeftCol;  /* Matching column in the left table */
92696 
92697         zName = pRightTab->aCol[j].zName;
92698         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
92699           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
92700                        isOuter, &p->pWhere);
92701         }
92702       }
92703     }
92704 
92705     /* Disallow both ON and USING clauses in the same join
92706     */
92707     if( pRight->pOn && pRight->pUsing ){
92708       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
92709         "clauses in the same join");
92710       return 1;
92711     }
92712 
92713     /* Add the ON clause to the end of the WHERE clause, connected by
92714     ** an AND operator.
92715     */
92716     if( pRight->pOn ){
92717       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
92718       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
92719       pRight->pOn = 0;
92720     }
92721 
92722     /* Create extra terms on the WHERE clause for each column named
92723     ** in the USING clause.  Example: If the two tables to be joined are
92724     ** A and B and the USING clause names X, Y, and Z, then add this
92725     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
92726     ** Report an error if any column mentioned in the USING clause is
92727     ** not contained in both tables to be joined.
92728     */
92729     if( pRight->pUsing ){
92730       IdList *pList = pRight->pUsing;
92731       for(j=0; j<pList->nId; j++){
92732         char *zName;     /* Name of the term in the USING clause */
92733         int iLeft;       /* Table on the left with matching column name */
92734         int iLeftCol;    /* Column number of matching column on the left */
92735         int iRightCol;   /* Column number of matching column on the right */
92736 
92737         zName = pList->a[j].zName;
92738         iRightCol = columnIndex(pRightTab, zName);
92739         if( iRightCol<0
92740          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
92741         ){
92742           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
92743             "not present in both tables", zName);
92744           return 1;
92745         }
92746         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
92747                      isOuter, &p->pWhere);
92748       }
92749     }
92750   }
92751   return 0;
92752 }
92753 
92754 /*
92755 ** Insert code into "v" that will push the record on the top of the
92756 ** stack into the sorter.
92757 */
92758 static void pushOntoSorter(
92759   Parse *pParse,         /* Parser context */
92760   ExprList *pOrderBy,    /* The ORDER BY clause */
92761   Select *pSelect,       /* The whole SELECT statement */
92762   int regData            /* Register holding data to be sorted */
92763 ){
92764   Vdbe *v = pParse->pVdbe;
92765   int nExpr = pOrderBy->nExpr;
92766   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
92767   int regRecord = sqlite3GetTempReg(pParse);
92768   int op;
92769   sqlite3ExprCacheClear(pParse);
92770   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
92771   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
92772   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
92773   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
92774   if( pSelect->selFlags & SF_UseSorter ){
92775     op = OP_SorterInsert;
92776   }else{
92777     op = OP_IdxInsert;
92778   }
92779   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
92780   sqlite3ReleaseTempReg(pParse, regRecord);
92781   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
92782   if( pSelect->iLimit ){
92783     int addr1, addr2;
92784     int iLimit;
92785     if( pSelect->iOffset ){
92786       iLimit = pSelect->iOffset+1;
92787     }else{
92788       iLimit = pSelect->iLimit;
92789     }
92790     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
92791     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
92792     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
92793     sqlite3VdbeJumpHere(v, addr1);
92794     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
92795     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
92796     sqlite3VdbeJumpHere(v, addr2);
92797   }
92798 }
92799 
92800 /*
92801 ** Add code to implement the OFFSET
92802 */
92803 static void codeOffset(
92804   Vdbe *v,          /* Generate code into this VM */
92805   Select *p,        /* The SELECT statement being coded */
92806   int iContinue     /* Jump here to skip the current record */
92807 ){
92808   if( p->iOffset && iContinue!=0 ){
92809     int addr;
92810     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
92811     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
92812     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
92813     VdbeComment((v, "skip OFFSET records"));
92814     sqlite3VdbeJumpHere(v, addr);
92815   }
92816 }
92817 
92818 /*
92819 ** Add code that will check to make sure the N registers starting at iMem
92820 ** form a distinct entry.  iTab is a sorting index that holds previously
92821 ** seen combinations of the N values.  A new entry is made in iTab
92822 ** if the current N values are new.
92823 **
92824 ** A jump to addrRepeat is made and the N+1 values are popped from the
92825 ** stack if the top N elements are not distinct.
92826 */
92827 static void codeDistinct(
92828   Parse *pParse,     /* Parsing and code generating context */
92829   int iTab,          /* A sorting index used to test for distinctness */
92830   int addrRepeat,    /* Jump to here if not distinct */
92831   int N,             /* Number of elements */
92832   int iMem           /* First element */
92833 ){
92834   Vdbe *v;
92835   int r1;
92836 
92837   v = pParse->pVdbe;
92838   r1 = sqlite3GetTempReg(pParse);
92839   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
92840   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
92841   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
92842   sqlite3ReleaseTempReg(pParse, r1);
92843 }
92844 
92845 #ifndef SQLITE_OMIT_SUBQUERY
92846 /*
92847 ** Generate an error message when a SELECT is used within a subexpression
92848 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
92849 ** column.  We do this in a subroutine because the error used to occur
92850 ** in multiple places.  (The error only occurs in one place now, but we
92851 ** retain the subroutine to minimize code disruption.)
92852 */
92853 static int checkForMultiColumnSelectError(
92854   Parse *pParse,       /* Parse context. */
92855   SelectDest *pDest,   /* Destination of SELECT results */
92856   int nExpr            /* Number of result columns returned by SELECT */
92857 ){
92858   int eDest = pDest->eDest;
92859   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
92860     sqlite3ErrorMsg(pParse, "only a single result allowed for "
92861        "a SELECT that is part of an expression");
92862     return 1;
92863   }else{
92864     return 0;
92865   }
92866 }
92867 #endif
92868 
92869 /*
92870 ** This routine generates the code for the inside of the inner loop
92871 ** of a SELECT.
92872 **
92873 ** If srcTab and nColumn are both zero, then the pEList expressions
92874 ** are evaluated in order to get the data for this row.  If nColumn>0
92875 ** then data is pulled from srcTab and pEList is used only to get the
92876 ** datatypes for each column.
92877 */
92878 static void selectInnerLoop(
92879   Parse *pParse,          /* The parser context */
92880   Select *p,              /* The complete select statement being coded */
92881   ExprList *pEList,       /* List of values being extracted */
92882   int srcTab,             /* Pull data from this table */
92883   int nColumn,            /* Number of columns in the source table */
92884   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
92885   int distinct,           /* If >=0, make sure results are distinct */
92886   SelectDest *pDest,      /* How to dispose of the results */
92887   int iContinue,          /* Jump here to continue with next row */
92888   int iBreak              /* Jump here to break out of the inner loop */
92889 ){
92890   Vdbe *v = pParse->pVdbe;
92891   int i;
92892   int hasDistinct;        /* True if the DISTINCT keyword is present */
92893   int regResult;              /* Start of memory holding result set */
92894   int eDest = pDest->eDest;   /* How to dispose of results */
92895   int iParm = pDest->iParm;   /* First argument to disposal method */
92896   int nResultCol;             /* Number of result columns */
92897 
92898   assert( v );
92899   if( NEVER(v==0) ) return;
92900   assert( pEList!=0 );
92901   hasDistinct = distinct>=0;
92902   if( pOrderBy==0 && !hasDistinct ){
92903     codeOffset(v, p, iContinue);
92904   }
92905 
92906   /* Pull the requested columns.
92907   */
92908   if( nColumn>0 ){
92909     nResultCol = nColumn;
92910   }else{
92911     nResultCol = pEList->nExpr;
92912   }
92913   if( pDest->iMem==0 ){
92914     pDest->iMem = pParse->nMem+1;
92915     pDest->nMem = nResultCol;
92916     pParse->nMem += nResultCol;
92917   }else{
92918     assert( pDest->nMem==nResultCol );
92919   }
92920   regResult = pDest->iMem;
92921   if( nColumn>0 ){
92922     for(i=0; i<nColumn; i++){
92923       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
92924     }
92925   }else if( eDest!=SRT_Exists ){
92926     /* If the destination is an EXISTS(...) expression, the actual
92927     ** values returned by the SELECT are not required.
92928     */
92929     sqlite3ExprCacheClear(pParse);
92930     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
92931   }
92932   nColumn = nResultCol;
92933 
92934   /* If the DISTINCT keyword was present on the SELECT statement
92935   ** and this row has been seen before, then do not make this row
92936   ** part of the result.
92937   */
92938   if( hasDistinct ){
92939     assert( pEList!=0 );
92940     assert( pEList->nExpr==nColumn );
92941     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
92942     if( pOrderBy==0 ){
92943       codeOffset(v, p, iContinue);
92944     }
92945   }
92946 
92947   switch( eDest ){
92948     /* In this mode, write each query result to the key of the temporary
92949     ** table iParm.
92950     */
92951 #ifndef SQLITE_OMIT_COMPOUND_SELECT
92952     case SRT_Union: {
92953       int r1;
92954       r1 = sqlite3GetTempReg(pParse);
92955       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
92956       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
92957       sqlite3ReleaseTempReg(pParse, r1);
92958       break;
92959     }
92960 
92961     /* Construct a record from the query result, but instead of
92962     ** saving that record, use it as a key to delete elements from
92963     ** the temporary table iParm.
92964     */
92965     case SRT_Except: {
92966       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
92967       break;
92968     }
92969 #endif
92970 
92971     /* Store the result as data using a unique key.
92972     */
92973     case SRT_Table:
92974     case SRT_EphemTab: {
92975       int r1 = sqlite3GetTempReg(pParse);
92976       testcase( eDest==SRT_Table );
92977       testcase( eDest==SRT_EphemTab );
92978       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
92979       if( pOrderBy ){
92980         pushOntoSorter(pParse, pOrderBy, p, r1);
92981       }else{
92982         int r2 = sqlite3GetTempReg(pParse);
92983         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
92984         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
92985         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
92986         sqlite3ReleaseTempReg(pParse, r2);
92987       }
92988       sqlite3ReleaseTempReg(pParse, r1);
92989       break;
92990     }
92991 
92992 #ifndef SQLITE_OMIT_SUBQUERY
92993     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
92994     ** then there should be a single item on the stack.  Write this
92995     ** item into the set table with bogus data.
92996     */
92997     case SRT_Set: {
92998       assert( nColumn==1 );
92999       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
93000       if( pOrderBy ){
93001         /* At first glance you would think we could optimize out the
93002         ** ORDER BY in this case since the order of entries in the set
93003         ** does not matter.  But there might be a LIMIT clause, in which
93004         ** case the order does matter */
93005         pushOntoSorter(pParse, pOrderBy, p, regResult);
93006       }else{
93007         int r1 = sqlite3GetTempReg(pParse);
93008         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
93009         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
93010         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
93011         sqlite3ReleaseTempReg(pParse, r1);
93012       }
93013       break;
93014     }
93015 
93016     /* If any row exist in the result set, record that fact and abort.
93017     */
93018     case SRT_Exists: {
93019       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
93020       /* The LIMIT clause will terminate the loop for us */
93021       break;
93022     }
93023 
93024     /* If this is a scalar select that is part of an expression, then
93025     ** store the results in the appropriate memory cell and break out
93026     ** of the scan loop.
93027     */
93028     case SRT_Mem: {
93029       assert( nColumn==1 );
93030       if( pOrderBy ){
93031         pushOntoSorter(pParse, pOrderBy, p, regResult);
93032       }else{
93033         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
93034         /* The LIMIT clause will jump out of the loop for us */
93035       }
93036       break;
93037     }
93038 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
93039 
93040     /* Send the data to the callback function or to a subroutine.  In the
93041     ** case of a subroutine, the subroutine itself is responsible for
93042     ** popping the data from the stack.
93043     */
93044     case SRT_Coroutine:
93045     case SRT_Output: {
93046       testcase( eDest==SRT_Coroutine );
93047       testcase( eDest==SRT_Output );
93048       if( pOrderBy ){
93049         int r1 = sqlite3GetTempReg(pParse);
93050         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
93051         pushOntoSorter(pParse, pOrderBy, p, r1);
93052         sqlite3ReleaseTempReg(pParse, r1);
93053       }else if( eDest==SRT_Coroutine ){
93054         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
93055       }else{
93056         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
93057         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
93058       }
93059       break;
93060     }
93061 
93062 #if !defined(SQLITE_OMIT_TRIGGER)
93063     /* Discard the results.  This is used for SELECT statements inside
93064     ** the body of a TRIGGER.  The purpose of such selects is to call
93065     ** user-defined functions that have side effects.  We do not care
93066     ** about the actual results of the select.
93067     */
93068     default: {
93069       assert( eDest==SRT_Discard );
93070       break;
93071     }
93072 #endif
93073   }
93074 
93075   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
93076   ** there is a sorter, in which case the sorter has already limited
93077   ** the output for us.
93078   */
93079   if( pOrderBy==0 && p->iLimit ){
93080     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
93081   }
93082 }
93083 
93084 /*
93085 ** Given an expression list, generate a KeyInfo structure that records
93086 ** the collating sequence for each expression in that expression list.
93087 **
93088 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
93089 ** KeyInfo structure is appropriate for initializing a virtual index to
93090 ** implement that clause.  If the ExprList is the result set of a SELECT
93091 ** then the KeyInfo structure is appropriate for initializing a virtual
93092 ** index to implement a DISTINCT test.
93093 **
93094 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
93095 ** function is responsible for seeing that this structure is eventually
93096 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
93097 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
93098 */
93099 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
93100   sqlite3 *db = pParse->db;
93101   int nExpr;
93102   KeyInfo *pInfo;
93103   struct ExprList_item *pItem;
93104   int i;
93105 
93106   nExpr = pList->nExpr;
93107   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
93108   if( pInfo ){
93109     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
93110     pInfo->nField = (u16)nExpr;
93111     pInfo->enc = ENC(db);
93112     pInfo->db = db;
93113     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
93114       CollSeq *pColl;
93115       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
93116       if( !pColl ){
93117         pColl = db->pDfltColl;
93118       }
93119       pInfo->aColl[i] = pColl;
93120       pInfo->aSortOrder[i] = pItem->sortOrder;
93121     }
93122   }
93123   return pInfo;
93124 }
93125 
93126 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93127 /*
93128 ** Name of the connection operator, used for error messages.
93129 */
93130 static const char *selectOpName(int id){
93131   char *z;
93132   switch( id ){
93133     case TK_ALL:       z = "UNION ALL";   break;
93134     case TK_INTERSECT: z = "INTERSECT";   break;
93135     case TK_EXCEPT:    z = "EXCEPT";      break;
93136     default:           z = "UNION";       break;
93137   }
93138   return z;
93139 }
93140 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
93141 
93142 #ifndef SQLITE_OMIT_EXPLAIN
93143 /*
93144 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
93145 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
93146 ** where the caption is of the form:
93147 **
93148 **   "USE TEMP B-TREE FOR xxx"
93149 **
93150 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
93151 ** is determined by the zUsage argument.
93152 */
93153 static void explainTempTable(Parse *pParse, const char *zUsage){
93154   if( pParse->explain==2 ){
93155     Vdbe *v = pParse->pVdbe;
93156     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
93157     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
93158   }
93159 }
93160 
93161 /*
93162 ** Assign expression b to lvalue a. A second, no-op, version of this macro
93163 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
93164 ** in sqlite3Select() to assign values to structure member variables that
93165 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
93166 ** code with #ifndef directives.
93167 */
93168 # define explainSetInteger(a, b) a = b
93169 
93170 #else
93171 /* No-op versions of the explainXXX() functions and macros. */
93172 # define explainTempTable(y,z)
93173 # define explainSetInteger(y,z)
93174 #endif
93175 
93176 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
93177 /*
93178 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
93179 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
93180 ** where the caption is of one of the two forms:
93181 **
93182 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
93183 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
93184 **
93185 ** where iSub1 and iSub2 are the integers passed as the corresponding
93186 ** function parameters, and op is the text representation of the parameter
93187 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
93188 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
93189 ** false, or the second form if it is true.
93190 */
93191 static void explainComposite(
93192   Parse *pParse,                  /* Parse context */
93193   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
93194   int iSub1,                      /* Subquery id 1 */
93195   int iSub2,                      /* Subquery id 2 */
93196   int bUseTmp                     /* True if a temp table was used */
93197 ){
93198   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
93199   if( pParse->explain==2 ){
93200     Vdbe *v = pParse->pVdbe;
93201     char *zMsg = sqlite3MPrintf(
93202         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
93203         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
93204     );
93205     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
93206   }
93207 }
93208 #else
93209 /* No-op versions of the explainXXX() functions and macros. */
93210 # define explainComposite(v,w,x,y,z)
93211 #endif
93212 
93213 /*
93214 ** If the inner loop was generated using a non-null pOrderBy argument,
93215 ** then the results were placed in a sorter.  After the loop is terminated
93216 ** we need to run the sorter and output the results.  The following
93217 ** routine generates the code needed to do that.
93218 */
93219 static void generateSortTail(
93220   Parse *pParse,    /* Parsing context */
93221   Select *p,        /* The SELECT statement */
93222   Vdbe *v,          /* Generate code into this VDBE */
93223   int nColumn,      /* Number of columns of data */
93224   SelectDest *pDest /* Write the sorted results here */
93225 ){
93226   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
93227   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
93228   int addr;
93229   int iTab;
93230   int pseudoTab = 0;
93231   ExprList *pOrderBy = p->pOrderBy;
93232 
93233   int eDest = pDest->eDest;
93234   int iParm = pDest->iParm;
93235 
93236   int regRow;
93237   int regRowid;
93238 
93239   iTab = pOrderBy->iECursor;
93240   regRow = sqlite3GetTempReg(pParse);
93241   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
93242     pseudoTab = pParse->nTab++;
93243     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
93244     regRowid = 0;
93245   }else{
93246     regRowid = sqlite3GetTempReg(pParse);
93247   }
93248   if( p->selFlags & SF_UseSorter ){
93249     int regSortOut = ++pParse->nMem;
93250     int ptab2 = pParse->nTab++;
93251     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
93252     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
93253     codeOffset(v, p, addrContinue);
93254     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
93255     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
93256     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
93257   }else{
93258     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
93259     codeOffset(v, p, addrContinue);
93260     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
93261   }
93262   switch( eDest ){
93263     case SRT_Table:
93264     case SRT_EphemTab: {
93265       testcase( eDest==SRT_Table );
93266       testcase( eDest==SRT_EphemTab );
93267       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
93268       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
93269       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
93270       break;
93271     }
93272 #ifndef SQLITE_OMIT_SUBQUERY
93273     case SRT_Set: {
93274       assert( nColumn==1 );
93275       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
93276       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
93277       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
93278       break;
93279     }
93280     case SRT_Mem: {
93281       assert( nColumn==1 );
93282       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
93283       /* The LIMIT clause will terminate the loop for us */
93284       break;
93285     }
93286 #endif
93287     default: {
93288       int i;
93289       assert( eDest==SRT_Output || eDest==SRT_Coroutine );
93290       testcase( eDest==SRT_Output );
93291       testcase( eDest==SRT_Coroutine );
93292       for(i=0; i<nColumn; i++){
93293         assert( regRow!=pDest->iMem+i );
93294         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
93295         if( i==0 ){
93296           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
93297         }
93298       }
93299       if( eDest==SRT_Output ){
93300         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
93301         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
93302       }else{
93303         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
93304       }
93305       break;
93306     }
93307   }
93308   sqlite3ReleaseTempReg(pParse, regRow);
93309   sqlite3ReleaseTempReg(pParse, regRowid);
93310 
93311   /* The bottom of the loop
93312   */
93313   sqlite3VdbeResolveLabel(v, addrContinue);
93314   if( p->selFlags & SF_UseSorter ){
93315     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
93316   }else{
93317     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
93318   }
93319   sqlite3VdbeResolveLabel(v, addrBreak);
93320   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
93321     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
93322   }
93323 }
93324 
93325 /*
93326 ** Return a pointer to a string containing the 'declaration type' of the
93327 ** expression pExpr. The string may be treated as static by the caller.
93328 **
93329 ** The declaration type is the exact datatype definition extracted from the
93330 ** original CREATE TABLE statement if the expression is a column. The
93331 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
93332 ** is considered a column can be complex in the presence of subqueries. The
93333 ** result-set expression in all of the following SELECT statements is
93334 ** considered a column by this function.
93335 **
93336 **   SELECT col FROM tbl;
93337 **   SELECT (SELECT col FROM tbl;
93338 **   SELECT (SELECT col FROM tbl);
93339 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
93340 **
93341 ** The declaration type for any expression other than a column is NULL.
93342 */
93343 static const char *columnType(
93344   NameContext *pNC,
93345   Expr *pExpr,
93346   const char **pzOriginDb,
93347   const char **pzOriginTab,
93348   const char **pzOriginCol
93349 ){
93350   char const *zType = 0;
93351   char const *zOriginDb = 0;
93352   char const *zOriginTab = 0;
93353   char const *zOriginCol = 0;
93354   int j;
93355   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
93356 
93357   switch( pExpr->op ){
93358     case TK_AGG_COLUMN:
93359     case TK_COLUMN: {
93360       /* The expression is a column. Locate the table the column is being
93361       ** extracted from in NameContext.pSrcList. This table may be real
93362       ** database table or a subquery.
93363       */
93364       Table *pTab = 0;            /* Table structure column is extracted from */
93365       Select *pS = 0;             /* Select the column is extracted from */
93366       int iCol = pExpr->iColumn;  /* Index of column in pTab */
93367       testcase( pExpr->op==TK_AGG_COLUMN );
93368       testcase( pExpr->op==TK_COLUMN );
93369       while( pNC && !pTab ){
93370         SrcList *pTabList = pNC->pSrcList;
93371         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
93372         if( j<pTabList->nSrc ){
93373           pTab = pTabList->a[j].pTab;
93374           pS = pTabList->a[j].pSelect;
93375         }else{
93376           pNC = pNC->pNext;
93377         }
93378       }
93379 
93380       if( pTab==0 ){
93381         /* At one time, code such as "SELECT new.x" within a trigger would
93382         ** cause this condition to run.  Since then, we have restructured how
93383         ** trigger code is generated and so this condition is no longer
93384         ** possible. However, it can still be true for statements like
93385         ** the following:
93386         **
93387         **   CREATE TABLE t1(col INTEGER);
93388         **   SELECT (SELECT t1.col) FROM FROM t1;
93389         **
93390         ** when columnType() is called on the expression "t1.col" in the
93391         ** sub-select. In this case, set the column type to NULL, even
93392         ** though it should really be "INTEGER".
93393         **
93394         ** This is not a problem, as the column type of "t1.col" is never
93395         ** used. When columnType() is called on the expression
93396         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
93397         ** branch below.  */
93398         break;
93399       }
93400 
93401       assert( pTab && pExpr->pTab==pTab );
93402       if( pS ){
93403         /* The "table" is actually a sub-select or a view in the FROM clause
93404         ** of the SELECT statement. Return the declaration type and origin
93405         ** data for the result-set column of the sub-select.
93406         */
93407         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
93408           /* If iCol is less than zero, then the expression requests the
93409           ** rowid of the sub-select or view. This expression is legal (see
93410           ** test case misc2.2.2) - it always evaluates to NULL.
93411           */
93412           NameContext sNC;
93413           Expr *p = pS->pEList->a[iCol].pExpr;
93414           sNC.pSrcList = pS->pSrc;
93415           sNC.pNext = pNC;
93416           sNC.pParse = pNC->pParse;
93417           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
93418         }
93419       }else if( ALWAYS(pTab->pSchema) ){
93420         /* A real table */
93421         assert( !pS );
93422         if( iCol<0 ) iCol = pTab->iPKey;
93423         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
93424         if( iCol<0 ){
93425           zType = "INTEGER";
93426           zOriginCol = "rowid";
93427         }else{
93428           zType = pTab->aCol[iCol].zType;
93429           zOriginCol = pTab->aCol[iCol].zName;
93430         }
93431         zOriginTab = pTab->zName;
93432         if( pNC->pParse ){
93433           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
93434           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
93435         }
93436       }
93437       break;
93438     }
93439 #ifndef SQLITE_OMIT_SUBQUERY
93440     case TK_SELECT: {
93441       /* The expression is a sub-select. Return the declaration type and
93442       ** origin info for the single column in the result set of the SELECT
93443       ** statement.
93444       */
93445       NameContext sNC;
93446       Select *pS = pExpr->x.pSelect;
93447       Expr *p = pS->pEList->a[0].pExpr;
93448       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
93449       sNC.pSrcList = pS->pSrc;
93450       sNC.pNext = pNC;
93451       sNC.pParse = pNC->pParse;
93452       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
93453       break;
93454     }
93455 #endif
93456   }
93457 
93458   if( pzOriginDb ){
93459     assert( pzOriginTab && pzOriginCol );
93460     *pzOriginDb = zOriginDb;
93461     *pzOriginTab = zOriginTab;
93462     *pzOriginCol = zOriginCol;
93463   }
93464   return zType;
93465 }
93466 
93467 /*
93468 ** Generate code that will tell the VDBE the declaration types of columns
93469 ** in the result set.
93470 */
93471 static void generateColumnTypes(
93472   Parse *pParse,      /* Parser context */
93473   SrcList *pTabList,  /* List of tables */
93474   ExprList *pEList    /* Expressions defining the result set */
93475 ){
93476 #ifndef SQLITE_OMIT_DECLTYPE
93477   Vdbe *v = pParse->pVdbe;
93478   int i;
93479   NameContext sNC;
93480   sNC.pSrcList = pTabList;
93481   sNC.pParse = pParse;
93482   for(i=0; i<pEList->nExpr; i++){
93483     Expr *p = pEList->a[i].pExpr;
93484     const char *zType;
93485 #ifdef SQLITE_ENABLE_COLUMN_METADATA
93486     const char *zOrigDb = 0;
93487     const char *zOrigTab = 0;
93488     const char *zOrigCol = 0;
93489     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
93490 
93491     /* The vdbe must make its own copy of the column-type and other
93492     ** column specific strings, in case the schema is reset before this
93493     ** virtual machine is deleted.
93494     */
93495     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
93496     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
93497     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
93498 #else
93499     zType = columnType(&sNC, p, 0, 0, 0);
93500 #endif
93501     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
93502   }
93503 #endif /* SQLITE_OMIT_DECLTYPE */
93504 }
93505 
93506 /*
93507 ** Generate code that will tell the VDBE the names of columns
93508 ** in the result set.  This information is used to provide the
93509 ** azCol[] values in the callback.
93510 */
93511 static void generateColumnNames(
93512   Parse *pParse,      /* Parser context */
93513   SrcList *pTabList,  /* List of tables */
93514   ExprList *pEList    /* Expressions defining the result set */
93515 ){
93516   Vdbe *v = pParse->pVdbe;
93517   int i, j;
93518   sqlite3 *db = pParse->db;
93519   int fullNames, shortNames;
93520 
93521 #ifndef SQLITE_OMIT_EXPLAIN
93522   /* If this is an EXPLAIN, skip this step */
93523   if( pParse->explain ){
93524     return;
93525   }
93526 #endif
93527 
93528   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
93529   pParse->colNamesSet = 1;
93530   fullNames = (db->flags & SQLITE_FullColNames)!=0;
93531   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
93532   sqlite3VdbeSetNumCols(v, pEList->nExpr);
93533   for(i=0; i<pEList->nExpr; i++){
93534     Expr *p;
93535     p = pEList->a[i].pExpr;
93536     if( NEVER(p==0) ) continue;
93537     if( pEList->a[i].zName ){
93538       char *zName = pEList->a[i].zName;
93539       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
93540     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
93541       Table *pTab;
93542       char *zCol;
93543       int iCol = p->iColumn;
93544       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
93545         if( pTabList->a[j].iCursor==p->iTable ) break;
93546       }
93547       assert( j<pTabList->nSrc );
93548       pTab = pTabList->a[j].pTab;
93549       if( iCol<0 ) iCol = pTab->iPKey;
93550       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
93551       if( iCol<0 ){
93552         zCol = "rowid";
93553       }else{
93554         zCol = pTab->aCol[iCol].zName;
93555       }
93556       if( !shortNames && !fullNames ){
93557         sqlite3VdbeSetColName(v, i, COLNAME_NAME,
93558             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
93559       }else if( fullNames ){
93560         char *zName = 0;
93561         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
93562         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
93563       }else{
93564         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
93565       }
93566     }else{
93567       sqlite3VdbeSetColName(v, i, COLNAME_NAME,
93568           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
93569     }
93570   }
93571   generateColumnTypes(pParse, pTabList, pEList);
93572 }
93573 
93574 /*
93575 ** Given a an expression list (which is really the list of expressions
93576 ** that form the result set of a SELECT statement) compute appropriate
93577 ** column names for a table that would hold the expression list.
93578 **
93579 ** All column names will be unique.
93580 **
93581 ** Only the column names are computed.  Column.zType, Column.zColl,
93582 ** and other fields of Column are zeroed.
93583 **
93584 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
93585 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
93586 */
93587 static int selectColumnsFromExprList(
93588   Parse *pParse,          /* Parsing context */
93589   ExprList *pEList,       /* Expr list from which to derive column names */
93590   int *pnCol,             /* Write the number of columns here */
93591   Column **paCol          /* Write the new column list here */
93592 ){
93593   sqlite3 *db = pParse->db;   /* Database connection */
93594   int i, j;                   /* Loop counters */
93595   int cnt;                    /* Index added to make the name unique */
93596   Column *aCol, *pCol;        /* For looping over result columns */
93597   int nCol;                   /* Number of columns in the result set */
93598   Expr *p;                    /* Expression for a single result column */
93599   char *zName;                /* Column name */
93600   int nName;                  /* Size of name in zName[] */
93601 
93602   *pnCol = nCol = pEList->nExpr;
93603   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
93604   if( aCol==0 ) return SQLITE_NOMEM;
93605   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
93606     /* Get an appropriate name for the column
93607     */
93608     p = pEList->a[i].pExpr;
93609     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
93610                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
93611     if( (zName = pEList->a[i].zName)!=0 ){
93612       /* If the column contains an "AS <name>" phrase, use <name> as the name */
93613       zName = sqlite3DbStrDup(db, zName);
93614     }else{
93615       Expr *pColExpr = p;  /* The expression that is the result column name */
93616       Table *pTab;         /* Table associated with this expression */
93617       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
93618       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
93619         /* For columns use the column name name */
93620         int iCol = pColExpr->iColumn;
93621         pTab = pColExpr->pTab;
93622         if( iCol<0 ) iCol = pTab->iPKey;
93623         zName = sqlite3MPrintf(db, "%s",
93624                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
93625       }else if( pColExpr->op==TK_ID ){
93626         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
93627         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
93628       }else{
93629         /* Use the original text of the column expression as its name */
93630         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
93631       }
93632     }
93633     if( db->mallocFailed ){
93634       sqlite3DbFree(db, zName);
93635       break;
93636     }
93637 
93638     /* Make sure the column name is unique.  If the name is not unique,
93639     ** append a integer to the name so that it becomes unique.
93640     */
93641     nName = sqlite3Strlen30(zName);
93642     for(j=cnt=0; j<i; j++){
93643       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
93644         char *zNewName;
93645         zName[nName] = 0;
93646         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
93647         sqlite3DbFree(db, zName);
93648         zName = zNewName;
93649         j = -1;
93650         if( zName==0 ) break;
93651       }
93652     }
93653     pCol->zName = zName;
93654   }
93655   if( db->mallocFailed ){
93656     for(j=0; j<i; j++){
93657       sqlite3DbFree(db, aCol[j].zName);
93658     }
93659     sqlite3DbFree(db, aCol);
93660     *paCol = 0;
93661     *pnCol = 0;
93662     return SQLITE_NOMEM;
93663   }
93664   return SQLITE_OK;
93665 }
93666 
93667 /*
93668 ** Add type and collation information to a column list based on
93669 ** a SELECT statement.
93670 **
93671 ** The column list presumably came from selectColumnNamesFromExprList().
93672 ** The column list has only names, not types or collations.  This
93673 ** routine goes through and adds the types and collations.
93674 **
93675 ** This routine requires that all identifiers in the SELECT
93676 ** statement be resolved.
93677 */
93678 static void selectAddColumnTypeAndCollation(
93679   Parse *pParse,        /* Parsing contexts */
93680   int nCol,             /* Number of columns */
93681   Column *aCol,         /* List of columns */
93682   Select *pSelect       /* SELECT used to determine types and collations */
93683 ){
93684   sqlite3 *db = pParse->db;
93685   NameContext sNC;
93686   Column *pCol;
93687   CollSeq *pColl;
93688   int i;
93689   Expr *p;
93690   struct ExprList_item *a;
93691 
93692   assert( pSelect!=0 );
93693   assert( (pSelect->selFlags & SF_Resolved)!=0 );
93694   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
93695   if( db->mallocFailed ) return;
93696   memset(&sNC, 0, sizeof(sNC));
93697   sNC.pSrcList = pSelect->pSrc;
93698   a = pSelect->pEList->a;
93699   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
93700     p = a[i].pExpr;
93701     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
93702     pCol->affinity = sqlite3ExprAffinity(p);
93703     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
93704     pColl = sqlite3ExprCollSeq(pParse, p);
93705     if( pColl ){
93706       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
93707     }
93708   }
93709 }
93710 
93711 /*
93712 ** Given a SELECT statement, generate a Table structure that describes
93713 ** the result set of that SELECT.
93714 */
93715 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
93716   Table *pTab;
93717   sqlite3 *db = pParse->db;
93718   int savedFlags;
93719 
93720   savedFlags = db->flags;
93721   db->flags &= ~SQLITE_FullColNames;
93722   db->flags |= SQLITE_ShortColNames;
93723   sqlite3SelectPrep(pParse, pSelect, 0);
93724   if( pParse->nErr ) return 0;
93725   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
93726   db->flags = savedFlags;
93727   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
93728   if( pTab==0 ){
93729     return 0;
93730   }
93731   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
93732   ** is disabled */
93733   assert( db->lookaside.bEnabled==0 );
93734   pTab->nRef = 1;
93735   pTab->zName = 0;
93736   pTab->nRowEst = 1000000;
93737   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
93738   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
93739   pTab->iPKey = -1;
93740   if( db->mallocFailed ){
93741     sqlite3DeleteTable(db, pTab);
93742     return 0;
93743   }
93744   return pTab;
93745 }
93746 
93747 /*
93748 ** Get a VDBE for the given parser context.  Create a new one if necessary.
93749 ** If an error occurs, return NULL and leave a message in pParse.
93750 */
93751 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
93752   Vdbe *v = pParse->pVdbe;
93753   if( v==0 ){
93754     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
93755 #ifndef SQLITE_OMIT_TRACE
93756     if( v ){
93757       sqlite3VdbeAddOp0(v, OP_Trace);
93758     }
93759 #endif
93760   }
93761   return v;
93762 }
93763 
93764 
93765 /*
93766 ** Compute the iLimit and iOffset fields of the SELECT based on the
93767 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
93768 ** that appear in the original SQL statement after the LIMIT and OFFSET
93769 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
93770 ** are the integer memory register numbers for counters used to compute
93771 ** the limit and offset.  If there is no limit and/or offset, then
93772 ** iLimit and iOffset are negative.
93773 **
93774 ** This routine changes the values of iLimit and iOffset only if
93775 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
93776 ** iOffset should have been preset to appropriate default values
93777 ** (usually but not always -1) prior to calling this routine.
93778 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
93779 ** redefined.  The UNION ALL operator uses this property to force
93780 ** the reuse of the same limit and offset registers across multiple
93781 ** SELECT statements.
93782 */
93783 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
93784   Vdbe *v = 0;
93785   int iLimit = 0;
93786   int iOffset;
93787   int addr1, n;
93788   if( p->iLimit ) return;
93789 
93790   /*
93791   ** "LIMIT -1" always shows all rows.  There is some
93792   ** contraversy about what the correct behavior should be.
93793   ** The current implementation interprets "LIMIT 0" to mean
93794   ** no rows.
93795   */
93796   sqlite3ExprCacheClear(pParse);
93797   assert( p->pOffset==0 || p->pLimit!=0 );
93798   if( p->pLimit ){
93799     p->iLimit = iLimit = ++pParse->nMem;
93800     v = sqlite3GetVdbe(pParse);
93801     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
93802     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
93803       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
93804       VdbeComment((v, "LIMIT counter"));
93805       if( n==0 ){
93806         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
93807       }else{
93808         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
93809       }
93810     }else{
93811       sqlite3ExprCode(pParse, p->pLimit, iLimit);
93812       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
93813       VdbeComment((v, "LIMIT counter"));
93814       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
93815     }
93816     if( p->pOffset ){
93817       p->iOffset = iOffset = ++pParse->nMem;
93818       pParse->nMem++;   /* Allocate an extra register for limit+offset */
93819       sqlite3ExprCode(pParse, p->pOffset, iOffset);
93820       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
93821       VdbeComment((v, "OFFSET counter"));
93822       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
93823       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
93824       sqlite3VdbeJumpHere(v, addr1);
93825       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
93826       VdbeComment((v, "LIMIT+OFFSET"));
93827       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
93828       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
93829       sqlite3VdbeJumpHere(v, addr1);
93830     }
93831   }
93832 }
93833 
93834 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93835 /*
93836 ** Return the appropriate collating sequence for the iCol-th column of
93837 ** the result set for the compound-select statement "p".  Return NULL if
93838 ** the column has no default collating sequence.
93839 **
93840 ** The collating sequence for the compound select is taken from the
93841 ** left-most term of the select that has a collating sequence.
93842 */
93843 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
93844   CollSeq *pRet;
93845   if( p->pPrior ){
93846     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
93847   }else{
93848     pRet = 0;
93849   }
93850   assert( iCol>=0 );
93851   if( pRet==0 && iCol<p->pEList->nExpr ){
93852     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
93853   }
93854   return pRet;
93855 }
93856 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
93857 
93858 /* Forward reference */
93859 static int multiSelectOrderBy(
93860   Parse *pParse,        /* Parsing context */
93861   Select *p,            /* The right-most of SELECTs to be coded */
93862   SelectDest *pDest     /* What to do with query results */
93863 );
93864 
93865 
93866 #ifndef SQLITE_OMIT_COMPOUND_SELECT
93867 /*
93868 ** This routine is called to process a compound query form from
93869 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
93870 ** INTERSECT
93871 **
93872 ** "p" points to the right-most of the two queries.  the query on the
93873 ** left is p->pPrior.  The left query could also be a compound query
93874 ** in which case this routine will be called recursively.
93875 **
93876 ** The results of the total query are to be written into a destination
93877 ** of type eDest with parameter iParm.
93878 **
93879 ** Example 1:  Consider a three-way compound SQL statement.
93880 **
93881 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
93882 **
93883 ** This statement is parsed up as follows:
93884 **
93885 **     SELECT c FROM t3
93886 **      |
93887 **      `----->  SELECT b FROM t2
93888 **                |
93889 **                `------>  SELECT a FROM t1
93890 **
93891 ** The arrows in the diagram above represent the Select.pPrior pointer.
93892 ** So if this routine is called with p equal to the t3 query, then
93893 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
93894 **
93895 ** Notice that because of the way SQLite parses compound SELECTs, the
93896 ** individual selects always group from left to right.
93897 */
93898 static int multiSelect(
93899   Parse *pParse,        /* Parsing context */
93900   Select *p,            /* The right-most of SELECTs to be coded */
93901   SelectDest *pDest     /* What to do with query results */
93902 ){
93903   int rc = SQLITE_OK;   /* Success code from a subroutine */
93904   Select *pPrior;       /* Another SELECT immediately to our left */
93905   Vdbe *v;              /* Generate code to this VDBE */
93906   SelectDest dest;      /* Alternative data destination */
93907   Select *pDelete = 0;  /* Chain of simple selects to delete */
93908   sqlite3 *db;          /* Database connection */
93909 #ifndef SQLITE_OMIT_EXPLAIN
93910   int iSub1;            /* EQP id of left-hand query */
93911   int iSub2;            /* EQP id of right-hand query */
93912 #endif
93913 
93914   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
93915   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
93916   */
93917   assert( p && p->pPrior );  /* Calling function guarantees this much */
93918   db = pParse->db;
93919   pPrior = p->pPrior;
93920   assert( pPrior->pRightmost!=pPrior );
93921   assert( pPrior->pRightmost==p->pRightmost );
93922   dest = *pDest;
93923   if( pPrior->pOrderBy ){
93924     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
93925       selectOpName(p->op));
93926     rc = 1;
93927     goto multi_select_end;
93928   }
93929   if( pPrior->pLimit ){
93930     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
93931       selectOpName(p->op));
93932     rc = 1;
93933     goto multi_select_end;
93934   }
93935 
93936   v = sqlite3GetVdbe(pParse);
93937   assert( v!=0 );  /* The VDBE already created by calling function */
93938 
93939   /* Create the destination temporary table if necessary
93940   */
93941   if( dest.eDest==SRT_EphemTab ){
93942     assert( p->pEList );
93943     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
93944     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
93945     dest.eDest = SRT_Table;
93946   }
93947 
93948   /* Make sure all SELECTs in the statement have the same number of elements
93949   ** in their result sets.
93950   */
93951   assert( p->pEList && pPrior->pEList );
93952   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
93953     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
93954       " do not have the same number of result columns", selectOpName(p->op));
93955     rc = 1;
93956     goto multi_select_end;
93957   }
93958 
93959   /* Compound SELECTs that have an ORDER BY clause are handled separately.
93960   */
93961   if( p->pOrderBy ){
93962     return multiSelectOrderBy(pParse, p, pDest);
93963   }
93964 
93965   /* Generate code for the left and right SELECT statements.
93966   */
93967   switch( p->op ){
93968     case TK_ALL: {
93969       int addr = 0;
93970       int nLimit;
93971       assert( !pPrior->pLimit );
93972       pPrior->pLimit = p->pLimit;
93973       pPrior->pOffset = p->pOffset;
93974       explainSetInteger(iSub1, pParse->iNextSelectId);
93975       rc = sqlite3Select(pParse, pPrior, &dest);
93976       p->pLimit = 0;
93977       p->pOffset = 0;
93978       if( rc ){
93979         goto multi_select_end;
93980       }
93981       p->pPrior = 0;
93982       p->iLimit = pPrior->iLimit;
93983       p->iOffset = pPrior->iOffset;
93984       if( p->iLimit ){
93985         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
93986         VdbeComment((v, "Jump ahead if LIMIT reached"));
93987       }
93988       explainSetInteger(iSub2, pParse->iNextSelectId);
93989       rc = sqlite3Select(pParse, p, &dest);
93990       testcase( rc!=SQLITE_OK );
93991       pDelete = p->pPrior;
93992       p->pPrior = pPrior;
93993       p->nSelectRow += pPrior->nSelectRow;
93994       if( pPrior->pLimit
93995        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
93996        && p->nSelectRow > (double)nLimit
93997       ){
93998         p->nSelectRow = (double)nLimit;
93999       }
94000       if( addr ){
94001         sqlite3VdbeJumpHere(v, addr);
94002       }
94003       break;
94004     }
94005     case TK_EXCEPT:
94006     case TK_UNION: {
94007       int unionTab;    /* Cursor number of the temporary table holding result */
94008       u8 op = 0;       /* One of the SRT_ operations to apply to self */
94009       int priorOp;     /* The SRT_ operation to apply to prior selects */
94010       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
94011       int addr;
94012       SelectDest uniondest;
94013 
94014       testcase( p->op==TK_EXCEPT );
94015       testcase( p->op==TK_UNION );
94016       priorOp = SRT_Union;
94017       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
94018         /* We can reuse a temporary table generated by a SELECT to our
94019         ** right.
94020         */
94021         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
94022                                      ** of a 3-way or more compound */
94023         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
94024         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
94025         unionTab = dest.iParm;
94026       }else{
94027         /* We will need to create our own temporary table to hold the
94028         ** intermediate results.
94029         */
94030         unionTab = pParse->nTab++;
94031         assert( p->pOrderBy==0 );
94032         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
94033         assert( p->addrOpenEphm[0] == -1 );
94034         p->addrOpenEphm[0] = addr;
94035         p->pRightmost->selFlags |= SF_UsesEphemeral;
94036         assert( p->pEList );
94037       }
94038 
94039       /* Code the SELECT statements to our left
94040       */
94041       assert( !pPrior->pOrderBy );
94042       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
94043       explainSetInteger(iSub1, pParse->iNextSelectId);
94044       rc = sqlite3Select(pParse, pPrior, &uniondest);
94045       if( rc ){
94046         goto multi_select_end;
94047       }
94048 
94049       /* Code the current SELECT statement
94050       */
94051       if( p->op==TK_EXCEPT ){
94052         op = SRT_Except;
94053       }else{
94054         assert( p->op==TK_UNION );
94055         op = SRT_Union;
94056       }
94057       p->pPrior = 0;
94058       pLimit = p->pLimit;
94059       p->pLimit = 0;
94060       pOffset = p->pOffset;
94061       p->pOffset = 0;
94062       uniondest.eDest = op;
94063       explainSetInteger(iSub2, pParse->iNextSelectId);
94064       rc = sqlite3Select(pParse, p, &uniondest);
94065       testcase( rc!=SQLITE_OK );
94066       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
94067       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
94068       sqlite3ExprListDelete(db, p->pOrderBy);
94069       pDelete = p->pPrior;
94070       p->pPrior = pPrior;
94071       p->pOrderBy = 0;
94072       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
94073       sqlite3ExprDelete(db, p->pLimit);
94074       p->pLimit = pLimit;
94075       p->pOffset = pOffset;
94076       p->iLimit = 0;
94077       p->iOffset = 0;
94078 
94079       /* Convert the data in the temporary table into whatever form
94080       ** it is that we currently need.
94081       */
94082       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
94083       if( dest.eDest!=priorOp ){
94084         int iCont, iBreak, iStart;
94085         assert( p->pEList );
94086         if( dest.eDest==SRT_Output ){
94087           Select *pFirst = p;
94088           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
94089           generateColumnNames(pParse, 0, pFirst->pEList);
94090         }
94091         iBreak = sqlite3VdbeMakeLabel(v);
94092         iCont = sqlite3VdbeMakeLabel(v);
94093         computeLimitRegisters(pParse, p, iBreak);
94094         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
94095         iStart = sqlite3VdbeCurrentAddr(v);
94096         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
94097                         0, -1, &dest, iCont, iBreak);
94098         sqlite3VdbeResolveLabel(v, iCont);
94099         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
94100         sqlite3VdbeResolveLabel(v, iBreak);
94101         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
94102       }
94103       break;
94104     }
94105     default: assert( p->op==TK_INTERSECT ); {
94106       int tab1, tab2;
94107       int iCont, iBreak, iStart;
94108       Expr *pLimit, *pOffset;
94109       int addr;
94110       SelectDest intersectdest;
94111       int r1;
94112 
94113       /* INTERSECT is different from the others since it requires
94114       ** two temporary tables.  Hence it has its own case.  Begin
94115       ** by allocating the tables we will need.
94116       */
94117       tab1 = pParse->nTab++;
94118       tab2 = pParse->nTab++;
94119       assert( p->pOrderBy==0 );
94120 
94121       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
94122       assert( p->addrOpenEphm[0] == -1 );
94123       p->addrOpenEphm[0] = addr;
94124       p->pRightmost->selFlags |= SF_UsesEphemeral;
94125       assert( p->pEList );
94126 
94127       /* Code the SELECTs to our left into temporary table "tab1".
94128       */
94129       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
94130       explainSetInteger(iSub1, pParse->iNextSelectId);
94131       rc = sqlite3Select(pParse, pPrior, &intersectdest);
94132       if( rc ){
94133         goto multi_select_end;
94134       }
94135 
94136       /* Code the current SELECT into temporary table "tab2"
94137       */
94138       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
94139       assert( p->addrOpenEphm[1] == -1 );
94140       p->addrOpenEphm[1] = addr;
94141       p->pPrior = 0;
94142       pLimit = p->pLimit;
94143       p->pLimit = 0;
94144       pOffset = p->pOffset;
94145       p->pOffset = 0;
94146       intersectdest.iParm = tab2;
94147       explainSetInteger(iSub2, pParse->iNextSelectId);
94148       rc = sqlite3Select(pParse, p, &intersectdest);
94149       testcase( rc!=SQLITE_OK );
94150       pDelete = p->pPrior;
94151       p->pPrior = pPrior;
94152       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
94153       sqlite3ExprDelete(db, p->pLimit);
94154       p->pLimit = pLimit;
94155       p->pOffset = pOffset;
94156 
94157       /* Generate code to take the intersection of the two temporary
94158       ** tables.
94159       */
94160       assert( p->pEList );
94161       if( dest.eDest==SRT_Output ){
94162         Select *pFirst = p;
94163         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
94164         generateColumnNames(pParse, 0, pFirst->pEList);
94165       }
94166       iBreak = sqlite3VdbeMakeLabel(v);
94167       iCont = sqlite3VdbeMakeLabel(v);
94168       computeLimitRegisters(pParse, p, iBreak);
94169       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
94170       r1 = sqlite3GetTempReg(pParse);
94171       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
94172       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
94173       sqlite3ReleaseTempReg(pParse, r1);
94174       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
94175                       0, -1, &dest, iCont, iBreak);
94176       sqlite3VdbeResolveLabel(v, iCont);
94177       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
94178       sqlite3VdbeResolveLabel(v, iBreak);
94179       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
94180       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
94181       break;
94182     }
94183   }
94184 
94185   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
94186 
94187   /* Compute collating sequences used by
94188   ** temporary tables needed to implement the compound select.
94189   ** Attach the KeyInfo structure to all temporary tables.
94190   **
94191   ** This section is run by the right-most SELECT statement only.
94192   ** SELECT statements to the left always skip this part.  The right-most
94193   ** SELECT might also skip this part if it has no ORDER BY clause and
94194   ** no temp tables are required.
94195   */
94196   if( p->selFlags & SF_UsesEphemeral ){
94197     int i;                        /* Loop counter */
94198     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
94199     Select *pLoop;                /* For looping through SELECT statements */
94200     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
94201     int nCol;                     /* Number of columns in result set */
94202 
94203     assert( p->pRightmost==p );
94204     nCol = p->pEList->nExpr;
94205     pKeyInfo = sqlite3DbMallocZero(db,
94206                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
94207     if( !pKeyInfo ){
94208       rc = SQLITE_NOMEM;
94209       goto multi_select_end;
94210     }
94211 
94212     pKeyInfo->enc = ENC(db);
94213     pKeyInfo->nField = (u16)nCol;
94214 
94215     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
94216       *apColl = multiSelectCollSeq(pParse, p, i);
94217       if( 0==*apColl ){
94218         *apColl = db->pDfltColl;
94219       }
94220     }
94221 
94222     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
94223       for(i=0; i<2; i++){
94224         int addr = pLoop->addrOpenEphm[i];
94225         if( addr<0 ){
94226           /* If [0] is unused then [1] is also unused.  So we can
94227           ** always safely abort as soon as the first unused slot is found */
94228           assert( pLoop->addrOpenEphm[1]<0 );
94229           break;
94230         }
94231         sqlite3VdbeChangeP2(v, addr, nCol);
94232         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
94233         pLoop->addrOpenEphm[i] = -1;
94234       }
94235     }
94236     sqlite3DbFree(db, pKeyInfo);
94237   }
94238 
94239 multi_select_end:
94240   pDest->iMem = dest.iMem;
94241   pDest->nMem = dest.nMem;
94242   sqlite3SelectDelete(db, pDelete);
94243   return rc;
94244 }
94245 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
94246 
94247 /*
94248 ** Code an output subroutine for a coroutine implementation of a
94249 ** SELECT statment.
94250 **
94251 ** The data to be output is contained in pIn->iMem.  There are
94252 ** pIn->nMem columns to be output.  pDest is where the output should
94253 ** be sent.
94254 **
94255 ** regReturn is the number of the register holding the subroutine
94256 ** return address.
94257 **
94258 ** If regPrev>0 then it is the first register in a vector that
94259 ** records the previous output.  mem[regPrev] is a flag that is false
94260 ** if there has been no previous output.  If regPrev>0 then code is
94261 ** generated to suppress duplicates.  pKeyInfo is used for comparing
94262 ** keys.
94263 **
94264 ** If the LIMIT found in p->iLimit is reached, jump immediately to
94265 ** iBreak.
94266 */
94267 static int generateOutputSubroutine(
94268   Parse *pParse,          /* Parsing context */
94269   Select *p,              /* The SELECT statement */
94270   SelectDest *pIn,        /* Coroutine supplying data */
94271   SelectDest *pDest,      /* Where to send the data */
94272   int regReturn,          /* The return address register */
94273   int regPrev,            /* Previous result register.  No uniqueness if 0 */
94274   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
94275   int p4type,             /* The p4 type for pKeyInfo */
94276   int iBreak              /* Jump here if we hit the LIMIT */
94277 ){
94278   Vdbe *v = pParse->pVdbe;
94279   int iContinue;
94280   int addr;
94281 
94282   addr = sqlite3VdbeCurrentAddr(v);
94283   iContinue = sqlite3VdbeMakeLabel(v);
94284 
94285   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
94286   */
94287   if( regPrev ){
94288     int j1, j2;
94289     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
94290     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
94291                               (char*)pKeyInfo, p4type);
94292     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
94293     sqlite3VdbeJumpHere(v, j1);
94294     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
94295     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
94296   }
94297   if( pParse->db->mallocFailed ) return 0;
94298 
94299   /* Suppress the the first OFFSET entries if there is an OFFSET clause
94300   */
94301   codeOffset(v, p, iContinue);
94302 
94303   switch( pDest->eDest ){
94304     /* Store the result as data using a unique key.
94305     */
94306     case SRT_Table:
94307     case SRT_EphemTab: {
94308       int r1 = sqlite3GetTempReg(pParse);
94309       int r2 = sqlite3GetTempReg(pParse);
94310       testcase( pDest->eDest==SRT_Table );
94311       testcase( pDest->eDest==SRT_EphemTab );
94312       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
94313       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
94314       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
94315       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
94316       sqlite3ReleaseTempReg(pParse, r2);
94317       sqlite3ReleaseTempReg(pParse, r1);
94318       break;
94319     }
94320 
94321 #ifndef SQLITE_OMIT_SUBQUERY
94322     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
94323     ** then there should be a single item on the stack.  Write this
94324     ** item into the set table with bogus data.
94325     */
94326     case SRT_Set: {
94327       int r1;
94328       assert( pIn->nMem==1 );
94329       p->affinity =
94330          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
94331       r1 = sqlite3GetTempReg(pParse);
94332       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
94333       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
94334       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
94335       sqlite3ReleaseTempReg(pParse, r1);
94336       break;
94337     }
94338 
94339 #if 0  /* Never occurs on an ORDER BY query */
94340     /* If any row exist in the result set, record that fact and abort.
94341     */
94342     case SRT_Exists: {
94343       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
94344       /* The LIMIT clause will terminate the loop for us */
94345       break;
94346     }
94347 #endif
94348 
94349     /* If this is a scalar select that is part of an expression, then
94350     ** store the results in the appropriate memory cell and break out
94351     ** of the scan loop.
94352     */
94353     case SRT_Mem: {
94354       assert( pIn->nMem==1 );
94355       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
94356       /* The LIMIT clause will jump out of the loop for us */
94357       break;
94358     }
94359 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
94360 
94361     /* The results are stored in a sequence of registers
94362     ** starting at pDest->iMem.  Then the co-routine yields.
94363     */
94364     case SRT_Coroutine: {
94365       if( pDest->iMem==0 ){
94366         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
94367         pDest->nMem = pIn->nMem;
94368       }
94369       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
94370       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
94371       break;
94372     }
94373 
94374     /* If none of the above, then the result destination must be
94375     ** SRT_Output.  This routine is never called with any other
94376     ** destination other than the ones handled above or SRT_Output.
94377     **
94378     ** For SRT_Output, results are stored in a sequence of registers.
94379     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
94380     ** return the next row of result.
94381     */
94382     default: {
94383       assert( pDest->eDest==SRT_Output );
94384       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
94385       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
94386       break;
94387     }
94388   }
94389 
94390   /* Jump to the end of the loop if the LIMIT is reached.
94391   */
94392   if( p->iLimit ){
94393     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
94394   }
94395 
94396   /* Generate the subroutine return
94397   */
94398   sqlite3VdbeResolveLabel(v, iContinue);
94399   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
94400 
94401   return addr;
94402 }
94403 
94404 /*
94405 ** Alternative compound select code generator for cases when there
94406 ** is an ORDER BY clause.
94407 **
94408 ** We assume a query of the following form:
94409 **
94410 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
94411 **
94412 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
94413 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
94414 ** co-routines.  Then run the co-routines in parallel and merge the results
94415 ** into the output.  In addition to the two coroutines (called selectA and
94416 ** selectB) there are 7 subroutines:
94417 **
94418 **    outA:    Move the output of the selectA coroutine into the output
94419 **             of the compound query.
94420 **
94421 **    outB:    Move the output of the selectB coroutine into the output
94422 **             of the compound query.  (Only generated for UNION and
94423 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
94424 **             appears only in B.)
94425 **
94426 **    AltB:    Called when there is data from both coroutines and A<B.
94427 **
94428 **    AeqB:    Called when there is data from both coroutines and A==B.
94429 **
94430 **    AgtB:    Called when there is data from both coroutines and A>B.
94431 **
94432 **    EofA:    Called when data is exhausted from selectA.
94433 **
94434 **    EofB:    Called when data is exhausted from selectB.
94435 **
94436 ** The implementation of the latter five subroutines depend on which
94437 ** <operator> is used:
94438 **
94439 **
94440 **             UNION ALL         UNION            EXCEPT          INTERSECT
94441 **          -------------  -----------------  --------------  -----------------
94442 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
94443 **
94444 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
94445 **
94446 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
94447 **
94448 **   EofA:   outB, nextB      outB, nextB          halt             halt
94449 **
94450 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
94451 **
94452 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
94453 ** causes an immediate jump to EofA and an EOF on B following nextB causes
94454 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
94455 ** following nextX causes a jump to the end of the select processing.
94456 **
94457 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
94458 ** within the output subroutine.  The regPrev register set holds the previously
94459 ** output value.  A comparison is made against this value and the output
94460 ** is skipped if the next results would be the same as the previous.
94461 **
94462 ** The implementation plan is to implement the two coroutines and seven
94463 ** subroutines first, then put the control logic at the bottom.  Like this:
94464 **
94465 **          goto Init
94466 **     coA: coroutine for left query (A)
94467 **     coB: coroutine for right query (B)
94468 **    outA: output one row of A
94469 **    outB: output one row of B (UNION and UNION ALL only)
94470 **    EofA: ...
94471 **    EofB: ...
94472 **    AltB: ...
94473 **    AeqB: ...
94474 **    AgtB: ...
94475 **    Init: initialize coroutine registers
94476 **          yield coA
94477 **          if eof(A) goto EofA
94478 **          yield coB
94479 **          if eof(B) goto EofB
94480 **    Cmpr: Compare A, B
94481 **          Jump AltB, AeqB, AgtB
94482 **     End: ...
94483 **
94484 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
94485 ** actually called using Gosub and they do not Return.  EofA and EofB loop
94486 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
94487 ** and AgtB jump to either L2 or to one of EofA or EofB.
94488 */
94489 #ifndef SQLITE_OMIT_COMPOUND_SELECT
94490 static int multiSelectOrderBy(
94491   Parse *pParse,        /* Parsing context */
94492   Select *p,            /* The right-most of SELECTs to be coded */
94493   SelectDest *pDest     /* What to do with query results */
94494 ){
94495   int i, j;             /* Loop counters */
94496   Select *pPrior;       /* Another SELECT immediately to our left */
94497   Vdbe *v;              /* Generate code to this VDBE */
94498   SelectDest destA;     /* Destination for coroutine A */
94499   SelectDest destB;     /* Destination for coroutine B */
94500   int regAddrA;         /* Address register for select-A coroutine */
94501   int regEofA;          /* Flag to indicate when select-A is complete */
94502   int regAddrB;         /* Address register for select-B coroutine */
94503   int regEofB;          /* Flag to indicate when select-B is complete */
94504   int addrSelectA;      /* Address of the select-A coroutine */
94505   int addrSelectB;      /* Address of the select-B coroutine */
94506   int regOutA;          /* Address register for the output-A subroutine */
94507   int regOutB;          /* Address register for the output-B subroutine */
94508   int addrOutA;         /* Address of the output-A subroutine */
94509   int addrOutB = 0;     /* Address of the output-B subroutine */
94510   int addrEofA;         /* Address of the select-A-exhausted subroutine */
94511   int addrEofB;         /* Address of the select-B-exhausted subroutine */
94512   int addrAltB;         /* Address of the A<B subroutine */
94513   int addrAeqB;         /* Address of the A==B subroutine */
94514   int addrAgtB;         /* Address of the A>B subroutine */
94515   int regLimitA;        /* Limit register for select-A */
94516   int regLimitB;        /* Limit register for select-A */
94517   int regPrev;          /* A range of registers to hold previous output */
94518   int savedLimit;       /* Saved value of p->iLimit */
94519   int savedOffset;      /* Saved value of p->iOffset */
94520   int labelCmpr;        /* Label for the start of the merge algorithm */
94521   int labelEnd;         /* Label for the end of the overall SELECT stmt */
94522   int j1;               /* Jump instructions that get retargetted */
94523   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
94524   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
94525   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
94526   sqlite3 *db;          /* Database connection */
94527   ExprList *pOrderBy;   /* The ORDER BY clause */
94528   int nOrderBy;         /* Number of terms in the ORDER BY clause */
94529   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
94530 #ifndef SQLITE_OMIT_EXPLAIN
94531   int iSub1;            /* EQP id of left-hand query */
94532   int iSub2;            /* EQP id of right-hand query */
94533 #endif
94534 
94535   assert( p->pOrderBy!=0 );
94536   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
94537   db = pParse->db;
94538   v = pParse->pVdbe;
94539   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
94540   labelEnd = sqlite3VdbeMakeLabel(v);
94541   labelCmpr = sqlite3VdbeMakeLabel(v);
94542 
94543 
94544   /* Patch up the ORDER BY clause
94545   */
94546   op = p->op;
94547   pPrior = p->pPrior;
94548   assert( pPrior->pOrderBy==0 );
94549   pOrderBy = p->pOrderBy;
94550   assert( pOrderBy );
94551   nOrderBy = pOrderBy->nExpr;
94552 
94553   /* For operators other than UNION ALL we have to make sure that
94554   ** the ORDER BY clause covers every term of the result set.  Add
94555   ** terms to the ORDER BY clause as necessary.
94556   */
94557   if( op!=TK_ALL ){
94558     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
94559       struct ExprList_item *pItem;
94560       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
94561         assert( pItem->iCol>0 );
94562         if( pItem->iCol==i ) break;
94563       }
94564       if( j==nOrderBy ){
94565         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
94566         if( pNew==0 ) return SQLITE_NOMEM;
94567         pNew->flags |= EP_IntValue;
94568         pNew->u.iValue = i;
94569         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
94570         pOrderBy->a[nOrderBy++].iCol = (u16)i;
94571       }
94572     }
94573   }
94574 
94575   /* Compute the comparison permutation and keyinfo that is used with
94576   ** the permutation used to determine if the next
94577   ** row of results comes from selectA or selectB.  Also add explicit
94578   ** collations to the ORDER BY clause terms so that when the subqueries
94579   ** to the right and the left are evaluated, they use the correct
94580   ** collation.
94581   */
94582   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
94583   if( aPermute ){
94584     struct ExprList_item *pItem;
94585     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
94586       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
94587       aPermute[i] = pItem->iCol - 1;
94588     }
94589     pKeyMerge =
94590       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
94591     if( pKeyMerge ){
94592       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
94593       pKeyMerge->nField = (u16)nOrderBy;
94594       pKeyMerge->enc = ENC(db);
94595       for(i=0; i<nOrderBy; i++){
94596         CollSeq *pColl;
94597         Expr *pTerm = pOrderBy->a[i].pExpr;
94598         if( pTerm->flags & EP_ExpCollate ){
94599           pColl = pTerm->pColl;
94600         }else{
94601           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
94602           pTerm->flags |= EP_ExpCollate;
94603           pTerm->pColl = pColl;
94604         }
94605         pKeyMerge->aColl[i] = pColl;
94606         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
94607       }
94608     }
94609   }else{
94610     pKeyMerge = 0;
94611   }
94612 
94613   /* Reattach the ORDER BY clause to the query.
94614   */
94615   p->pOrderBy = pOrderBy;
94616   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
94617 
94618   /* Allocate a range of temporary registers and the KeyInfo needed
94619   ** for the logic that removes duplicate result rows when the
94620   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
94621   */
94622   if( op==TK_ALL ){
94623     regPrev = 0;
94624   }else{
94625     int nExpr = p->pEList->nExpr;
94626     assert( nOrderBy>=nExpr || db->mallocFailed );
94627     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
94628     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
94629     pKeyDup = sqlite3DbMallocZero(db,
94630                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
94631     if( pKeyDup ){
94632       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
94633       pKeyDup->nField = (u16)nExpr;
94634       pKeyDup->enc = ENC(db);
94635       for(i=0; i<nExpr; i++){
94636         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
94637         pKeyDup->aSortOrder[i] = 0;
94638       }
94639     }
94640   }
94641 
94642   /* Separate the left and the right query from one another
94643   */
94644   p->pPrior = 0;
94645   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
94646   if( pPrior->pPrior==0 ){
94647     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
94648   }
94649 
94650   /* Compute the limit registers */
94651   computeLimitRegisters(pParse, p, labelEnd);
94652   if( p->iLimit && op==TK_ALL ){
94653     regLimitA = ++pParse->nMem;
94654     regLimitB = ++pParse->nMem;
94655     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
94656                                   regLimitA);
94657     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
94658   }else{
94659     regLimitA = regLimitB = 0;
94660   }
94661   sqlite3ExprDelete(db, p->pLimit);
94662   p->pLimit = 0;
94663   sqlite3ExprDelete(db, p->pOffset);
94664   p->pOffset = 0;
94665 
94666   regAddrA = ++pParse->nMem;
94667   regEofA = ++pParse->nMem;
94668   regAddrB = ++pParse->nMem;
94669   regEofB = ++pParse->nMem;
94670   regOutA = ++pParse->nMem;
94671   regOutB = ++pParse->nMem;
94672   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
94673   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
94674 
94675   /* Jump past the various subroutines and coroutines to the main
94676   ** merge loop
94677   */
94678   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
94679   addrSelectA = sqlite3VdbeCurrentAddr(v);
94680 
94681 
94682   /* Generate a coroutine to evaluate the SELECT statement to the
94683   ** left of the compound operator - the "A" select.
94684   */
94685   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
94686   pPrior->iLimit = regLimitA;
94687   explainSetInteger(iSub1, pParse->iNextSelectId);
94688   sqlite3Select(pParse, pPrior, &destA);
94689   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
94690   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
94691   VdbeNoopComment((v, "End coroutine for left SELECT"));
94692 
94693   /* Generate a coroutine to evaluate the SELECT statement on
94694   ** the right - the "B" select
94695   */
94696   addrSelectB = sqlite3VdbeCurrentAddr(v);
94697   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
94698   savedLimit = p->iLimit;
94699   savedOffset = p->iOffset;
94700   p->iLimit = regLimitB;
94701   p->iOffset = 0;
94702   explainSetInteger(iSub2, pParse->iNextSelectId);
94703   sqlite3Select(pParse, p, &destB);
94704   p->iLimit = savedLimit;
94705   p->iOffset = savedOffset;
94706   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
94707   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
94708   VdbeNoopComment((v, "End coroutine for right SELECT"));
94709 
94710   /* Generate a subroutine that outputs the current row of the A
94711   ** select as the next output row of the compound select.
94712   */
94713   VdbeNoopComment((v, "Output routine for A"));
94714   addrOutA = generateOutputSubroutine(pParse,
94715                  p, &destA, pDest, regOutA,
94716                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
94717 
94718   /* Generate a subroutine that outputs the current row of the B
94719   ** select as the next output row of the compound select.
94720   */
94721   if( op==TK_ALL || op==TK_UNION ){
94722     VdbeNoopComment((v, "Output routine for B"));
94723     addrOutB = generateOutputSubroutine(pParse,
94724                  p, &destB, pDest, regOutB,
94725                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
94726   }
94727 
94728   /* Generate a subroutine to run when the results from select A
94729   ** are exhausted and only data in select B remains.
94730   */
94731   VdbeNoopComment((v, "eof-A subroutine"));
94732   if( op==TK_EXCEPT || op==TK_INTERSECT ){
94733     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
94734   }else{
94735     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
94736     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
94737     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
94738     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
94739     p->nSelectRow += pPrior->nSelectRow;
94740   }
94741 
94742   /* Generate a subroutine to run when the results from select B
94743   ** are exhausted and only data in select A remains.
94744   */
94745   if( op==TK_INTERSECT ){
94746     addrEofB = addrEofA;
94747     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
94748   }else{
94749     VdbeNoopComment((v, "eof-B subroutine"));
94750     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
94751     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
94752     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
94753     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
94754   }
94755 
94756   /* Generate code to handle the case of A<B
94757   */
94758   VdbeNoopComment((v, "A-lt-B subroutine"));
94759   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
94760   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
94761   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
94762   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
94763 
94764   /* Generate code to handle the case of A==B
94765   */
94766   if( op==TK_ALL ){
94767     addrAeqB = addrAltB;
94768   }else if( op==TK_INTERSECT ){
94769     addrAeqB = addrAltB;
94770     addrAltB++;
94771   }else{
94772     VdbeNoopComment((v, "A-eq-B subroutine"));
94773     addrAeqB =
94774     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
94775     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
94776     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
94777   }
94778 
94779   /* Generate code to handle the case of A>B
94780   */
94781   VdbeNoopComment((v, "A-gt-B subroutine"));
94782   addrAgtB = sqlite3VdbeCurrentAddr(v);
94783   if( op==TK_ALL || op==TK_UNION ){
94784     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
94785   }
94786   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
94787   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
94788   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
94789 
94790   /* This code runs once to initialize everything.
94791   */
94792   sqlite3VdbeJumpHere(v, j1);
94793   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
94794   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
94795   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
94796   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
94797   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
94798   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
94799 
94800   /* Implement the main merge loop
94801   */
94802   sqlite3VdbeResolveLabel(v, labelCmpr);
94803   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
94804   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
94805                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
94806   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
94807 
94808   /* Release temporary registers
94809   */
94810   if( regPrev ){
94811     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
94812   }
94813 
94814   /* Jump to the this point in order to terminate the query.
94815   */
94816   sqlite3VdbeResolveLabel(v, labelEnd);
94817 
94818   /* Set the number of output columns
94819   */
94820   if( pDest->eDest==SRT_Output ){
94821     Select *pFirst = pPrior;
94822     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
94823     generateColumnNames(pParse, 0, pFirst->pEList);
94824   }
94825 
94826   /* Reassembly the compound query so that it will be freed correctly
94827   ** by the calling function */
94828   if( p->pPrior ){
94829     sqlite3SelectDelete(db, p->pPrior);
94830   }
94831   p->pPrior = pPrior;
94832 
94833   /*** TBD:  Insert subroutine calls to close cursors on incomplete
94834   **** subqueries ****/
94835   explainComposite(pParse, p->op, iSub1, iSub2, 0);
94836   return SQLITE_OK;
94837 }
94838 #endif
94839 
94840 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
94841 /* Forward Declarations */
94842 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
94843 static void substSelect(sqlite3*, Select *, int, ExprList *);
94844 
94845 /*
94846 ** Scan through the expression pExpr.  Replace every reference to
94847 ** a column in table number iTable with a copy of the iColumn-th
94848 ** entry in pEList.  (But leave references to the ROWID column
94849 ** unchanged.)
94850 **
94851 ** This routine is part of the flattening procedure.  A subquery
94852 ** whose result set is defined by pEList appears as entry in the
94853 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
94854 ** FORM clause entry is iTable.  This routine make the necessary
94855 ** changes to pExpr so that it refers directly to the source table
94856 ** of the subquery rather the result set of the subquery.
94857 */
94858 static Expr *substExpr(
94859   sqlite3 *db,        /* Report malloc errors to this connection */
94860   Expr *pExpr,        /* Expr in which substitution occurs */
94861   int iTable,         /* Table to be substituted */
94862   ExprList *pEList    /* Substitute expressions */
94863 ){
94864   if( pExpr==0 ) return 0;
94865   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
94866     if( pExpr->iColumn<0 ){
94867       pExpr->op = TK_NULL;
94868     }else{
94869       Expr *pNew;
94870       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
94871       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
94872       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
94873       if( pNew && pExpr->pColl ){
94874         pNew->pColl = pExpr->pColl;
94875       }
94876       sqlite3ExprDelete(db, pExpr);
94877       pExpr = pNew;
94878     }
94879   }else{
94880     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
94881     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
94882     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
94883       substSelect(db, pExpr->x.pSelect, iTable, pEList);
94884     }else{
94885       substExprList(db, pExpr->x.pList, iTable, pEList);
94886     }
94887   }
94888   return pExpr;
94889 }
94890 static void substExprList(
94891   sqlite3 *db,         /* Report malloc errors here */
94892   ExprList *pList,     /* List to scan and in which to make substitutes */
94893   int iTable,          /* Table to be substituted */
94894   ExprList *pEList     /* Substitute values */
94895 ){
94896   int i;
94897   if( pList==0 ) return;
94898   for(i=0; i<pList->nExpr; i++){
94899     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
94900   }
94901 }
94902 static void substSelect(
94903   sqlite3 *db,         /* Report malloc errors here */
94904   Select *p,           /* SELECT statement in which to make substitutions */
94905   int iTable,          /* Table to be replaced */
94906   ExprList *pEList     /* Substitute values */
94907 ){
94908   SrcList *pSrc;
94909   struct SrcList_item *pItem;
94910   int i;
94911   if( !p ) return;
94912   substExprList(db, p->pEList, iTable, pEList);
94913   substExprList(db, p->pGroupBy, iTable, pEList);
94914   substExprList(db, p->pOrderBy, iTable, pEList);
94915   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
94916   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
94917   substSelect(db, p->pPrior, iTable, pEList);
94918   pSrc = p->pSrc;
94919   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
94920   if( ALWAYS(pSrc) ){
94921     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
94922       substSelect(db, pItem->pSelect, iTable, pEList);
94923     }
94924   }
94925 }
94926 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
94927 
94928 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
94929 /*
94930 ** This routine attempts to flatten subqueries in order to speed
94931 ** execution.  It returns 1 if it makes changes and 0 if no flattening
94932 ** occurs.
94933 **
94934 ** To understand the concept of flattening, consider the following
94935 ** query:
94936 **
94937 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
94938 **
94939 ** The default way of implementing this query is to execute the
94940 ** subquery first and store the results in a temporary table, then
94941 ** run the outer query on that temporary table.  This requires two
94942 ** passes over the data.  Furthermore, because the temporary table
94943 ** has no indices, the WHERE clause on the outer query cannot be
94944 ** optimized.
94945 **
94946 ** This routine attempts to rewrite queries such as the above into
94947 ** a single flat select, like this:
94948 **
94949 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
94950 **
94951 ** The code generated for this simpification gives the same result
94952 ** but only has to scan the data once.  And because indices might
94953 ** exist on the table t1, a complete scan of the data might be
94954 ** avoided.
94955 **
94956 ** Flattening is only attempted if all of the following are true:
94957 **
94958 **   (1)  The subquery and the outer query do not both use aggregates.
94959 **
94960 **   (2)  The subquery is not an aggregate or the outer query is not a join.
94961 **
94962 **   (3)  The subquery is not the right operand of a left outer join
94963 **        (Originally ticket #306.  Strengthened by ticket #3300)
94964 **
94965 **   (4)  The subquery is not DISTINCT.
94966 **
94967 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
94968 **        sub-queries that were excluded from this optimization. Restriction
94969 **        (4) has since been expanded to exclude all DISTINCT subqueries.
94970 **
94971 **   (6)  The subquery does not use aggregates or the outer query is not
94972 **        DISTINCT.
94973 **
94974 **   (7)  The subquery has a FROM clause.
94975 **
94976 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
94977 **
94978 **   (9)  The subquery does not use LIMIT or the outer query does not use
94979 **        aggregates.
94980 **
94981 **  (10)  The subquery does not use aggregates or the outer query does not
94982 **        use LIMIT.
94983 **
94984 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
94985 **
94986 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
94987 **        a separate restriction deriving from ticket #350.
94988 **
94989 **  (13)  The subquery and outer query do not both use LIMIT.
94990 **
94991 **  (14)  The subquery does not use OFFSET.
94992 **
94993 **  (15)  The outer query is not part of a compound select or the
94994 **        subquery does not have a LIMIT clause.
94995 **        (See ticket #2339 and ticket [02a8e81d44]).
94996 **
94997 **  (16)  The outer query is not an aggregate or the subquery does
94998 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
94999 **        until we introduced the group_concat() function.
95000 **
95001 **  (17)  The sub-query is not a compound select, or it is a UNION ALL
95002 **        compound clause made up entirely of non-aggregate queries, and
95003 **        the parent query:
95004 **
95005 **          * is not itself part of a compound select,
95006 **          * is not an aggregate or DISTINCT query, and
95007 **          * has no other tables or sub-selects in the FROM clause.
95008 **
95009 **        The parent and sub-query may contain WHERE clauses. Subject to
95010 **        rules (11), (13) and (14), they may also contain ORDER BY,
95011 **        LIMIT and OFFSET clauses.
95012 **
95013 **  (18)  If the sub-query is a compound select, then all terms of the
95014 **        ORDER by clause of the parent must be simple references to
95015 **        columns of the sub-query.
95016 **
95017 **  (19)  The subquery does not use LIMIT or the outer query does not
95018 **        have a WHERE clause.
95019 **
95020 **  (20)  If the sub-query is a compound select, then it must not use
95021 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
95022 **        somewhat by saying that the terms of the ORDER BY clause must
95023 **        appear as unmodified result columns in the outer query.  But
95024 **        have other optimizations in mind to deal with that case.
95025 **
95026 **  (21)  The subquery does not use LIMIT or the outer query is not
95027 **        DISTINCT.  (See ticket [752e1646fc]).
95028 **
95029 ** In this routine, the "p" parameter is a pointer to the outer query.
95030 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
95031 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
95032 **
95033 ** If flattening is not attempted, this routine is a no-op and returns 0.
95034 ** If flattening is attempted this routine returns 1.
95035 **
95036 ** All of the expression analysis must occur on both the outer query and
95037 ** the subquery before this routine runs.
95038 */
95039 static int flattenSubquery(
95040   Parse *pParse,       /* Parsing context */
95041   Select *p,           /* The parent or outer SELECT statement */
95042   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
95043   int isAgg,           /* True if outer SELECT uses aggregate functions */
95044   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
95045 ){
95046   const char *zSavedAuthContext = pParse->zAuthContext;
95047   Select *pParent;
95048   Select *pSub;       /* The inner query or "subquery" */
95049   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
95050   SrcList *pSrc;      /* The FROM clause of the outer query */
95051   SrcList *pSubSrc;   /* The FROM clause of the subquery */
95052   ExprList *pList;    /* The result set of the outer query */
95053   int iParent;        /* VDBE cursor number of the pSub result set temp table */
95054   int i;              /* Loop counter */
95055   Expr *pWhere;                    /* The WHERE clause */
95056   struct SrcList_item *pSubitem;   /* The subquery */
95057   sqlite3 *db = pParse->db;
95058 
95059   /* Check to see if flattening is permitted.  Return 0 if not.
95060   */
95061   assert( p!=0 );
95062   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
95063   if( db->flags & SQLITE_QueryFlattener ) return 0;
95064   pSrc = p->pSrc;
95065   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
95066   pSubitem = &pSrc->a[iFrom];
95067   iParent = pSubitem->iCursor;
95068   pSub = pSubitem->pSelect;
95069   assert( pSub!=0 );
95070   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
95071   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
95072   pSubSrc = pSub->pSrc;
95073   assert( pSubSrc );
95074   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
95075   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
95076   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
95077   ** became arbitrary expressions, we were forced to add restrictions (13)
95078   ** and (14). */
95079   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
95080   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
95081   if( p->pRightmost && pSub->pLimit ){
95082     return 0;                                            /* Restriction (15) */
95083   }
95084   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
95085   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
95086   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
95087      return 0;         /* Restrictions (8)(9) */
95088   }
95089   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
95090      return 0;         /* Restriction (6)  */
95091   }
95092   if( p->pOrderBy && pSub->pOrderBy ){
95093      return 0;                                           /* Restriction (11) */
95094   }
95095   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
95096   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
95097   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
95098      return 0;         /* Restriction (21) */
95099   }
95100 
95101   /* OBSOLETE COMMENT 1:
95102   ** Restriction 3:  If the subquery is a join, make sure the subquery is
95103   ** not used as the right operand of an outer join.  Examples of why this
95104   ** is not allowed:
95105   **
95106   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
95107   **
95108   ** If we flatten the above, we would get
95109   **
95110   **         (t1 LEFT OUTER JOIN t2) JOIN t3
95111   **
95112   ** which is not at all the same thing.
95113   **
95114   ** OBSOLETE COMMENT 2:
95115   ** Restriction 12:  If the subquery is the right operand of a left outer
95116   ** join, make sure the subquery has no WHERE clause.
95117   ** An examples of why this is not allowed:
95118   **
95119   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
95120   **
95121   ** If we flatten the above, we would get
95122   **
95123   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
95124   **
95125   ** But the t2.x>0 test will always fail on a NULL row of t2, which
95126   ** effectively converts the OUTER JOIN into an INNER JOIN.
95127   **
95128   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
95129   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
95130   ** is fraught with danger.  Best to avoid the whole thing.  If the
95131   ** subquery is the right term of a LEFT JOIN, then do not flatten.
95132   */
95133   if( (pSubitem->jointype & JT_OUTER)!=0 ){
95134     return 0;
95135   }
95136 
95137   /* Restriction 17: If the sub-query is a compound SELECT, then it must
95138   ** use only the UNION ALL operator. And none of the simple select queries
95139   ** that make up the compound SELECT are allowed to be aggregate or distinct
95140   ** queries.
95141   */
95142   if( pSub->pPrior ){
95143     if( pSub->pOrderBy ){
95144       return 0;  /* Restriction 20 */
95145     }
95146     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
95147       return 0;
95148     }
95149     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
95150       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
95151       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
95152       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
95153        || (pSub1->pPrior && pSub1->op!=TK_ALL)
95154        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
95155       ){
95156         return 0;
95157       }
95158     }
95159 
95160     /* Restriction 18. */
95161     if( p->pOrderBy ){
95162       int ii;
95163       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
95164         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
95165       }
95166     }
95167   }
95168 
95169   /***** If we reach this point, flattening is permitted. *****/
95170 
95171   /* Authorize the subquery */
95172   pParse->zAuthContext = pSubitem->zName;
95173   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
95174   pParse->zAuthContext = zSavedAuthContext;
95175 
95176   /* If the sub-query is a compound SELECT statement, then (by restrictions
95177   ** 17 and 18 above) it must be a UNION ALL and the parent query must
95178   ** be of the form:
95179   **
95180   **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
95181   **
95182   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
95183   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
95184   ** OFFSET clauses and joins them to the left-hand-side of the original
95185   ** using UNION ALL operators. In this case N is the number of simple
95186   ** select statements in the compound sub-query.
95187   **
95188   ** Example:
95189   **
95190   **     SELECT a+1 FROM (
95191   **        SELECT x FROM tab
95192   **        UNION ALL
95193   **        SELECT y FROM tab
95194   **        UNION ALL
95195   **        SELECT abs(z*2) FROM tab2
95196   **     ) WHERE a!=5 ORDER BY 1
95197   **
95198   ** Transformed into:
95199   **
95200   **     SELECT x+1 FROM tab WHERE x+1!=5
95201   **     UNION ALL
95202   **     SELECT y+1 FROM tab WHERE y+1!=5
95203   **     UNION ALL
95204   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
95205   **     ORDER BY 1
95206   **
95207   ** We call this the "compound-subquery flattening".
95208   */
95209   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
95210     Select *pNew;
95211     ExprList *pOrderBy = p->pOrderBy;
95212     Expr *pLimit = p->pLimit;
95213     Select *pPrior = p->pPrior;
95214     p->pOrderBy = 0;
95215     p->pSrc = 0;
95216     p->pPrior = 0;
95217     p->pLimit = 0;
95218     pNew = sqlite3SelectDup(db, p, 0);
95219     p->pLimit = pLimit;
95220     p->pOrderBy = pOrderBy;
95221     p->pSrc = pSrc;
95222     p->op = TK_ALL;
95223     p->pRightmost = 0;
95224     if( pNew==0 ){
95225       pNew = pPrior;
95226     }else{
95227       pNew->pPrior = pPrior;
95228       pNew->pRightmost = 0;
95229     }
95230     p->pPrior = pNew;
95231     if( db->mallocFailed ) return 1;
95232   }
95233 
95234   /* Begin flattening the iFrom-th entry of the FROM clause
95235   ** in the outer query.
95236   */
95237   pSub = pSub1 = pSubitem->pSelect;
95238 
95239   /* Delete the transient table structure associated with the
95240   ** subquery
95241   */
95242   sqlite3DbFree(db, pSubitem->zDatabase);
95243   sqlite3DbFree(db, pSubitem->zName);
95244   sqlite3DbFree(db, pSubitem->zAlias);
95245   pSubitem->zDatabase = 0;
95246   pSubitem->zName = 0;
95247   pSubitem->zAlias = 0;
95248   pSubitem->pSelect = 0;
95249 
95250   /* Defer deleting the Table object associated with the
95251   ** subquery until code generation is
95252   ** complete, since there may still exist Expr.pTab entries that
95253   ** refer to the subquery even after flattening.  Ticket #3346.
95254   **
95255   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
95256   */
95257   if( ALWAYS(pSubitem->pTab!=0) ){
95258     Table *pTabToDel = pSubitem->pTab;
95259     if( pTabToDel->nRef==1 ){
95260       Parse *pToplevel = sqlite3ParseToplevel(pParse);
95261       pTabToDel->pNextZombie = pToplevel->pZombieTab;
95262       pToplevel->pZombieTab = pTabToDel;
95263     }else{
95264       pTabToDel->nRef--;
95265     }
95266     pSubitem->pTab = 0;
95267   }
95268 
95269   /* The following loop runs once for each term in a compound-subquery
95270   ** flattening (as described above).  If we are doing a different kind
95271   ** of flattening - a flattening other than a compound-subquery flattening -
95272   ** then this loop only runs once.
95273   **
95274   ** This loop moves all of the FROM elements of the subquery into the
95275   ** the FROM clause of the outer query.  Before doing this, remember
95276   ** the cursor number for the original outer query FROM element in
95277   ** iParent.  The iParent cursor will never be used.  Subsequent code
95278   ** will scan expressions looking for iParent references and replace
95279   ** those references with expressions that resolve to the subquery FROM
95280   ** elements we are now copying in.
95281   */
95282   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
95283     int nSubSrc;
95284     u8 jointype = 0;
95285     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
95286     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
95287     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
95288 
95289     if( pSrc ){
95290       assert( pParent==p );  /* First time through the loop */
95291       jointype = pSubitem->jointype;
95292     }else{
95293       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
95294       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
95295       if( pSrc==0 ){
95296         assert( db->mallocFailed );
95297         break;
95298       }
95299     }
95300 
95301     /* The subquery uses a single slot of the FROM clause of the outer
95302     ** query.  If the subquery has more than one element in its FROM clause,
95303     ** then expand the outer query to make space for it to hold all elements
95304     ** of the subquery.
95305     **
95306     ** Example:
95307     **
95308     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
95309     **
95310     ** The outer query has 3 slots in its FROM clause.  One slot of the
95311     ** outer query (the middle slot) is used by the subquery.  The next
95312     ** block of code will expand the out query to 4 slots.  The middle
95313     ** slot is expanded to two slots in order to make space for the
95314     ** two elements in the FROM clause of the subquery.
95315     */
95316     if( nSubSrc>1 ){
95317       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
95318       if( db->mallocFailed ){
95319         break;
95320       }
95321     }
95322 
95323     /* Transfer the FROM clause terms from the subquery into the
95324     ** outer query.
95325     */
95326     for(i=0; i<nSubSrc; i++){
95327       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
95328       pSrc->a[i+iFrom] = pSubSrc->a[i];
95329       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
95330     }
95331     pSrc->a[iFrom].jointype = jointype;
95332 
95333     /* Now begin substituting subquery result set expressions for
95334     ** references to the iParent in the outer query.
95335     **
95336     ** Example:
95337     **
95338     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
95339     **   \                     \_____________ subquery __________/          /
95340     **    \_____________________ outer query ______________________________/
95341     **
95342     ** We look at every expression in the outer query and every place we see
95343     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
95344     */
95345     pList = pParent->pEList;
95346     for(i=0; i<pList->nExpr; i++){
95347       if( pList->a[i].zName==0 ){
95348         const char *zSpan = pList->a[i].zSpan;
95349         if( ALWAYS(zSpan) ){
95350           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
95351         }
95352       }
95353     }
95354     substExprList(db, pParent->pEList, iParent, pSub->pEList);
95355     if( isAgg ){
95356       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
95357       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
95358     }
95359     if( pSub->pOrderBy ){
95360       assert( pParent->pOrderBy==0 );
95361       pParent->pOrderBy = pSub->pOrderBy;
95362       pSub->pOrderBy = 0;
95363     }else if( pParent->pOrderBy ){
95364       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
95365     }
95366     if( pSub->pWhere ){
95367       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
95368     }else{
95369       pWhere = 0;
95370     }
95371     if( subqueryIsAgg ){
95372       assert( pParent->pHaving==0 );
95373       pParent->pHaving = pParent->pWhere;
95374       pParent->pWhere = pWhere;
95375       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
95376       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
95377                                   sqlite3ExprDup(db, pSub->pHaving, 0));
95378       assert( pParent->pGroupBy==0 );
95379       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
95380     }else{
95381       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
95382       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
95383     }
95384 
95385     /* The flattened query is distinct if either the inner or the
95386     ** outer query is distinct.
95387     */
95388     pParent->selFlags |= pSub->selFlags & SF_Distinct;
95389 
95390     /*
95391     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
95392     **
95393     ** One is tempted to try to add a and b to combine the limits.  But this
95394     ** does not work if either limit is negative.
95395     */
95396     if( pSub->pLimit ){
95397       pParent->pLimit = pSub->pLimit;
95398       pSub->pLimit = 0;
95399     }
95400   }
95401 
95402   /* Finially, delete what is left of the subquery and return
95403   ** success.
95404   */
95405   sqlite3SelectDelete(db, pSub1);
95406 
95407   return 1;
95408 }
95409 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
95410 
95411 /*
95412 ** Analyze the SELECT statement passed as an argument to see if it
95413 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
95414 ** it is, or 0 otherwise. At present, a query is considered to be
95415 ** a min()/max() query if:
95416 **
95417 **   1. There is a single object in the FROM clause.
95418 **
95419 **   2. There is a single expression in the result set, and it is
95420 **      either min(x) or max(x), where x is a column reference.
95421 */
95422 static u8 minMaxQuery(Select *p){
95423   Expr *pExpr;
95424   ExprList *pEList = p->pEList;
95425 
95426   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
95427   pExpr = pEList->a[0].pExpr;
95428   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
95429   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
95430   pEList = pExpr->x.pList;
95431   if( pEList==0 || pEList->nExpr!=1 ) return 0;
95432   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
95433   assert( !ExprHasProperty(pExpr, EP_IntValue) );
95434   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
95435     return WHERE_ORDERBY_MIN;
95436   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
95437     return WHERE_ORDERBY_MAX;
95438   }
95439   return WHERE_ORDERBY_NORMAL;
95440 }
95441 
95442 /*
95443 ** The select statement passed as the first argument is an aggregate query.
95444 ** The second argment is the associated aggregate-info object. This
95445 ** function tests if the SELECT is of the form:
95446 **
95447 **   SELECT count(*) FROM <tbl>
95448 **
95449 ** where table is a database table, not a sub-select or view. If the query
95450 ** does match this pattern, then a pointer to the Table object representing
95451 ** <tbl> is returned. Otherwise, 0 is returned.
95452 */
95453 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
95454   Table *pTab;
95455   Expr *pExpr;
95456 
95457   assert( !p->pGroupBy );
95458 
95459   if( p->pWhere || p->pEList->nExpr!=1
95460    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
95461   ){
95462     return 0;
95463   }
95464   pTab = p->pSrc->a[0].pTab;
95465   pExpr = p->pEList->a[0].pExpr;
95466   assert( pTab && !pTab->pSelect && pExpr );
95467 
95468   if( IsVirtual(pTab) ) return 0;
95469   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
95470   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
95471   if( pExpr->flags&EP_Distinct ) return 0;
95472 
95473   return pTab;
95474 }
95475 
95476 /*
95477 ** If the source-list item passed as an argument was augmented with an
95478 ** INDEXED BY clause, then try to locate the specified index. If there
95479 ** was such a clause and the named index cannot be found, return
95480 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
95481 ** pFrom->pIndex and return SQLITE_OK.
95482 */
95483 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
95484   if( pFrom->pTab && pFrom->zIndex ){
95485     Table *pTab = pFrom->pTab;
95486     char *zIndex = pFrom->zIndex;
95487     Index *pIdx;
95488     for(pIdx=pTab->pIndex;
95489         pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
95490         pIdx=pIdx->pNext
95491     );
95492     if( !pIdx ){
95493       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
95494       pParse->checkSchema = 1;
95495       return SQLITE_ERROR;
95496     }
95497     pFrom->pIndex = pIdx;
95498   }
95499   return SQLITE_OK;
95500 }
95501 
95502 /*
95503 ** This routine is a Walker callback for "expanding" a SELECT statement.
95504 ** "Expanding" means to do the following:
95505 **
95506 **    (1)  Make sure VDBE cursor numbers have been assigned to every
95507 **         element of the FROM clause.
95508 **
95509 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
95510 **         defines FROM clause.  When views appear in the FROM clause,
95511 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
95512 **         that implements the view.  A copy is made of the view's SELECT
95513 **         statement so that we can freely modify or delete that statement
95514 **         without worrying about messing up the presistent representation
95515 **         of the view.
95516 **
95517 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
95518 **         on joins and the ON and USING clause of joins.
95519 **
95520 **    (4)  Scan the list of columns in the result set (pEList) looking
95521 **         for instances of the "*" operator or the TABLE.* operator.
95522 **         If found, expand each "*" to be every column in every table
95523 **         and TABLE.* to be every column in TABLE.
95524 **
95525 */
95526 static int selectExpander(Walker *pWalker, Select *p){
95527   Parse *pParse = pWalker->pParse;
95528   int i, j, k;
95529   SrcList *pTabList;
95530   ExprList *pEList;
95531   struct SrcList_item *pFrom;
95532   sqlite3 *db = pParse->db;
95533 
95534   if( db->mallocFailed  ){
95535     return WRC_Abort;
95536   }
95537   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
95538     return WRC_Prune;
95539   }
95540   p->selFlags |= SF_Expanded;
95541   pTabList = p->pSrc;
95542   pEList = p->pEList;
95543 
95544   /* Make sure cursor numbers have been assigned to all entries in
95545   ** the FROM clause of the SELECT statement.
95546   */
95547   sqlite3SrcListAssignCursors(pParse, pTabList);
95548 
95549   /* Look up every table named in the FROM clause of the select.  If
95550   ** an entry of the FROM clause is a subquery instead of a table or view,
95551   ** then create a transient table structure to describe the subquery.
95552   */
95553   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
95554     Table *pTab;
95555     if( pFrom->pTab!=0 ){
95556       /* This statement has already been prepared.  There is no need
95557       ** to go further. */
95558       assert( i==0 );
95559       return WRC_Prune;
95560     }
95561     if( pFrom->zName==0 ){
95562 #ifndef SQLITE_OMIT_SUBQUERY
95563       Select *pSel = pFrom->pSelect;
95564       /* A sub-query in the FROM clause of a SELECT */
95565       assert( pSel!=0 );
95566       assert( pFrom->pTab==0 );
95567       sqlite3WalkSelect(pWalker, pSel);
95568       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
95569       if( pTab==0 ) return WRC_Abort;
95570       pTab->nRef = 1;
95571       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
95572       while( pSel->pPrior ){ pSel = pSel->pPrior; }
95573       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
95574       pTab->iPKey = -1;
95575       pTab->nRowEst = 1000000;
95576       pTab->tabFlags |= TF_Ephemeral;
95577 #endif
95578     }else{
95579       /* An ordinary table or view name in the FROM clause */
95580       assert( pFrom->pTab==0 );
95581       pFrom->pTab = pTab =
95582         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
95583       if( pTab==0 ) return WRC_Abort;
95584       pTab->nRef++;
95585 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
95586       if( pTab->pSelect || IsVirtual(pTab) ){
95587         /* We reach here if the named table is a really a view */
95588         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
95589         assert( pFrom->pSelect==0 );
95590         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
95591         sqlite3WalkSelect(pWalker, pFrom->pSelect);
95592       }
95593 #endif
95594     }
95595 
95596     /* Locate the index named by the INDEXED BY clause, if any. */
95597     if( sqlite3IndexedByLookup(pParse, pFrom) ){
95598       return WRC_Abort;
95599     }
95600   }
95601 
95602   /* Process NATURAL keywords, and ON and USING clauses of joins.
95603   */
95604   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
95605     return WRC_Abort;
95606   }
95607 
95608   /* For every "*" that occurs in the column list, insert the names of
95609   ** all columns in all tables.  And for every TABLE.* insert the names
95610   ** of all columns in TABLE.  The parser inserted a special expression
95611   ** with the TK_ALL operator for each "*" that it found in the column list.
95612   ** The following code just has to locate the TK_ALL expressions and expand
95613   ** each one to the list of all columns in all tables.
95614   **
95615   ** The first loop just checks to see if there are any "*" operators
95616   ** that need expanding.
95617   */
95618   for(k=0; k<pEList->nExpr; k++){
95619     Expr *pE = pEList->a[k].pExpr;
95620     if( pE->op==TK_ALL ) break;
95621     assert( pE->op!=TK_DOT || pE->pRight!=0 );
95622     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
95623     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
95624   }
95625   if( k<pEList->nExpr ){
95626     /*
95627     ** If we get here it means the result set contains one or more "*"
95628     ** operators that need to be expanded.  Loop through each expression
95629     ** in the result set and expand them one by one.
95630     */
95631     struct ExprList_item *a = pEList->a;
95632     ExprList *pNew = 0;
95633     int flags = pParse->db->flags;
95634     int longNames = (flags & SQLITE_FullColNames)!=0
95635                       && (flags & SQLITE_ShortColNames)==0;
95636 
95637     for(k=0; k<pEList->nExpr; k++){
95638       Expr *pE = a[k].pExpr;
95639       assert( pE->op!=TK_DOT || pE->pRight!=0 );
95640       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
95641         /* This particular expression does not need to be expanded.
95642         */
95643         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
95644         if( pNew ){
95645           pNew->a[pNew->nExpr-1].zName = a[k].zName;
95646           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
95647           a[k].zName = 0;
95648           a[k].zSpan = 0;
95649         }
95650         a[k].pExpr = 0;
95651       }else{
95652         /* This expression is a "*" or a "TABLE.*" and needs to be
95653         ** expanded. */
95654         int tableSeen = 0;      /* Set to 1 when TABLE matches */
95655         char *zTName;            /* text of name of TABLE */
95656         if( pE->op==TK_DOT ){
95657           assert( pE->pLeft!=0 );
95658           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
95659           zTName = pE->pLeft->u.zToken;
95660         }else{
95661           zTName = 0;
95662         }
95663         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
95664           Table *pTab = pFrom->pTab;
95665           char *zTabName = pFrom->zAlias;
95666           if( zTabName==0 ){
95667             zTabName = pTab->zName;
95668           }
95669           if( db->mallocFailed ) break;
95670           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
95671             continue;
95672           }
95673           tableSeen = 1;
95674           for(j=0; j<pTab->nCol; j++){
95675             Expr *pExpr, *pRight;
95676             char *zName = pTab->aCol[j].zName;
95677             char *zColname;  /* The computed column name */
95678             char *zToFree;   /* Malloced string that needs to be freed */
95679             Token sColname;  /* Computed column name as a token */
95680 
95681             /* If a column is marked as 'hidden' (currently only possible
95682             ** for virtual tables), do not include it in the expanded
95683             ** result-set list.
95684             */
95685             if( IsHiddenColumn(&pTab->aCol[j]) ){
95686               assert(IsVirtual(pTab));
95687               continue;
95688             }
95689 
95690             if( i>0 && zTName==0 ){
95691               if( (pFrom->jointype & JT_NATURAL)!=0
95692                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
95693               ){
95694                 /* In a NATURAL join, omit the join columns from the
95695                 ** table to the right of the join */
95696                 continue;
95697               }
95698               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
95699                 /* In a join with a USING clause, omit columns in the
95700                 ** using clause from the table on the right. */
95701                 continue;
95702               }
95703             }
95704             pRight = sqlite3Expr(db, TK_ID, zName);
95705             zColname = zName;
95706             zToFree = 0;
95707             if( longNames || pTabList->nSrc>1 ){
95708               Expr *pLeft;
95709               pLeft = sqlite3Expr(db, TK_ID, zTabName);
95710               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
95711               if( longNames ){
95712                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
95713                 zToFree = zColname;
95714               }
95715             }else{
95716               pExpr = pRight;
95717             }
95718             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
95719             sColname.z = zColname;
95720             sColname.n = sqlite3Strlen30(zColname);
95721             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
95722             sqlite3DbFree(db, zToFree);
95723           }
95724         }
95725         if( !tableSeen ){
95726           if( zTName ){
95727             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
95728           }else{
95729             sqlite3ErrorMsg(pParse, "no tables specified");
95730           }
95731         }
95732       }
95733     }
95734     sqlite3ExprListDelete(db, pEList);
95735     p->pEList = pNew;
95736   }
95737 #if SQLITE_MAX_COLUMN
95738   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
95739     sqlite3ErrorMsg(pParse, "too many columns in result set");
95740   }
95741 #endif
95742   return WRC_Continue;
95743 }
95744 
95745 /*
95746 ** No-op routine for the parse-tree walker.
95747 **
95748 ** When this routine is the Walker.xExprCallback then expression trees
95749 ** are walked without any actions being taken at each node.  Presumably,
95750 ** when this routine is used for Walker.xExprCallback then
95751 ** Walker.xSelectCallback is set to do something useful for every
95752 ** subquery in the parser tree.
95753 */
95754 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
95755   UNUSED_PARAMETER2(NotUsed, NotUsed2);
95756   return WRC_Continue;
95757 }
95758 
95759 /*
95760 ** This routine "expands" a SELECT statement and all of its subqueries.
95761 ** For additional information on what it means to "expand" a SELECT
95762 ** statement, see the comment on the selectExpand worker callback above.
95763 **
95764 ** Expanding a SELECT statement is the first step in processing a
95765 ** SELECT statement.  The SELECT statement must be expanded before
95766 ** name resolution is performed.
95767 **
95768 ** If anything goes wrong, an error message is written into pParse.
95769 ** The calling function can detect the problem by looking at pParse->nErr
95770 ** and/or pParse->db->mallocFailed.
95771 */
95772 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
95773   Walker w;
95774   w.xSelectCallback = selectExpander;
95775   w.xExprCallback = exprWalkNoop;
95776   w.pParse = pParse;
95777   sqlite3WalkSelect(&w, pSelect);
95778 }
95779 
95780 
95781 #ifndef SQLITE_OMIT_SUBQUERY
95782 /*
95783 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
95784 ** interface.
95785 **
95786 ** For each FROM-clause subquery, add Column.zType and Column.zColl
95787 ** information to the Table structure that represents the result set
95788 ** of that subquery.
95789 **
95790 ** The Table structure that represents the result set was constructed
95791 ** by selectExpander() but the type and collation information was omitted
95792 ** at that point because identifiers had not yet been resolved.  This
95793 ** routine is called after identifier resolution.
95794 */
95795 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
95796   Parse *pParse;
95797   int i;
95798   SrcList *pTabList;
95799   struct SrcList_item *pFrom;
95800 
95801   assert( p->selFlags & SF_Resolved );
95802   if( (p->selFlags & SF_HasTypeInfo)==0 ){
95803     p->selFlags |= SF_HasTypeInfo;
95804     pParse = pWalker->pParse;
95805     pTabList = p->pSrc;
95806     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
95807       Table *pTab = pFrom->pTab;
95808       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
95809         /* A sub-query in the FROM clause of a SELECT */
95810         Select *pSel = pFrom->pSelect;
95811         assert( pSel );
95812         while( pSel->pPrior ) pSel = pSel->pPrior;
95813         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
95814       }
95815     }
95816   }
95817   return WRC_Continue;
95818 }
95819 #endif
95820 
95821 
95822 /*
95823 ** This routine adds datatype and collating sequence information to
95824 ** the Table structures of all FROM-clause subqueries in a
95825 ** SELECT statement.
95826 **
95827 ** Use this routine after name resolution.
95828 */
95829 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
95830 #ifndef SQLITE_OMIT_SUBQUERY
95831   Walker w;
95832   w.xSelectCallback = selectAddSubqueryTypeInfo;
95833   w.xExprCallback = exprWalkNoop;
95834   w.pParse = pParse;
95835   sqlite3WalkSelect(&w, pSelect);
95836 #endif
95837 }
95838 
95839 
95840 /*
95841 ** This routine sets of a SELECT statement for processing.  The
95842 ** following is accomplished:
95843 **
95844 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
95845 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
95846 **     *  ON and USING clauses are shifted into WHERE statements
95847 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
95848 **     *  Identifiers in expression are matched to tables.
95849 **
95850 ** This routine acts recursively on all subqueries within the SELECT.
95851 */
95852 SQLITE_PRIVATE void sqlite3SelectPrep(
95853   Parse *pParse,         /* The parser context */
95854   Select *p,             /* The SELECT statement being coded. */
95855   NameContext *pOuterNC  /* Name context for container */
95856 ){
95857   sqlite3 *db;
95858   if( NEVER(p==0) ) return;
95859   db = pParse->db;
95860   if( p->selFlags & SF_HasTypeInfo ) return;
95861   sqlite3SelectExpand(pParse, p);
95862   if( pParse->nErr || db->mallocFailed ) return;
95863   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
95864   if( pParse->nErr || db->mallocFailed ) return;
95865   sqlite3SelectAddTypeInfo(pParse, p);
95866 }
95867 
95868 /*
95869 ** Reset the aggregate accumulator.
95870 **
95871 ** The aggregate accumulator is a set of memory cells that hold
95872 ** intermediate results while calculating an aggregate.  This
95873 ** routine simply stores NULLs in all of those memory cells.
95874 */
95875 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
95876   Vdbe *v = pParse->pVdbe;
95877   int i;
95878   struct AggInfo_func *pFunc;
95879   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
95880     return;
95881   }
95882   for(i=0; i<pAggInfo->nColumn; i++){
95883     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
95884   }
95885   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
95886     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
95887     if( pFunc->iDistinct>=0 ){
95888       Expr *pE = pFunc->pExpr;
95889       assert( !ExprHasProperty(pE, EP_xIsSelect) );
95890       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
95891         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
95892            "argument");
95893         pFunc->iDistinct = -1;
95894       }else{
95895         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
95896         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
95897                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
95898       }
95899     }
95900   }
95901 }
95902 
95903 /*
95904 ** Invoke the OP_AggFinalize opcode for every aggregate function
95905 ** in the AggInfo structure.
95906 */
95907 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
95908   Vdbe *v = pParse->pVdbe;
95909   int i;
95910   struct AggInfo_func *pF;
95911   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
95912     ExprList *pList = pF->pExpr->x.pList;
95913     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
95914     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
95915                       (void*)pF->pFunc, P4_FUNCDEF);
95916   }
95917 }
95918 
95919 /*
95920 ** Update the accumulator memory cells for an aggregate based on
95921 ** the current cursor position.
95922 */
95923 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
95924   Vdbe *v = pParse->pVdbe;
95925   int i;
95926   struct AggInfo_func *pF;
95927   struct AggInfo_col *pC;
95928 
95929   pAggInfo->directMode = 1;
95930   sqlite3ExprCacheClear(pParse);
95931   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
95932     int nArg;
95933     int addrNext = 0;
95934     int regAgg;
95935     ExprList *pList = pF->pExpr->x.pList;
95936     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
95937     if( pList ){
95938       nArg = pList->nExpr;
95939       regAgg = sqlite3GetTempRange(pParse, nArg);
95940       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
95941     }else{
95942       nArg = 0;
95943       regAgg = 0;
95944     }
95945     if( pF->iDistinct>=0 ){
95946       addrNext = sqlite3VdbeMakeLabel(v);
95947       assert( nArg==1 );
95948       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
95949     }
95950     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
95951       CollSeq *pColl = 0;
95952       struct ExprList_item *pItem;
95953       int j;
95954       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
95955       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
95956         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95957       }
95958       if( !pColl ){
95959         pColl = pParse->db->pDfltColl;
95960       }
95961       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
95962     }
95963     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
95964                       (void*)pF->pFunc, P4_FUNCDEF);
95965     sqlite3VdbeChangeP5(v, (u8)nArg);
95966     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
95967     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
95968     if( addrNext ){
95969       sqlite3VdbeResolveLabel(v, addrNext);
95970       sqlite3ExprCacheClear(pParse);
95971     }
95972   }
95973 
95974   /* Before populating the accumulator registers, clear the column cache.
95975   ** Otherwise, if any of the required column values are already present
95976   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
95977   ** to pC->iMem. But by the time the value is used, the original register
95978   ** may have been used, invalidating the underlying buffer holding the
95979   ** text or blob value. See ticket [883034dcb5].
95980   **
95981   ** Another solution would be to change the OP_SCopy used to copy cached
95982   ** values to an OP_Copy.
95983   */
95984   sqlite3ExprCacheClear(pParse);
95985   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
95986     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
95987   }
95988   pAggInfo->directMode = 0;
95989   sqlite3ExprCacheClear(pParse);
95990 }
95991 
95992 /*
95993 ** Add a single OP_Explain instruction to the VDBE to explain a simple
95994 ** count(*) query ("SELECT count(*) FROM pTab").
95995 */
95996 #ifndef SQLITE_OMIT_EXPLAIN
95997 static void explainSimpleCount(
95998   Parse *pParse,                  /* Parse context */
95999   Table *pTab,                    /* Table being queried */
96000   Index *pIdx                     /* Index used to optimize scan, or NULL */
96001 ){
96002   if( pParse->explain==2 ){
96003     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
96004         pTab->zName,
96005         pIdx ? "USING COVERING INDEX " : "",
96006         pIdx ? pIdx->zName : "",
96007         pTab->nRowEst
96008     );
96009     sqlite3VdbeAddOp4(
96010         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
96011     );
96012   }
96013 }
96014 #else
96015 # define explainSimpleCount(a,b,c)
96016 #endif
96017 
96018 /*
96019 ** Generate code for the SELECT statement given in the p argument.
96020 **
96021 ** The results are distributed in various ways depending on the
96022 ** contents of the SelectDest structure pointed to by argument pDest
96023 ** as follows:
96024 **
96025 **     pDest->eDest    Result
96026 **     ------------    -------------------------------------------
96027 **     SRT_Output      Generate a row of output (using the OP_ResultRow
96028 **                     opcode) for each row in the result set.
96029 **
96030 **     SRT_Mem         Only valid if the result is a single column.
96031 **                     Store the first column of the first result row
96032 **                     in register pDest->iParm then abandon the rest
96033 **                     of the query.  This destination implies "LIMIT 1".
96034 **
96035 **     SRT_Set         The result must be a single column.  Store each
96036 **                     row of result as the key in table pDest->iParm.
96037 **                     Apply the affinity pDest->affinity before storing
96038 **                     results.  Used to implement "IN (SELECT ...)".
96039 **
96040 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
96041 **
96042 **     SRT_Except      Remove results from the temporary table pDest->iParm.
96043 **
96044 **     SRT_Table       Store results in temporary table pDest->iParm.
96045 **                     This is like SRT_EphemTab except that the table
96046 **                     is assumed to already be open.
96047 **
96048 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
96049 **                     the result there. The cursor is left open after
96050 **                     returning.  This is like SRT_Table except that
96051 **                     this destination uses OP_OpenEphemeral to create
96052 **                     the table first.
96053 **
96054 **     SRT_Coroutine   Generate a co-routine that returns a new row of
96055 **                     results each time it is invoked.  The entry point
96056 **                     of the co-routine is stored in register pDest->iParm.
96057 **
96058 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
96059 **                     set is not empty.
96060 **
96061 **     SRT_Discard     Throw the results away.  This is used by SELECT
96062 **                     statements within triggers whose only purpose is
96063 **                     the side-effects of functions.
96064 **
96065 ** This routine returns the number of errors.  If any errors are
96066 ** encountered, then an appropriate error message is left in
96067 ** pParse->zErrMsg.
96068 **
96069 ** This routine does NOT free the Select structure passed in.  The
96070 ** calling function needs to do that.
96071 */
96072 SQLITE_PRIVATE int sqlite3Select(
96073   Parse *pParse,         /* The parser context */
96074   Select *p,             /* The SELECT statement being coded. */
96075   SelectDest *pDest      /* What to do with the query results */
96076 ){
96077   int i, j;              /* Loop counters */
96078   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
96079   Vdbe *v;               /* The virtual machine under construction */
96080   int isAgg;             /* True for select lists like "count(*)" */
96081   ExprList *pEList;      /* List of columns to extract. */
96082   SrcList *pTabList;     /* List of tables to select from */
96083   Expr *pWhere;          /* The WHERE clause.  May be NULL */
96084   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
96085   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
96086   Expr *pHaving;         /* The HAVING clause.  May be NULL */
96087   int isDistinct;        /* True if the DISTINCT keyword is present */
96088   int distinct;          /* Table to use for the distinct set */
96089   int rc = 1;            /* Value to return from this function */
96090   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
96091   int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
96092   AggInfo sAggInfo;      /* Information used by aggregate queries */
96093   int iEnd;              /* Address of the end of the query */
96094   sqlite3 *db;           /* The database connection */
96095 
96096 #ifndef SQLITE_OMIT_EXPLAIN
96097   int iRestoreSelectId = pParse->iSelectId;
96098   pParse->iSelectId = pParse->iNextSelectId++;
96099 #endif
96100 
96101   db = pParse->db;
96102   if( p==0 || db->mallocFailed || pParse->nErr ){
96103     return 1;
96104   }
96105   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
96106   memset(&sAggInfo, 0, sizeof(sAggInfo));
96107 
96108   if( IgnorableOrderby(pDest) ){
96109     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
96110            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
96111     /* If ORDER BY makes no difference in the output then neither does
96112     ** DISTINCT so it can be removed too. */
96113     sqlite3ExprListDelete(db, p->pOrderBy);
96114     p->pOrderBy = 0;
96115     p->selFlags &= ~SF_Distinct;
96116   }
96117   sqlite3SelectPrep(pParse, p, 0);
96118   pOrderBy = p->pOrderBy;
96119   pTabList = p->pSrc;
96120   pEList = p->pEList;
96121   if( pParse->nErr || db->mallocFailed ){
96122     goto select_end;
96123   }
96124   isAgg = (p->selFlags & SF_Aggregate)!=0;
96125   assert( pEList!=0 );
96126 
96127   /* Begin generating code.
96128   */
96129   v = sqlite3GetVdbe(pParse);
96130   if( v==0 ) goto select_end;
96131 
96132   /* If writing to memory or generating a set
96133   ** only a single column may be output.
96134   */
96135 #ifndef SQLITE_OMIT_SUBQUERY
96136   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
96137     goto select_end;
96138   }
96139 #endif
96140 
96141   /* Generate code for all sub-queries in the FROM clause
96142   */
96143 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
96144   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
96145     struct SrcList_item *pItem = &pTabList->a[i];
96146     SelectDest dest;
96147     Select *pSub = pItem->pSelect;
96148     int isAggSub;
96149 
96150     if( pSub==0 ) continue;
96151     if( pItem->addrFillSub ){
96152       sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
96153       continue;
96154     }
96155 
96156     /* Increment Parse.nHeight by the height of the largest expression
96157     ** tree refered to by this, the parent select. The child select
96158     ** may contain expression trees of at most
96159     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
96160     ** more conservative than necessary, but much easier than enforcing
96161     ** an exact limit.
96162     */
96163     pParse->nHeight += sqlite3SelectExprHeight(p);
96164 
96165     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
96166     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
96167       /* This subquery can be absorbed into its parent. */
96168       if( isAggSub ){
96169         isAgg = 1;
96170         p->selFlags |= SF_Aggregate;
96171       }
96172       i = -1;
96173     }else{
96174       /* Generate a subroutine that will fill an ephemeral table with
96175       ** the content of this subquery.  pItem->addrFillSub will point
96176       ** to the address of the generated subroutine.  pItem->regReturn
96177       ** is a register allocated to hold the subroutine return address
96178       */
96179       int topAddr;
96180       int onceAddr = 0;
96181       int retAddr;
96182       assert( pItem->addrFillSub==0 );
96183       pItem->regReturn = ++pParse->nMem;
96184       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
96185       pItem->addrFillSub = topAddr+1;
96186       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
96187       if( pItem->isCorrelated==0 && pParse->pTriggerTab==0 ){
96188         /* If the subquery is no correlated and if we are not inside of
96189         ** a trigger, then we only need to compute the value of the subquery
96190         ** once. */
96191         int regOnce = ++pParse->nMem;
96192         onceAddr = sqlite3VdbeAddOp1(v, OP_Once, regOnce);
96193       }
96194       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
96195       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
96196       sqlite3Select(pParse, pSub, &dest);
96197       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
96198       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
96199       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
96200       VdbeComment((v, "end %s", pItem->pTab->zName));
96201       sqlite3VdbeChangeP1(v, topAddr, retAddr);
96202 
96203     }
96204     if( /*pParse->nErr ||*/ db->mallocFailed ){
96205       goto select_end;
96206     }
96207     pParse->nHeight -= sqlite3SelectExprHeight(p);
96208     pTabList = p->pSrc;
96209     if( !IgnorableOrderby(pDest) ){
96210       pOrderBy = p->pOrderBy;
96211     }
96212   }
96213   pEList = p->pEList;
96214 #endif
96215   pWhere = p->pWhere;
96216   pGroupBy = p->pGroupBy;
96217   pHaving = p->pHaving;
96218   isDistinct = (p->selFlags & SF_Distinct)!=0;
96219 
96220 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96221   /* If there is are a sequence of queries, do the earlier ones first.
96222   */
96223   if( p->pPrior ){
96224     if( p->pRightmost==0 ){
96225       Select *pLoop, *pRight = 0;
96226       int cnt = 0;
96227       int mxSelect;
96228       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
96229         pLoop->pRightmost = p;
96230         pLoop->pNext = pRight;
96231         pRight = pLoop;
96232       }
96233       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
96234       if( mxSelect && cnt>mxSelect ){
96235         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
96236         goto select_end;
96237       }
96238     }
96239     rc = multiSelect(pParse, p, pDest);
96240     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
96241     return rc;
96242   }
96243 #endif
96244 
96245   /* If there is both a GROUP BY and an ORDER BY clause and they are
96246   ** identical, then disable the ORDER BY clause since the GROUP BY
96247   ** will cause elements to come out in the correct order.  This is
96248   ** an optimization - the correct answer should result regardless.
96249   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
96250   ** to disable this optimization for testing purposes.
96251   */
96252   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
96253          && (db->flags & SQLITE_GroupByOrder)==0 ){
96254     pOrderBy = 0;
96255   }
96256 
96257   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
96258   ** if the select-list is the same as the ORDER BY list, then this query
96259   ** can be rewritten as a GROUP BY. In other words, this:
96260   **
96261   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
96262   **
96263   ** is transformed to:
96264   **
96265   **     SELECT xyz FROM ... GROUP BY xyz
96266   **
96267   ** The second form is preferred as a single index (or temp-table) may be
96268   ** used for both the ORDER BY and DISTINCT processing. As originally
96269   ** written the query must use a temp-table for at least one of the ORDER
96270   ** BY and DISTINCT, and an index or separate temp-table for the other.
96271   */
96272   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
96273    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
96274   ){
96275     p->selFlags &= ~SF_Distinct;
96276     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
96277     pGroupBy = p->pGroupBy;
96278     pOrderBy = 0;
96279   }
96280 
96281   /* If there is an ORDER BY clause, then this sorting
96282   ** index might end up being unused if the data can be
96283   ** extracted in pre-sorted order.  If that is the case, then the
96284   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
96285   ** we figure out that the sorting index is not needed.  The addrSortIndex
96286   ** variable is used to facilitate that change.
96287   */
96288   if( pOrderBy ){
96289     KeyInfo *pKeyInfo;
96290     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
96291     pOrderBy->iECursor = pParse->nTab++;
96292     p->addrOpenEphm[2] = addrSortIndex =
96293       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
96294                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
96295                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96296   }else{
96297     addrSortIndex = -1;
96298   }
96299 
96300   /* If the output is destined for a temporary table, open that table.
96301   */
96302   if( pDest->eDest==SRT_EphemTab ){
96303     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
96304   }
96305 
96306   /* Set the limiter.
96307   */
96308   iEnd = sqlite3VdbeMakeLabel(v);
96309   p->nSelectRow = (double)LARGEST_INT64;
96310   computeLimitRegisters(pParse, p, iEnd);
96311   if( p->iLimit==0 && addrSortIndex>=0 ){
96312     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
96313     p->selFlags |= SF_UseSorter;
96314   }
96315 
96316   /* Open a virtual index to use for the distinct set.
96317   */
96318   if( p->selFlags & SF_Distinct ){
96319     KeyInfo *pKeyInfo;
96320     distinct = pParse->nTab++;
96321     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
96322     addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
96323         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96324     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96325   }else{
96326     distinct = addrDistinctIndex = -1;
96327   }
96328 
96329   /* Aggregate and non-aggregate queries are handled differently */
96330   if( !isAgg && pGroupBy==0 ){
96331     ExprList *pDist = (isDistinct ? p->pEList : 0);
96332 
96333     /* Begin the database scan. */
96334     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
96335     if( pWInfo==0 ) goto select_end;
96336     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
96337 
96338     /* If sorting index that was created by a prior OP_OpenEphemeral
96339     ** instruction ended up not being needed, then change the OP_OpenEphemeral
96340     ** into an OP_Noop.
96341     */
96342     if( addrSortIndex>=0 && pOrderBy==0 ){
96343       sqlite3VdbeChangeToNoop(v, addrSortIndex);
96344       p->addrOpenEphm[2] = -1;
96345     }
96346 
96347     if( pWInfo->eDistinct ){
96348       VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
96349 
96350       assert( addrDistinctIndex>=0 );
96351       pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
96352 
96353       assert( isDistinct );
96354       assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
96355            || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
96356       );
96357       distinct = -1;
96358       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
96359         int iJump;
96360         int iExpr;
96361         int iFlag = ++pParse->nMem;
96362         int iBase = pParse->nMem+1;
96363         int iBase2 = iBase + pEList->nExpr;
96364         pParse->nMem += (pEList->nExpr*2);
96365 
96366         /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
96367         ** OP_Integer initializes the "first row" flag.  */
96368         pOp->opcode = OP_Integer;
96369         pOp->p1 = 1;
96370         pOp->p2 = iFlag;
96371 
96372         sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
96373         iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
96374         sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
96375         for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
96376           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
96377           sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
96378           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
96379           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96380         }
96381         sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
96382 
96383         sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
96384         assert( sqlite3VdbeCurrentAddr(v)==iJump );
96385         sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
96386       }else{
96387         pOp->opcode = OP_Noop;
96388       }
96389     }
96390 
96391     /* Use the standard inner loop. */
96392     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
96393                     pWInfo->iContinue, pWInfo->iBreak);
96394 
96395     /* End the database scan loop.
96396     */
96397     sqlite3WhereEnd(pWInfo);
96398   }else{
96399     /* This is the processing for aggregate queries */
96400     NameContext sNC;    /* Name context for processing aggregate information */
96401     int iAMem;          /* First Mem address for storing current GROUP BY */
96402     int iBMem;          /* First Mem address for previous GROUP BY */
96403     int iUseFlag;       /* Mem address holding flag indicating that at least
96404                         ** one row of the input to the aggregator has been
96405                         ** processed */
96406     int iAbortFlag;     /* Mem address which causes query abort if positive */
96407     int groupBySort;    /* Rows come from source in GROUP BY order */
96408     int addrEnd;        /* End of processing for this SELECT */
96409     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
96410     int sortOut = 0;    /* Output register from the sorter */
96411 
96412     /* Remove any and all aliases between the result set and the
96413     ** GROUP BY clause.
96414     */
96415     if( pGroupBy ){
96416       int k;                        /* Loop counter */
96417       struct ExprList_item *pItem;  /* For looping over expression in a list */
96418 
96419       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
96420         pItem->iAlias = 0;
96421       }
96422       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
96423         pItem->iAlias = 0;
96424       }
96425       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
96426     }else{
96427       p->nSelectRow = (double)1;
96428     }
96429 
96430 
96431     /* Create a label to jump to when we want to abort the query */
96432     addrEnd = sqlite3VdbeMakeLabel(v);
96433 
96434     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
96435     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
96436     ** SELECT statement.
96437     */
96438     memset(&sNC, 0, sizeof(sNC));
96439     sNC.pParse = pParse;
96440     sNC.pSrcList = pTabList;
96441     sNC.pAggInfo = &sAggInfo;
96442     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
96443     sAggInfo.pGroupBy = pGroupBy;
96444     sqlite3ExprAnalyzeAggList(&sNC, pEList);
96445     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
96446     if( pHaving ){
96447       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
96448     }
96449     sAggInfo.nAccumulator = sAggInfo.nColumn;
96450     for(i=0; i<sAggInfo.nFunc; i++){
96451       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
96452       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
96453     }
96454     if( db->mallocFailed ) goto select_end;
96455 
96456     /* Processing for aggregates with GROUP BY is very different and
96457     ** much more complex than aggregates without a GROUP BY.
96458     */
96459     if( pGroupBy ){
96460       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
96461       int j1;             /* A-vs-B comparision jump */
96462       int addrOutputRow;  /* Start of subroutine that outputs a result row */
96463       int regOutputRow;   /* Return address register for output subroutine */
96464       int addrSetAbort;   /* Set the abort flag and return */
96465       int addrTopOfLoop;  /* Top of the input loop */
96466       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
96467       int addrReset;      /* Subroutine for resetting the accumulator */
96468       int regReset;       /* Return address register for reset subroutine */
96469 
96470       /* If there is a GROUP BY clause we might need a sorting index to
96471       ** implement it.  Allocate that sorting index now.  If it turns out
96472       ** that we do not need it after all, the OP_SorterOpen instruction
96473       ** will be converted into a Noop.
96474       */
96475       sAggInfo.sortingIdx = pParse->nTab++;
96476       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
96477       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
96478           sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
96479           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
96480 
96481       /* Initialize memory locations used by GROUP BY aggregate processing
96482       */
96483       iUseFlag = ++pParse->nMem;
96484       iAbortFlag = ++pParse->nMem;
96485       regOutputRow = ++pParse->nMem;
96486       addrOutputRow = sqlite3VdbeMakeLabel(v);
96487       regReset = ++pParse->nMem;
96488       addrReset = sqlite3VdbeMakeLabel(v);
96489       iAMem = pParse->nMem + 1;
96490       pParse->nMem += pGroupBy->nExpr;
96491       iBMem = pParse->nMem + 1;
96492       pParse->nMem += pGroupBy->nExpr;
96493       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
96494       VdbeComment((v, "clear abort flag"));
96495       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
96496       VdbeComment((v, "indicate accumulator empty"));
96497 
96498       /* Begin a loop that will extract all source rows in GROUP BY order.
96499       ** This might involve two separate loops with an OP_Sort in between, or
96500       ** it might be a single loop that uses an index to extract information
96501       ** in the right order to begin with.
96502       */
96503       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
96504       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
96505       if( pWInfo==0 ) goto select_end;
96506       if( pGroupBy==0 ){
96507         /* The optimizer is able to deliver rows in group by order so
96508         ** we do not have to sort.  The OP_OpenEphemeral table will be
96509         ** cancelled later because we still need to use the pKeyInfo
96510         */
96511         pGroupBy = p->pGroupBy;
96512         groupBySort = 0;
96513       }else{
96514         /* Rows are coming out in undetermined order.  We have to push
96515         ** each row into a sorting index, terminate the first loop,
96516         ** then loop over the sorting index in order to get the output
96517         ** in sorted order
96518         */
96519         int regBase;
96520         int regRecord;
96521         int nCol;
96522         int nGroupBy;
96523 
96524         explainTempTable(pParse,
96525             isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
96526 
96527         groupBySort = 1;
96528         nGroupBy = pGroupBy->nExpr;
96529         nCol = nGroupBy + 1;
96530         j = nGroupBy+1;
96531         for(i=0; i<sAggInfo.nColumn; i++){
96532           if( sAggInfo.aCol[i].iSorterColumn>=j ){
96533             nCol++;
96534             j++;
96535           }
96536         }
96537         regBase = sqlite3GetTempRange(pParse, nCol);
96538         sqlite3ExprCacheClear(pParse);
96539         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
96540         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
96541         j = nGroupBy+1;
96542         for(i=0; i<sAggInfo.nColumn; i++){
96543           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
96544           if( pCol->iSorterColumn>=j ){
96545             int r1 = j + regBase;
96546             int r2;
96547 
96548             r2 = sqlite3ExprCodeGetColumn(pParse,
96549                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
96550             if( r1!=r2 ){
96551               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
96552             }
96553             j++;
96554           }
96555         }
96556         regRecord = sqlite3GetTempReg(pParse);
96557         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
96558         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
96559         sqlite3ReleaseTempReg(pParse, regRecord);
96560         sqlite3ReleaseTempRange(pParse, regBase, nCol);
96561         sqlite3WhereEnd(pWInfo);
96562         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
96563         sortOut = sqlite3GetTempReg(pParse);
96564         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
96565         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
96566         VdbeComment((v, "GROUP BY sort"));
96567         sAggInfo.useSortingIdx = 1;
96568         sqlite3ExprCacheClear(pParse);
96569       }
96570 
96571       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
96572       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
96573       ** Then compare the current GROUP BY terms against the GROUP BY terms
96574       ** from the previous row currently stored in a0, a1, a2...
96575       */
96576       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
96577       sqlite3ExprCacheClear(pParse);
96578       if( groupBySort ){
96579         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
96580       }
96581       for(j=0; j<pGroupBy->nExpr; j++){
96582         if( groupBySort ){
96583           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
96584           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
96585         }else{
96586           sAggInfo.directMode = 1;
96587           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
96588         }
96589       }
96590       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
96591                           (char*)pKeyInfo, P4_KEYINFO);
96592       j1 = sqlite3VdbeCurrentAddr(v);
96593       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
96594 
96595       /* Generate code that runs whenever the GROUP BY changes.
96596       ** Changes in the GROUP BY are detected by the previous code
96597       ** block.  If there were no changes, this block is skipped.
96598       **
96599       ** This code copies current group by terms in b0,b1,b2,...
96600       ** over to a0,a1,a2.  It then calls the output subroutine
96601       ** and resets the aggregate accumulator registers in preparation
96602       ** for the next GROUP BY batch.
96603       */
96604       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
96605       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
96606       VdbeComment((v, "output one row"));
96607       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
96608       VdbeComment((v, "check abort flag"));
96609       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
96610       VdbeComment((v, "reset accumulator"));
96611 
96612       /* Update the aggregate accumulators based on the content of
96613       ** the current row
96614       */
96615       sqlite3VdbeJumpHere(v, j1);
96616       updateAccumulator(pParse, &sAggInfo);
96617       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
96618       VdbeComment((v, "indicate data in accumulator"));
96619 
96620       /* End of the loop
96621       */
96622       if( groupBySort ){
96623         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
96624       }else{
96625         sqlite3WhereEnd(pWInfo);
96626         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
96627       }
96628 
96629       /* Output the final row of result
96630       */
96631       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
96632       VdbeComment((v, "output final row"));
96633 
96634       /* Jump over the subroutines
96635       */
96636       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
96637 
96638       /* Generate a subroutine that outputs a single row of the result
96639       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
96640       ** is less than or equal to zero, the subroutine is a no-op.  If
96641       ** the processing calls for the query to abort, this subroutine
96642       ** increments the iAbortFlag memory location before returning in
96643       ** order to signal the caller to abort.
96644       */
96645       addrSetAbort = sqlite3VdbeCurrentAddr(v);
96646       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
96647       VdbeComment((v, "set abort flag"));
96648       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
96649       sqlite3VdbeResolveLabel(v, addrOutputRow);
96650       addrOutputRow = sqlite3VdbeCurrentAddr(v);
96651       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
96652       VdbeComment((v, "Groupby result generator entry point"));
96653       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
96654       finalizeAggFunctions(pParse, &sAggInfo);
96655       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
96656       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
96657                       distinct, pDest,
96658                       addrOutputRow+1, addrSetAbort);
96659       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
96660       VdbeComment((v, "end groupby result generator"));
96661 
96662       /* Generate a subroutine that will reset the group-by accumulator
96663       */
96664       sqlite3VdbeResolveLabel(v, addrReset);
96665       resetAccumulator(pParse, &sAggInfo);
96666       sqlite3VdbeAddOp1(v, OP_Return, regReset);
96667 
96668     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
96669     else {
96670       ExprList *pDel = 0;
96671 #ifndef SQLITE_OMIT_BTREECOUNT
96672       Table *pTab;
96673       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
96674         /* If isSimpleCount() returns a pointer to a Table structure, then
96675         ** the SQL statement is of the form:
96676         **
96677         **   SELECT count(*) FROM <tbl>
96678         **
96679         ** where the Table structure returned represents table <tbl>.
96680         **
96681         ** This statement is so common that it is optimized specially. The
96682         ** OP_Count instruction is executed either on the intkey table that
96683         ** contains the data for table <tbl> or on one of its indexes. It
96684         ** is better to execute the op on an index, as indexes are almost
96685         ** always spread across less pages than their corresponding tables.
96686         */
96687         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
96688         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
96689         Index *pIdx;                         /* Iterator variable */
96690         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
96691         Index *pBest = 0;                    /* Best index found so far */
96692         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
96693 
96694         sqlite3CodeVerifySchema(pParse, iDb);
96695         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
96696 
96697         /* Search for the index that has the least amount of columns. If
96698         ** there is such an index, and it has less columns than the table
96699         ** does, then we can assume that it consumes less space on disk and
96700         ** will therefore be cheaper to scan to determine the query result.
96701         ** In this case set iRoot to the root page number of the index b-tree
96702         ** and pKeyInfo to the KeyInfo structure required to navigate the
96703         ** index.
96704         **
96705         ** (2011-04-15) Do not do a full scan of an unordered index.
96706         **
96707         ** In practice the KeyInfo structure will not be used. It is only
96708         ** passed to keep OP_OpenRead happy.
96709         */
96710         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
96711           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
96712             pBest = pIdx;
96713           }
96714         }
96715         if( pBest && pBest->nColumn<pTab->nCol ){
96716           iRoot = pBest->tnum;
96717           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
96718         }
96719 
96720         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
96721         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
96722         if( pKeyInfo ){
96723           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
96724         }
96725         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
96726         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
96727         explainSimpleCount(pParse, pTab, pBest);
96728       }else
96729 #endif /* SQLITE_OMIT_BTREECOUNT */
96730       {
96731         /* Check if the query is of one of the following forms:
96732         **
96733         **   SELECT min(x) FROM ...
96734         **   SELECT max(x) FROM ...
96735         **
96736         ** If it is, then ask the code in where.c to attempt to sort results
96737         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
96738         ** If where.c is able to produce results sorted in this order, then
96739         ** add vdbe code to break out of the processing loop after the
96740         ** first iteration (since the first iteration of the loop is
96741         ** guaranteed to operate on the row with the minimum or maximum
96742         ** value of x, the only row required).
96743         **
96744         ** A special flag must be passed to sqlite3WhereBegin() to slightly
96745         ** modify behaviour as follows:
96746         **
96747         **   + If the query is a "SELECT min(x)", then the loop coded by
96748         **     where.c should not iterate over any values with a NULL value
96749         **     for x.
96750         **
96751         **   + The optimizer code in where.c (the thing that decides which
96752         **     index or indices to use) should place a different priority on
96753         **     satisfying the 'ORDER BY' clause than it does in other cases.
96754         **     Refer to code and comments in where.c for details.
96755         */
96756         ExprList *pMinMax = 0;
96757         u8 flag = minMaxQuery(p);
96758         if( flag ){
96759           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
96760           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
96761           pDel = pMinMax;
96762           if( pMinMax && !db->mallocFailed ){
96763             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
96764             pMinMax->a[0].pExpr->op = TK_COLUMN;
96765           }
96766         }
96767 
96768         /* This case runs if the aggregate has no GROUP BY clause.  The
96769         ** processing is much simpler since there is only a single row
96770         ** of output.
96771         */
96772         resetAccumulator(pParse, &sAggInfo);
96773         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
96774         if( pWInfo==0 ){
96775           sqlite3ExprListDelete(db, pDel);
96776           goto select_end;
96777         }
96778         updateAccumulator(pParse, &sAggInfo);
96779         if( !pMinMax && flag ){
96780           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
96781           VdbeComment((v, "%s() by index",
96782                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
96783         }
96784         sqlite3WhereEnd(pWInfo);
96785         finalizeAggFunctions(pParse, &sAggInfo);
96786       }
96787 
96788       pOrderBy = 0;
96789       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
96790       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
96791                       pDest, addrEnd, addrEnd);
96792       sqlite3ExprListDelete(db, pDel);
96793     }
96794     sqlite3VdbeResolveLabel(v, addrEnd);
96795 
96796   } /* endif aggregate query */
96797 
96798   if( distinct>=0 ){
96799     explainTempTable(pParse, "DISTINCT");
96800   }
96801 
96802   /* If there is an ORDER BY clause, then we need to sort the results
96803   ** and send them to the callback one by one.
96804   */
96805   if( pOrderBy ){
96806     explainTempTable(pParse, "ORDER BY");
96807     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
96808   }
96809 
96810   /* Jump here to skip this query
96811   */
96812   sqlite3VdbeResolveLabel(v, iEnd);
96813 
96814   /* The SELECT was successfully coded.   Set the return code to 0
96815   ** to indicate no errors.
96816   */
96817   rc = 0;
96818 
96819   /* Control jumps to here if an error is encountered above, or upon
96820   ** successful coding of the SELECT.
96821   */
96822 select_end:
96823   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
96824 
96825   /* Identify column names if results of the SELECT are to be output.
96826   */
96827   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
96828     generateColumnNames(pParse, pTabList, pEList);
96829   }
96830 
96831   sqlite3DbFree(db, sAggInfo.aCol);
96832   sqlite3DbFree(db, sAggInfo.aFunc);
96833   return rc;
96834 }
96835 
96836 #if defined(SQLITE_DEBUG)
96837 /*
96838 *******************************************************************************
96839 ** The following code is used for testing and debugging only.  The code
96840 ** that follows does not appear in normal builds.
96841 **
96842 ** These routines are used to print out the content of all or part of a
96843 ** parse structures such as Select or Expr.  Such printouts are useful
96844 ** for helping to understand what is happening inside the code generator
96845 ** during the execution of complex SELECT statements.
96846 **
96847 ** These routine are not called anywhere from within the normal
96848 ** code base.  Then are intended to be called from within the debugger
96849 ** or from temporary "printf" statements inserted for debugging.
96850 */
96851 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
96852   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
96853     sqlite3DebugPrintf("(%s", p->u.zToken);
96854   }else{
96855     sqlite3DebugPrintf("(%d", p->op);
96856   }
96857   if( p->pLeft ){
96858     sqlite3DebugPrintf(" ");
96859     sqlite3PrintExpr(p->pLeft);
96860   }
96861   if( p->pRight ){
96862     sqlite3DebugPrintf(" ");
96863     sqlite3PrintExpr(p->pRight);
96864   }
96865   sqlite3DebugPrintf(")");
96866 }
96867 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
96868   int i;
96869   for(i=0; i<pList->nExpr; i++){
96870     sqlite3PrintExpr(pList->a[i].pExpr);
96871     if( i<pList->nExpr-1 ){
96872       sqlite3DebugPrintf(", ");
96873     }
96874   }
96875 }
96876 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
96877   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
96878   sqlite3PrintExprList(p->pEList);
96879   sqlite3DebugPrintf("\n");
96880   if( p->pSrc ){
96881     char *zPrefix;
96882     int i;
96883     zPrefix = "FROM";
96884     for(i=0; i<p->pSrc->nSrc; i++){
96885       struct SrcList_item *pItem = &p->pSrc->a[i];
96886       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
96887       zPrefix = "";
96888       if( pItem->pSelect ){
96889         sqlite3DebugPrintf("(\n");
96890         sqlite3PrintSelect(pItem->pSelect, indent+10);
96891         sqlite3DebugPrintf("%*s)", indent+8, "");
96892       }else if( pItem->zName ){
96893         sqlite3DebugPrintf("%s", pItem->zName);
96894       }
96895       if( pItem->pTab ){
96896         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
96897       }
96898       if( pItem->zAlias ){
96899         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
96900       }
96901       if( i<p->pSrc->nSrc-1 ){
96902         sqlite3DebugPrintf(",");
96903       }
96904       sqlite3DebugPrintf("\n");
96905     }
96906   }
96907   if( p->pWhere ){
96908     sqlite3DebugPrintf("%*s WHERE ", indent, "");
96909     sqlite3PrintExpr(p->pWhere);
96910     sqlite3DebugPrintf("\n");
96911   }
96912   if( p->pGroupBy ){
96913     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
96914     sqlite3PrintExprList(p->pGroupBy);
96915     sqlite3DebugPrintf("\n");
96916   }
96917   if( p->pHaving ){
96918     sqlite3DebugPrintf("%*s HAVING ", indent, "");
96919     sqlite3PrintExpr(p->pHaving);
96920     sqlite3DebugPrintf("\n");
96921   }
96922   if( p->pOrderBy ){
96923     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
96924     sqlite3PrintExprList(p->pOrderBy);
96925     sqlite3DebugPrintf("\n");
96926   }
96927 }
96928 /* End of the structure debug printing code
96929 *****************************************************************************/
96930 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
96931 
96932 /************** End of select.c **********************************************/
96933 /************** Begin file table.c *******************************************/
96934 /*
96935 ** 2001 September 15
96936 **
96937 ** The author disclaims copyright to this source code.  In place of
96938 ** a legal notice, here is a blessing:
96939 **
96940 **    May you do good and not evil.
96941 **    May you find forgiveness for yourself and forgive others.
96942 **    May you share freely, never taking more than you give.
96943 **
96944 *************************************************************************
96945 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
96946 ** interface routines.  These are just wrappers around the main
96947 ** interface routine of sqlite3_exec().
96948 **
96949 ** These routines are in a separate files so that they will not be linked
96950 ** if they are not used.
96951 */
96952 /* #include <stdlib.h> */
96953 /* #include <string.h> */
96954 
96955 #ifndef SQLITE_OMIT_GET_TABLE
96956 
96957 /*
96958 ** This structure is used to pass data from sqlite3_get_table() through
96959 ** to the callback function is uses to build the result.
96960 */
96961 typedef struct TabResult {
96962   char **azResult;   /* Accumulated output */
96963   char *zErrMsg;     /* Error message text, if an error occurs */
96964   int nAlloc;        /* Slots allocated for azResult[] */
96965   int nRow;          /* Number of rows in the result */
96966   int nColumn;       /* Number of columns in the result */
96967   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
96968   int rc;            /* Return code from sqlite3_exec() */
96969 } TabResult;
96970 
96971 /*
96972 ** This routine is called once for each row in the result table.  Its job
96973 ** is to fill in the TabResult structure appropriately, allocating new
96974 ** memory as necessary.
96975 */
96976 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
96977   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
96978   int need;                         /* Slots needed in p->azResult[] */
96979   int i;                            /* Loop counter */
96980   char *z;                          /* A single column of result */
96981 
96982   /* Make sure there is enough space in p->azResult to hold everything
96983   ** we need to remember from this invocation of the callback.
96984   */
96985   if( p->nRow==0 && argv!=0 ){
96986     need = nCol*2;
96987   }else{
96988     need = nCol;
96989   }
96990   if( p->nData + need > p->nAlloc ){
96991     char **azNew;
96992     p->nAlloc = p->nAlloc*2 + need;
96993     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
96994     if( azNew==0 ) goto malloc_failed;
96995     p->azResult = azNew;
96996   }
96997 
96998   /* If this is the first row, then generate an extra row containing
96999   ** the names of all columns.
97000   */
97001   if( p->nRow==0 ){
97002     p->nColumn = nCol;
97003     for(i=0; i<nCol; i++){
97004       z = sqlite3_mprintf("%s", colv[i]);
97005       if( z==0 ) goto malloc_failed;
97006       p->azResult[p->nData++] = z;
97007     }
97008   }else if( p->nColumn!=nCol ){
97009     sqlite3_free(p->zErrMsg);
97010     p->zErrMsg = sqlite3_mprintf(
97011        "sqlite3_get_table() called with two or more incompatible queries"
97012     );
97013     p->rc = SQLITE_ERROR;
97014     return 1;
97015   }
97016 
97017   /* Copy over the row data
97018   */
97019   if( argv!=0 ){
97020     for(i=0; i<nCol; i++){
97021       if( argv[i]==0 ){
97022         z = 0;
97023       }else{
97024         int n = sqlite3Strlen30(argv[i])+1;
97025         z = sqlite3_malloc( n );
97026         if( z==0 ) goto malloc_failed;
97027         memcpy(z, argv[i], n);
97028       }
97029       p->azResult[p->nData++] = z;
97030     }
97031     p->nRow++;
97032   }
97033   return 0;
97034 
97035 malloc_failed:
97036   p->rc = SQLITE_NOMEM;
97037   return 1;
97038 }
97039 
97040 /*
97041 ** Query the database.  But instead of invoking a callback for each row,
97042 ** malloc() for space to hold the result and return the entire results
97043 ** at the conclusion of the call.
97044 **
97045 ** The result that is written to ***pazResult is held in memory obtained
97046 ** from malloc().  But the caller cannot free this memory directly.
97047 ** Instead, the entire table should be passed to sqlite3_free_table() when
97048 ** the calling procedure is finished using it.
97049 */
97050 SQLITE_API int sqlite3_get_table(
97051   sqlite3 *db,                /* The database on which the SQL executes */
97052   const char *zSql,           /* The SQL to be executed */
97053   char ***pazResult,          /* Write the result table here */
97054   int *pnRow,                 /* Write the number of rows in the result here */
97055   int *pnColumn,              /* Write the number of columns of result here */
97056   char **pzErrMsg             /* Write error messages here */
97057 ){
97058   int rc;
97059   TabResult res;
97060 
97061   *pazResult = 0;
97062   if( pnColumn ) *pnColumn = 0;
97063   if( pnRow ) *pnRow = 0;
97064   if( pzErrMsg ) *pzErrMsg = 0;
97065   res.zErrMsg = 0;
97066   res.nRow = 0;
97067   res.nColumn = 0;
97068   res.nData = 1;
97069   res.nAlloc = 20;
97070   res.rc = SQLITE_OK;
97071   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
97072   if( res.azResult==0 ){
97073      db->errCode = SQLITE_NOMEM;
97074      return SQLITE_NOMEM;
97075   }
97076   res.azResult[0] = 0;
97077   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
97078   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
97079   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
97080   if( (rc&0xff)==SQLITE_ABORT ){
97081     sqlite3_free_table(&res.azResult[1]);
97082     if( res.zErrMsg ){
97083       if( pzErrMsg ){
97084         sqlite3_free(*pzErrMsg);
97085         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
97086       }
97087       sqlite3_free(res.zErrMsg);
97088     }
97089     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
97090     return res.rc;
97091   }
97092   sqlite3_free(res.zErrMsg);
97093   if( rc!=SQLITE_OK ){
97094     sqlite3_free_table(&res.azResult[1]);
97095     return rc;
97096   }
97097   if( res.nAlloc>res.nData ){
97098     char **azNew;
97099     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
97100     if( azNew==0 ){
97101       sqlite3_free_table(&res.azResult[1]);
97102       db->errCode = SQLITE_NOMEM;
97103       return SQLITE_NOMEM;
97104     }
97105     res.azResult = azNew;
97106   }
97107   *pazResult = &res.azResult[1];
97108   if( pnColumn ) *pnColumn = res.nColumn;
97109   if( pnRow ) *pnRow = res.nRow;
97110   return rc;
97111 }
97112 
97113 /*
97114 ** This routine frees the space the sqlite3_get_table() malloced.
97115 */
97116 SQLITE_API void sqlite3_free_table(
97117   char **azResult            /* Result returned from from sqlite3_get_table() */
97118 ){
97119   if( azResult ){
97120     int i, n;
97121     azResult--;
97122     assert( azResult!=0 );
97123     n = SQLITE_PTR_TO_INT(azResult[0]);
97124     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
97125     sqlite3_free(azResult);
97126   }
97127 }
97128 
97129 #endif /* SQLITE_OMIT_GET_TABLE */
97130 
97131 /************** End of table.c ***********************************************/
97132 /************** Begin file trigger.c *****************************************/
97133 /*
97134 **
97135 ** The author disclaims copyright to this source code.  In place of
97136 ** a legal notice, here is a blessing:
97137 **
97138 **    May you do good and not evil.
97139 **    May you find forgiveness for yourself and forgive others.
97140 **    May you share freely, never taking more than you give.
97141 **
97142 *************************************************************************
97143 ** This file contains the implementation for TRIGGERs
97144 */
97145 
97146 #ifndef SQLITE_OMIT_TRIGGER
97147 /*
97148 ** Delete a linked list of TriggerStep structures.
97149 */
97150 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
97151   while( pTriggerStep ){
97152     TriggerStep * pTmp = pTriggerStep;
97153     pTriggerStep = pTriggerStep->pNext;
97154 
97155     sqlite3ExprDelete(db, pTmp->pWhere);
97156     sqlite3ExprListDelete(db, pTmp->pExprList);
97157     sqlite3SelectDelete(db, pTmp->pSelect);
97158     sqlite3IdListDelete(db, pTmp->pIdList);
97159 
97160     sqlite3DbFree(db, pTmp);
97161   }
97162 }
97163 
97164 /*
97165 ** Given table pTab, return a list of all the triggers attached to
97166 ** the table. The list is connected by Trigger.pNext pointers.
97167 **
97168 ** All of the triggers on pTab that are in the same database as pTab
97169 ** are already attached to pTab->pTrigger.  But there might be additional
97170 ** triggers on pTab in the TEMP schema.  This routine prepends all
97171 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
97172 ** and returns the combined list.
97173 **
97174 ** To state it another way:  This routine returns a list of all triggers
97175 ** that fire off of pTab.  The list will include any TEMP triggers on
97176 ** pTab as well as the triggers lised in pTab->pTrigger.
97177 */
97178 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
97179   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
97180   Trigger *pList = 0;                  /* List of triggers to return */
97181 
97182   if( pParse->disableTriggers ){
97183     return 0;
97184   }
97185 
97186   if( pTmpSchema!=pTab->pSchema ){
97187     HashElem *p;
97188     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
97189     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
97190       Trigger *pTrig = (Trigger *)sqliteHashData(p);
97191       if( pTrig->pTabSchema==pTab->pSchema
97192        && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
97193       ){
97194         pTrig->pNext = (pList ? pList : pTab->pTrigger);
97195         pList = pTrig;
97196       }
97197     }
97198   }
97199 
97200   return (pList ? pList : pTab->pTrigger);
97201 }
97202 
97203 /*
97204 ** This is called by the parser when it sees a CREATE TRIGGER statement
97205 ** up to the point of the BEGIN before the trigger actions.  A Trigger
97206 ** structure is generated based on the information available and stored
97207 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
97208 ** sqlite3FinishTrigger() function is called to complete the trigger
97209 ** construction process.
97210 */
97211 SQLITE_PRIVATE void sqlite3BeginTrigger(
97212   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
97213   Token *pName1,      /* The name of the trigger */
97214   Token *pName2,      /* The name of the trigger */
97215   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
97216   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
97217   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
97218   SrcList *pTableName,/* The name of the table/view the trigger applies to */
97219   Expr *pWhen,        /* WHEN clause */
97220   int isTemp,         /* True if the TEMPORARY keyword is present */
97221   int noErr           /* Suppress errors if the trigger already exists */
97222 ){
97223   Trigger *pTrigger = 0;  /* The new trigger */
97224   Table *pTab;            /* Table that the trigger fires off of */
97225   char *zName = 0;        /* Name of the trigger */
97226   sqlite3 *db = pParse->db;  /* The database connection */
97227   int iDb;                /* The database to store the trigger in */
97228   Token *pName;           /* The unqualified db name */
97229   DbFixer sFix;           /* State vector for the DB fixer */
97230   int iTabDb;             /* Index of the database holding pTab */
97231 
97232   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
97233   assert( pName2!=0 );
97234   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
97235   assert( op>0 && op<0xff );
97236   if( isTemp ){
97237     /* If TEMP was specified, then the trigger name may not be qualified. */
97238     if( pName2->n>0 ){
97239       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
97240       goto trigger_cleanup;
97241     }
97242     iDb = 1;
97243     pName = pName1;
97244   }else{
97245     /* Figure out the db that the the trigger will be created in */
97246     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
97247     if( iDb<0 ){
97248       goto trigger_cleanup;
97249     }
97250   }
97251   if( !pTableName || db->mallocFailed ){
97252     goto trigger_cleanup;
97253   }
97254 
97255   /* A long-standing parser bug is that this syntax was allowed:
97256   **
97257   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
97258   **                                                 ^^^^^^^^
97259   **
97260   ** To maintain backwards compatibility, ignore the database
97261   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
97262   */
97263   if( db->init.busy && iDb!=1 ){
97264     sqlite3DbFree(db, pTableName->a[0].zDatabase);
97265     pTableName->a[0].zDatabase = 0;
97266   }
97267 
97268   /* If the trigger name was unqualified, and the table is a temp table,
97269   ** then set iDb to 1 to create the trigger in the temporary database.
97270   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
97271   ** exist, the error is caught by the block below.
97272   */
97273   pTab = sqlite3SrcListLookup(pParse, pTableName);
97274   if( db->init.busy==0 && pName2->n==0 && pTab
97275         && pTab->pSchema==db->aDb[1].pSchema ){
97276     iDb = 1;
97277   }
97278 
97279   /* Ensure the table name matches database name and that the table exists */
97280   if( db->mallocFailed ) goto trigger_cleanup;
97281   assert( pTableName->nSrc==1 );
97282   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
97283       sqlite3FixSrcList(&sFix, pTableName) ){
97284     goto trigger_cleanup;
97285   }
97286   pTab = sqlite3SrcListLookup(pParse, pTableName);
97287   if( !pTab ){
97288     /* The table does not exist. */
97289     if( db->init.iDb==1 ){
97290       /* Ticket #3810.
97291       ** Normally, whenever a table is dropped, all associated triggers are
97292       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
97293       ** and the table is dropped by a different database connection, the
97294       ** trigger is not visible to the database connection that does the
97295       ** drop so the trigger cannot be dropped.  This results in an
97296       ** "orphaned trigger" - a trigger whose associated table is missing.
97297       */
97298       db->init.orphanTrigger = 1;
97299     }
97300     goto trigger_cleanup;
97301   }
97302   if( IsVirtual(pTab) ){
97303     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
97304     goto trigger_cleanup;
97305   }
97306 
97307   /* Check that the trigger name is not reserved and that no trigger of the
97308   ** specified name exists */
97309   zName = sqlite3NameFromToken(db, pName);
97310   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
97311     goto trigger_cleanup;
97312   }
97313   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97314   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
97315                       zName, sqlite3Strlen30(zName)) ){
97316     if( !noErr ){
97317       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
97318     }else{
97319       assert( !db->init.busy );
97320       sqlite3CodeVerifySchema(pParse, iDb);
97321     }
97322     goto trigger_cleanup;
97323   }
97324 
97325   /* Do not create a trigger on a system table */
97326   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
97327     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
97328     pParse->nErr++;
97329     goto trigger_cleanup;
97330   }
97331 
97332   /* INSTEAD of triggers are only for views and views only support INSTEAD
97333   ** of triggers.
97334   */
97335   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
97336     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
97337         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
97338     goto trigger_cleanup;
97339   }
97340   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
97341     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
97342         " trigger on table: %S", pTableName, 0);
97343     goto trigger_cleanup;
97344   }
97345   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
97346 
97347 #ifndef SQLITE_OMIT_AUTHORIZATION
97348   {
97349     int code = SQLITE_CREATE_TRIGGER;
97350     const char *zDb = db->aDb[iTabDb].zName;
97351     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
97352     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
97353     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
97354       goto trigger_cleanup;
97355     }
97356     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
97357       goto trigger_cleanup;
97358     }
97359   }
97360 #endif
97361 
97362   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
97363   ** cannot appear on views.  So we might as well translate every
97364   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
97365   ** elsewhere.
97366   */
97367   if (tr_tm == TK_INSTEAD){
97368     tr_tm = TK_BEFORE;
97369   }
97370 
97371   /* Build the Trigger object */
97372   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
97373   if( pTrigger==0 ) goto trigger_cleanup;
97374   pTrigger->zName = zName;
97375   zName = 0;
97376   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
97377   pTrigger->pSchema = db->aDb[iDb].pSchema;
97378   pTrigger->pTabSchema = pTab->pSchema;
97379   pTrigger->op = (u8)op;
97380   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
97381   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
97382   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
97383   assert( pParse->pNewTrigger==0 );
97384   pParse->pNewTrigger = pTrigger;
97385 
97386 trigger_cleanup:
97387   sqlite3DbFree(db, zName);
97388   sqlite3SrcListDelete(db, pTableName);
97389   sqlite3IdListDelete(db, pColumns);
97390   sqlite3ExprDelete(db, pWhen);
97391   if( !pParse->pNewTrigger ){
97392     sqlite3DeleteTrigger(db, pTrigger);
97393   }else{
97394     assert( pParse->pNewTrigger==pTrigger );
97395   }
97396 }
97397 
97398 /*
97399 ** This routine is called after all of the trigger actions have been parsed
97400 ** in order to complete the process of building the trigger.
97401 */
97402 SQLITE_PRIVATE void sqlite3FinishTrigger(
97403   Parse *pParse,          /* Parser context */
97404   TriggerStep *pStepList, /* The triggered program */
97405   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
97406 ){
97407   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
97408   char *zName;                            /* Name of trigger */
97409   sqlite3 *db = pParse->db;               /* The database */
97410   DbFixer sFix;                           /* Fixer object */
97411   int iDb;                                /* Database containing the trigger */
97412   Token nameToken;                        /* Trigger name for error reporting */
97413 
97414   pParse->pNewTrigger = 0;
97415   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
97416   zName = pTrig->zName;
97417   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
97418   pTrig->step_list = pStepList;
97419   while( pStepList ){
97420     pStepList->pTrig = pTrig;
97421     pStepList = pStepList->pNext;
97422   }
97423   nameToken.z = pTrig->zName;
97424   nameToken.n = sqlite3Strlen30(nameToken.z);
97425   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
97426           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
97427     goto triggerfinish_cleanup;
97428   }
97429 
97430   /* if we are not initializing,
97431   ** build the sqlite_master entry
97432   */
97433   if( !db->init.busy ){
97434     Vdbe *v;
97435     char *z;
97436 
97437     /* Make an entry in the sqlite_master table */
97438     v = sqlite3GetVdbe(pParse);
97439     if( v==0 ) goto triggerfinish_cleanup;
97440     sqlite3BeginWriteOperation(pParse, 0, iDb);
97441     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
97442     sqlite3NestedParse(pParse,
97443        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
97444        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
97445        pTrig->table, z);
97446     sqlite3DbFree(db, z);
97447     sqlite3ChangeCookie(pParse, iDb);
97448     sqlite3VdbeAddParseSchemaOp(v, iDb,
97449         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
97450   }
97451 
97452   if( db->init.busy ){
97453     Trigger *pLink = pTrig;
97454     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
97455     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97456     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
97457     if( pTrig ){
97458       db->mallocFailed = 1;
97459     }else if( pLink->pSchema==pLink->pTabSchema ){
97460       Table *pTab;
97461       int n = sqlite3Strlen30(pLink->table);
97462       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
97463       assert( pTab!=0 );
97464       pLink->pNext = pTab->pTrigger;
97465       pTab->pTrigger = pLink;
97466     }
97467   }
97468 
97469 triggerfinish_cleanup:
97470   sqlite3DeleteTrigger(db, pTrig);
97471   assert( !pParse->pNewTrigger );
97472   sqlite3DeleteTriggerStep(db, pStepList);
97473 }
97474 
97475 /*
97476 ** Turn a SELECT statement (that the pSelect parameter points to) into
97477 ** a trigger step.  Return a pointer to a TriggerStep structure.
97478 **
97479 ** The parser calls this routine when it finds a SELECT statement in
97480 ** body of a TRIGGER.
97481 */
97482 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
97483   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
97484   if( pTriggerStep==0 ) {
97485     sqlite3SelectDelete(db, pSelect);
97486     return 0;
97487   }
97488   pTriggerStep->op = TK_SELECT;
97489   pTriggerStep->pSelect = pSelect;
97490   pTriggerStep->orconf = OE_Default;
97491   return pTriggerStep;
97492 }
97493 
97494 /*
97495 ** Allocate space to hold a new trigger step.  The allocated space
97496 ** holds both the TriggerStep object and the TriggerStep.target.z string.
97497 **
97498 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
97499 */
97500 static TriggerStep *triggerStepAllocate(
97501   sqlite3 *db,                /* Database connection */
97502   u8 op,                      /* Trigger opcode */
97503   Token *pName                /* The target name */
97504 ){
97505   TriggerStep *pTriggerStep;
97506 
97507   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
97508   if( pTriggerStep ){
97509     char *z = (char*)&pTriggerStep[1];
97510     memcpy(z, pName->z, pName->n);
97511     pTriggerStep->target.z = z;
97512     pTriggerStep->target.n = pName->n;
97513     pTriggerStep->op = op;
97514   }
97515   return pTriggerStep;
97516 }
97517 
97518 /*
97519 ** Build a trigger step out of an INSERT statement.  Return a pointer
97520 ** to the new trigger step.
97521 **
97522 ** The parser calls this routine when it sees an INSERT inside the
97523 ** body of a trigger.
97524 */
97525 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
97526   sqlite3 *db,        /* The database connection */
97527   Token *pTableName,  /* Name of the table into which we insert */
97528   IdList *pColumn,    /* List of columns in pTableName to insert into */
97529   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
97530   Select *pSelect,    /* A SELECT statement that supplies values */
97531   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
97532 ){
97533   TriggerStep *pTriggerStep;
97534 
97535   assert(pEList == 0 || pSelect == 0);
97536   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
97537 
97538   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
97539   if( pTriggerStep ){
97540     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
97541     pTriggerStep->pIdList = pColumn;
97542     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
97543     pTriggerStep->orconf = orconf;
97544   }else{
97545     sqlite3IdListDelete(db, pColumn);
97546   }
97547   sqlite3ExprListDelete(db, pEList);
97548   sqlite3SelectDelete(db, pSelect);
97549 
97550   return pTriggerStep;
97551 }
97552 
97553 /*
97554 ** Construct a trigger step that implements an UPDATE statement and return
97555 ** a pointer to that trigger step.  The parser calls this routine when it
97556 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
97557 */
97558 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
97559   sqlite3 *db,         /* The database connection */
97560   Token *pTableName,   /* Name of the table to be updated */
97561   ExprList *pEList,    /* The SET clause: list of column and new values */
97562   Expr *pWhere,        /* The WHERE clause */
97563   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
97564 ){
97565   TriggerStep *pTriggerStep;
97566 
97567   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
97568   if( pTriggerStep ){
97569     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
97570     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97571     pTriggerStep->orconf = orconf;
97572   }
97573   sqlite3ExprListDelete(db, pEList);
97574   sqlite3ExprDelete(db, pWhere);
97575   return pTriggerStep;
97576 }
97577 
97578 /*
97579 ** Construct a trigger step that implements a DELETE statement and return
97580 ** a pointer to that trigger step.  The parser calls this routine when it
97581 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
97582 */
97583 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
97584   sqlite3 *db,            /* Database connection */
97585   Token *pTableName,      /* The table from which rows are deleted */
97586   Expr *pWhere            /* The WHERE clause */
97587 ){
97588   TriggerStep *pTriggerStep;
97589 
97590   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
97591   if( pTriggerStep ){
97592     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
97593     pTriggerStep->orconf = OE_Default;
97594   }
97595   sqlite3ExprDelete(db, pWhere);
97596   return pTriggerStep;
97597 }
97598 
97599 /*
97600 ** Recursively delete a Trigger structure
97601 */
97602 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
97603   if( pTrigger==0 ) return;
97604   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
97605   sqlite3DbFree(db, pTrigger->zName);
97606   sqlite3DbFree(db, pTrigger->table);
97607   sqlite3ExprDelete(db, pTrigger->pWhen);
97608   sqlite3IdListDelete(db, pTrigger->pColumns);
97609   sqlite3DbFree(db, pTrigger);
97610 }
97611 
97612 /*
97613 ** This function is called to drop a trigger from the database schema.
97614 **
97615 ** This may be called directly from the parser and therefore identifies
97616 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
97617 ** same job as this routine except it takes a pointer to the trigger
97618 ** instead of the trigger name.
97619 **/
97620 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
97621   Trigger *pTrigger = 0;
97622   int i;
97623   const char *zDb;
97624   const char *zName;
97625   int nName;
97626   sqlite3 *db = pParse->db;
97627 
97628   if( db->mallocFailed ) goto drop_trigger_cleanup;
97629   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97630     goto drop_trigger_cleanup;
97631   }
97632 
97633   assert( pName->nSrc==1 );
97634   zDb = pName->a[0].zDatabase;
97635   zName = pName->a[0].zName;
97636   nName = sqlite3Strlen30(zName);
97637   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97638   for(i=OMIT_TEMPDB; i<db->nDb; i++){
97639     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
97640     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
97641     assert( sqlite3SchemaMutexHeld(db, j, 0) );
97642     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
97643     if( pTrigger ) break;
97644   }
97645   if( !pTrigger ){
97646     if( !noErr ){
97647       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
97648     }else{
97649       sqlite3CodeVerifyNamedSchema(pParse, zDb);
97650     }
97651     pParse->checkSchema = 1;
97652     goto drop_trigger_cleanup;
97653   }
97654   sqlite3DropTriggerPtr(pParse, pTrigger);
97655 
97656 drop_trigger_cleanup:
97657   sqlite3SrcListDelete(db, pName);
97658 }
97659 
97660 /*
97661 ** Return a pointer to the Table structure for the table that a trigger
97662 ** is set on.
97663 */
97664 static Table *tableOfTrigger(Trigger *pTrigger){
97665   int n = sqlite3Strlen30(pTrigger->table);
97666   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
97667 }
97668 
97669 
97670 /*
97671 ** Drop a trigger given a pointer to that trigger.
97672 */
97673 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
97674   Table   *pTable;
97675   Vdbe *v;
97676   sqlite3 *db = pParse->db;
97677   int iDb;
97678 
97679   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
97680   assert( iDb>=0 && iDb<db->nDb );
97681   pTable = tableOfTrigger(pTrigger);
97682   assert( pTable );
97683   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
97684 #ifndef SQLITE_OMIT_AUTHORIZATION
97685   {
97686     int code = SQLITE_DROP_TRIGGER;
97687     const char *zDb = db->aDb[iDb].zName;
97688     const char *zTab = SCHEMA_TABLE(iDb);
97689     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
97690     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
97691       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
97692       return;
97693     }
97694   }
97695 #endif
97696 
97697   /* Generate code to destroy the database record of the trigger.
97698   */
97699   assert( pTable!=0 );
97700   if( (v = sqlite3GetVdbe(pParse))!=0 ){
97701     int base;
97702     static const VdbeOpList dropTrigger[] = {
97703       { OP_Rewind,     0, ADDR(9),  0},
97704       { OP_String8,    0, 1,        0}, /* 1 */
97705       { OP_Column,     0, 1,        2},
97706       { OP_Ne,         2, ADDR(8),  1},
97707       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
97708       { OP_Column,     0, 0,        2},
97709       { OP_Ne,         2, ADDR(8),  1},
97710       { OP_Delete,     0, 0,        0},
97711       { OP_Next,       0, ADDR(1),  0}, /* 8 */
97712     };
97713 
97714     sqlite3BeginWriteOperation(pParse, 0, iDb);
97715     sqlite3OpenMasterTable(pParse, iDb);
97716     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
97717     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
97718     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
97719     sqlite3ChangeCookie(pParse, iDb);
97720     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
97721     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
97722     if( pParse->nMem<3 ){
97723       pParse->nMem = 3;
97724     }
97725   }
97726 }
97727 
97728 /*
97729 ** Remove a trigger from the hash tables of the sqlite* pointer.
97730 */
97731 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
97732   Trigger *pTrigger;
97733   Hash *pHash;
97734 
97735   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97736   pHash = &(db->aDb[iDb].pSchema->trigHash);
97737   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
97738   if( ALWAYS(pTrigger) ){
97739     if( pTrigger->pSchema==pTrigger->pTabSchema ){
97740       Table *pTab = tableOfTrigger(pTrigger);
97741       Trigger **pp;
97742       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
97743       *pp = (*pp)->pNext;
97744     }
97745     sqlite3DeleteTrigger(db, pTrigger);
97746     db->flags |= SQLITE_InternChanges;
97747   }
97748 }
97749 
97750 /*
97751 ** pEList is the SET clause of an UPDATE statement.  Each entry
97752 ** in pEList is of the format <id>=<expr>.  If any of the entries
97753 ** in pEList have an <id> which matches an identifier in pIdList,
97754 ** then return TRUE.  If pIdList==NULL, then it is considered a
97755 ** wildcard that matches anything.  Likewise if pEList==NULL then
97756 ** it matches anything so always return true.  Return false only
97757 ** if there is no match.
97758 */
97759 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
97760   int e;
97761   if( pIdList==0 || NEVER(pEList==0) ) return 1;
97762   for(e=0; e<pEList->nExpr; e++){
97763     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
97764   }
97765   return 0;
97766 }
97767 
97768 /*
97769 ** Return a list of all triggers on table pTab if there exists at least
97770 ** one trigger that must be fired when an operation of type 'op' is
97771 ** performed on the table, and, if that operation is an UPDATE, if at
97772 ** least one of the columns in pChanges is being modified.
97773 */
97774 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
97775   Parse *pParse,          /* Parse context */
97776   Table *pTab,            /* The table the contains the triggers */
97777   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
97778   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
97779   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
97780 ){
97781   int mask = 0;
97782   Trigger *pList = 0;
97783   Trigger *p;
97784 
97785   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
97786     pList = sqlite3TriggerList(pParse, pTab);
97787   }
97788   assert( pList==0 || IsVirtual(pTab)==0 );
97789   for(p=pList; p; p=p->pNext){
97790     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
97791       mask |= p->tr_tm;
97792     }
97793   }
97794   if( pMask ){
97795     *pMask = mask;
97796   }
97797   return (mask ? pList : 0);
97798 }
97799 
97800 /*
97801 ** Convert the pStep->target token into a SrcList and return a pointer
97802 ** to that SrcList.
97803 **
97804 ** This routine adds a specific database name, if needed, to the target when
97805 ** forming the SrcList.  This prevents a trigger in one database from
97806 ** referring to a target in another database.  An exception is when the
97807 ** trigger is in TEMP in which case it can refer to any other database it
97808 ** wants.
97809 */
97810 static SrcList *targetSrcList(
97811   Parse *pParse,       /* The parsing context */
97812   TriggerStep *pStep   /* The trigger containing the target token */
97813 ){
97814   int iDb;             /* Index of the database to use */
97815   SrcList *pSrc;       /* SrcList to be returned */
97816 
97817   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
97818   if( pSrc ){
97819     assert( pSrc->nSrc>0 );
97820     assert( pSrc->a!=0 );
97821     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
97822     if( iDb==0 || iDb>=2 ){
97823       sqlite3 *db = pParse->db;
97824       assert( iDb<pParse->db->nDb );
97825       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
97826     }
97827   }
97828   return pSrc;
97829 }
97830 
97831 /*
97832 ** Generate VDBE code for the statements inside the body of a single
97833 ** trigger.
97834 */
97835 static int codeTriggerProgram(
97836   Parse *pParse,            /* The parser context */
97837   TriggerStep *pStepList,   /* List of statements inside the trigger body */
97838   int orconf                /* Conflict algorithm. (OE_Abort, etc) */
97839 ){
97840   TriggerStep *pStep;
97841   Vdbe *v = pParse->pVdbe;
97842   sqlite3 *db = pParse->db;
97843 
97844   assert( pParse->pTriggerTab && pParse->pToplevel );
97845   assert( pStepList );
97846   assert( v!=0 );
97847   for(pStep=pStepList; pStep; pStep=pStep->pNext){
97848     /* Figure out the ON CONFLICT policy that will be used for this step
97849     ** of the trigger program. If the statement that caused this trigger
97850     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
97851     ** the ON CONFLICT policy that was specified as part of the trigger
97852     ** step statement. Example:
97853     **
97854     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
97855     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
97856     **   END;
97857     **
97858     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
97859     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
97860     */
97861     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
97862 
97863     switch( pStep->op ){
97864       case TK_UPDATE: {
97865         sqlite3Update(pParse,
97866           targetSrcList(pParse, pStep),
97867           sqlite3ExprListDup(db, pStep->pExprList, 0),
97868           sqlite3ExprDup(db, pStep->pWhere, 0),
97869           pParse->eOrconf
97870         );
97871         break;
97872       }
97873       case TK_INSERT: {
97874         sqlite3Insert(pParse,
97875           targetSrcList(pParse, pStep),
97876           sqlite3ExprListDup(db, pStep->pExprList, 0),
97877           sqlite3SelectDup(db, pStep->pSelect, 0),
97878           sqlite3IdListDup(db, pStep->pIdList),
97879           pParse->eOrconf
97880         );
97881         break;
97882       }
97883       case TK_DELETE: {
97884         sqlite3DeleteFrom(pParse,
97885           targetSrcList(pParse, pStep),
97886           sqlite3ExprDup(db, pStep->pWhere, 0)
97887         );
97888         break;
97889       }
97890       default: assert( pStep->op==TK_SELECT ); {
97891         SelectDest sDest;
97892         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
97893         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
97894         sqlite3Select(pParse, pSelect, &sDest);
97895         sqlite3SelectDelete(db, pSelect);
97896         break;
97897       }
97898     }
97899     if( pStep->op!=TK_SELECT ){
97900       sqlite3VdbeAddOp0(v, OP_ResetCount);
97901     }
97902   }
97903 
97904   return 0;
97905 }
97906 
97907 #ifdef SQLITE_DEBUG
97908 /*
97909 ** This function is used to add VdbeComment() annotations to a VDBE
97910 ** program. It is not used in production code, only for debugging.
97911 */
97912 static const char *onErrorText(int onError){
97913   switch( onError ){
97914     case OE_Abort:    return "abort";
97915     case OE_Rollback: return "rollback";
97916     case OE_Fail:     return "fail";
97917     case OE_Replace:  return "replace";
97918     case OE_Ignore:   return "ignore";
97919     case OE_Default:  return "default";
97920   }
97921   return "n/a";
97922 }
97923 #endif
97924 
97925 /*
97926 ** Parse context structure pFrom has just been used to create a sub-vdbe
97927 ** (trigger program). If an error has occurred, transfer error information
97928 ** from pFrom to pTo.
97929 */
97930 static void transferParseError(Parse *pTo, Parse *pFrom){
97931   assert( pFrom->zErrMsg==0 || pFrom->nErr );
97932   assert( pTo->zErrMsg==0 || pTo->nErr );
97933   if( pTo->nErr==0 ){
97934     pTo->zErrMsg = pFrom->zErrMsg;
97935     pTo->nErr = pFrom->nErr;
97936   }else{
97937     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
97938   }
97939 }
97940 
97941 /*
97942 ** Create and populate a new TriggerPrg object with a sub-program
97943 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
97944 */
97945 static TriggerPrg *codeRowTrigger(
97946   Parse *pParse,       /* Current parse context */
97947   Trigger *pTrigger,   /* Trigger to code */
97948   Table *pTab,         /* The table pTrigger is attached to */
97949   int orconf           /* ON CONFLICT policy to code trigger program with */
97950 ){
97951   Parse *pTop = sqlite3ParseToplevel(pParse);
97952   sqlite3 *db = pParse->db;   /* Database handle */
97953   TriggerPrg *pPrg;           /* Value to return */
97954   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
97955   Vdbe *v;                    /* Temporary VM */
97956   NameContext sNC;            /* Name context for sub-vdbe */
97957   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
97958   Parse *pSubParse;           /* Parse context for sub-vdbe */
97959   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
97960 
97961   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
97962   assert( pTop->pVdbe );
97963 
97964   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
97965   ** are freed if an error occurs, link them into the Parse.pTriggerPrg
97966   ** list of the top-level Parse object sooner rather than later.  */
97967   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
97968   if( !pPrg ) return 0;
97969   pPrg->pNext = pTop->pTriggerPrg;
97970   pTop->pTriggerPrg = pPrg;
97971   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
97972   if( !pProgram ) return 0;
97973   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
97974   pPrg->pTrigger = pTrigger;
97975   pPrg->orconf = orconf;
97976   pPrg->aColmask[0] = 0xffffffff;
97977   pPrg->aColmask[1] = 0xffffffff;
97978 
97979   /* Allocate and populate a new Parse context to use for coding the
97980   ** trigger sub-program.  */
97981   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
97982   if( !pSubParse ) return 0;
97983   memset(&sNC, 0, sizeof(sNC));
97984   sNC.pParse = pSubParse;
97985   pSubParse->db = db;
97986   pSubParse->pTriggerTab = pTab;
97987   pSubParse->pToplevel = pTop;
97988   pSubParse->zAuthContext = pTrigger->zName;
97989   pSubParse->eTriggerOp = pTrigger->op;
97990   pSubParse->nQueryLoop = pParse->nQueryLoop;
97991 
97992   v = sqlite3GetVdbe(pSubParse);
97993   if( v ){
97994     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
97995       pTrigger->zName, onErrorText(orconf),
97996       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
97997         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
97998         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
97999         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
98000       pTab->zName
98001     ));
98002 #ifndef SQLITE_OMIT_TRACE
98003     sqlite3VdbeChangeP4(v, -1,
98004       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
98005     );
98006 #endif
98007 
98008     /* If one was specified, code the WHEN clause. If it evaluates to false
98009     ** (or NULL) the sub-vdbe is immediately halted by jumping to the
98010     ** OP_Halt inserted at the end of the program.  */
98011     if( pTrigger->pWhen ){
98012       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
98013       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
98014        && db->mallocFailed==0
98015       ){
98016         iEndTrigger = sqlite3VdbeMakeLabel(v);
98017         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
98018       }
98019       sqlite3ExprDelete(db, pWhen);
98020     }
98021 
98022     /* Code the trigger program into the sub-vdbe. */
98023     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
98024 
98025     /* Insert an OP_Halt at the end of the sub-program. */
98026     if( iEndTrigger ){
98027       sqlite3VdbeResolveLabel(v, iEndTrigger);
98028     }
98029     sqlite3VdbeAddOp0(v, OP_Halt);
98030     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
98031 
98032     transferParseError(pParse, pSubParse);
98033     if( db->mallocFailed==0 ){
98034       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
98035     }
98036     pProgram->nMem = pSubParse->nMem;
98037     pProgram->nCsr = pSubParse->nTab;
98038     pProgram->token = (void *)pTrigger;
98039     pPrg->aColmask[0] = pSubParse->oldmask;
98040     pPrg->aColmask[1] = pSubParse->newmask;
98041     sqlite3VdbeDelete(v);
98042   }
98043 
98044   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
98045   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
98046   sqlite3StackFree(db, pSubParse);
98047 
98048   return pPrg;
98049 }
98050 
98051 /*
98052 ** Return a pointer to a TriggerPrg object containing the sub-program for
98053 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
98054 ** TriggerPrg object exists, a new object is allocated and populated before
98055 ** being returned.
98056 */
98057 static TriggerPrg *getRowTrigger(
98058   Parse *pParse,       /* Current parse context */
98059   Trigger *pTrigger,   /* Trigger to code */
98060   Table *pTab,         /* The table trigger pTrigger is attached to */
98061   int orconf           /* ON CONFLICT algorithm. */
98062 ){
98063   Parse *pRoot = sqlite3ParseToplevel(pParse);
98064   TriggerPrg *pPrg;
98065 
98066   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
98067 
98068   /* It may be that this trigger has already been coded (or is in the
98069   ** process of being coded). If this is the case, then an entry with
98070   ** a matching TriggerPrg.pTrigger field will be present somewhere
98071   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
98072   for(pPrg=pRoot->pTriggerPrg;
98073       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
98074       pPrg=pPrg->pNext
98075   );
98076 
98077   /* If an existing TriggerPrg could not be located, create a new one. */
98078   if( !pPrg ){
98079     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
98080   }
98081 
98082   return pPrg;
98083 }
98084 
98085 /*
98086 ** Generate code for the trigger program associated with trigger p on
98087 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
98088 ** function are the same as those described in the header function for
98089 ** sqlite3CodeRowTrigger()
98090 */
98091 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
98092   Parse *pParse,       /* Parse context */
98093   Trigger *p,          /* Trigger to code */
98094   Table *pTab,         /* The table to code triggers from */
98095   int reg,             /* Reg array containing OLD.* and NEW.* values */
98096   int orconf,          /* ON CONFLICT policy */
98097   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
98098 ){
98099   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
98100   TriggerPrg *pPrg;
98101   pPrg = getRowTrigger(pParse, p, pTab, orconf);
98102   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
98103 
98104   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
98105   ** is a pointer to the sub-vdbe containing the trigger program.  */
98106   if( pPrg ){
98107     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
98108 
98109     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
98110     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
98111     VdbeComment(
98112         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
98113 
98114     /* Set the P5 operand of the OP_Program instruction to non-zero if
98115     ** recursive invocation of this trigger program is disallowed. Recursive
98116     ** invocation is disallowed if (a) the sub-program is really a trigger,
98117     ** not a foreign key action, and (b) the flag to enable recursive triggers
98118     ** is clear.  */
98119     sqlite3VdbeChangeP5(v, (u8)bRecursive);
98120   }
98121 }
98122 
98123 /*
98124 ** This is called to code the required FOR EACH ROW triggers for an operation
98125 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
98126 ** is given by the op paramater. The tr_tm parameter determines whether the
98127 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
98128 ** parameter pChanges is passed the list of columns being modified.
98129 **
98130 ** If there are no triggers that fire at the specified time for the specified
98131 ** operation on pTab, this function is a no-op.
98132 **
98133 ** The reg argument is the address of the first in an array of registers
98134 ** that contain the values substituted for the new.* and old.* references
98135 ** in the trigger program. If N is the number of columns in table pTab
98136 ** (a copy of pTab->nCol), then registers are populated as follows:
98137 **
98138 **   Register       Contains
98139 **   ------------------------------------------------------
98140 **   reg+0          OLD.rowid
98141 **   reg+1          OLD.* value of left-most column of pTab
98142 **   ...            ...
98143 **   reg+N          OLD.* value of right-most column of pTab
98144 **   reg+N+1        NEW.rowid
98145 **   reg+N+2        OLD.* value of left-most column of pTab
98146 **   ...            ...
98147 **   reg+N+N+1      NEW.* value of right-most column of pTab
98148 **
98149 ** For ON DELETE triggers, the registers containing the NEW.* values will
98150 ** never be accessed by the trigger program, so they are not allocated or
98151 ** populated by the caller (there is no data to populate them with anyway).
98152 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
98153 ** are never accessed, and so are not allocated by the caller. So, for an
98154 ** ON INSERT trigger, the value passed to this function as parameter reg
98155 ** is not a readable register, although registers (reg+N) through
98156 ** (reg+N+N+1) are.
98157 **
98158 ** Parameter orconf is the default conflict resolution algorithm for the
98159 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
98160 ** is the instruction that control should jump to if a trigger program
98161 ** raises an IGNORE exception.
98162 */
98163 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
98164   Parse *pParse,       /* Parse context */
98165   Trigger *pTrigger,   /* List of triggers on table pTab */
98166   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
98167   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
98168   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
98169   Table *pTab,         /* The table to code triggers from */
98170   int reg,             /* The first in an array of registers (see above) */
98171   int orconf,          /* ON CONFLICT policy */
98172   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
98173 ){
98174   Trigger *p;          /* Used to iterate through pTrigger list */
98175 
98176   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
98177   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
98178   assert( (op==TK_UPDATE)==(pChanges!=0) );
98179 
98180   for(p=pTrigger; p; p=p->pNext){
98181 
98182     /* Sanity checking:  The schema for the trigger and for the table are
98183     ** always defined.  The trigger must be in the same schema as the table
98184     ** or else it must be a TEMP trigger. */
98185     assert( p->pSchema!=0 );
98186     assert( p->pTabSchema!=0 );
98187     assert( p->pSchema==p->pTabSchema
98188          || p->pSchema==pParse->db->aDb[1].pSchema );
98189 
98190     /* Determine whether we should code this trigger */
98191     if( p->op==op
98192      && p->tr_tm==tr_tm
98193      && checkColumnOverlap(p->pColumns, pChanges)
98194     ){
98195       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
98196     }
98197   }
98198 }
98199 
98200 /*
98201 ** Triggers may access values stored in the old.* or new.* pseudo-table.
98202 ** This function returns a 32-bit bitmask indicating which columns of the
98203 ** old.* or new.* tables actually are used by triggers. This information
98204 ** may be used by the caller, for example, to avoid having to load the entire
98205 ** old.* record into memory when executing an UPDATE or DELETE command.
98206 **
98207 ** Bit 0 of the returned mask is set if the left-most column of the
98208 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
98209 ** the second leftmost column value is required, and so on. If there
98210 ** are more than 32 columns in the table, and at least one of the columns
98211 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
98212 **
98213 ** It is not possible to determine if the old.rowid or new.rowid column is
98214 ** accessed by triggers. The caller must always assume that it is.
98215 **
98216 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
98217 ** applies to the old.* table. If 1, the new.* table.
98218 **
98219 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
98220 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
98221 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
98222 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
98223 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
98224 */
98225 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
98226   Parse *pParse,       /* Parse context */
98227   Trigger *pTrigger,   /* List of triggers on table pTab */
98228   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
98229   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
98230   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
98231   Table *pTab,         /* The table to code triggers from */
98232   int orconf           /* Default ON CONFLICT policy for trigger steps */
98233 ){
98234   const int op = pChanges ? TK_UPDATE : TK_DELETE;
98235   u32 mask = 0;
98236   Trigger *p;
98237 
98238   assert( isNew==1 || isNew==0 );
98239   for(p=pTrigger; p; p=p->pNext){
98240     if( p->op==op && (tr_tm&p->tr_tm)
98241      && checkColumnOverlap(p->pColumns,pChanges)
98242     ){
98243       TriggerPrg *pPrg;
98244       pPrg = getRowTrigger(pParse, p, pTab, orconf);
98245       if( pPrg ){
98246         mask |= pPrg->aColmask[isNew];
98247       }
98248     }
98249   }
98250 
98251   return mask;
98252 }
98253 
98254 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
98255 
98256 /************** End of trigger.c *********************************************/
98257 /************** Begin file update.c ******************************************/
98258 /*
98259 ** 2001 September 15
98260 **
98261 ** The author disclaims copyright to this source code.  In place of
98262 ** a legal notice, here is a blessing:
98263 **
98264 **    May you do good and not evil.
98265 **    May you find forgiveness for yourself and forgive others.
98266 **    May you share freely, never taking more than you give.
98267 **
98268 *************************************************************************
98269 ** This file contains C code routines that are called by the parser
98270 ** to handle UPDATE statements.
98271 */
98272 
98273 #ifndef SQLITE_OMIT_VIRTUALTABLE
98274 /* Forward declaration */
98275 static void updateVirtualTable(
98276   Parse *pParse,       /* The parsing context */
98277   SrcList *pSrc,       /* The virtual table to be modified */
98278   Table *pTab,         /* The virtual table */
98279   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
98280   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
98281   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
98282   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
98283   int onError          /* ON CONFLICT strategy */
98284 );
98285 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98286 
98287 /*
98288 ** The most recently coded instruction was an OP_Column to retrieve the
98289 ** i-th column of table pTab. This routine sets the P4 parameter of the
98290 ** OP_Column to the default value, if any.
98291 **
98292 ** The default value of a column is specified by a DEFAULT clause in the
98293 ** column definition. This was either supplied by the user when the table
98294 ** was created, or added later to the table definition by an ALTER TABLE
98295 ** command. If the latter, then the row-records in the table btree on disk
98296 ** may not contain a value for the column and the default value, taken
98297 ** from the P4 parameter of the OP_Column instruction, is returned instead.
98298 ** If the former, then all row-records are guaranteed to include a value
98299 ** for the column and the P4 value is not required.
98300 **
98301 ** Column definitions created by an ALTER TABLE command may only have
98302 ** literal default values specified: a number, null or a string. (If a more
98303 ** complicated default expression value was provided, it is evaluated
98304 ** when the ALTER TABLE is executed and one of the literal values written
98305 ** into the sqlite_master table.)
98306 **
98307 ** Therefore, the P4 parameter is only required if the default value for
98308 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
98309 ** function is capable of transforming these types of expressions into
98310 ** sqlite3_value objects.
98311 **
98312 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
98313 ** on register iReg. This is used when an equivalent integer value is
98314 ** stored in place of an 8-byte floating point value in order to save
98315 ** space.
98316 */
98317 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
98318   assert( pTab!=0 );
98319   if( !pTab->pSelect ){
98320     sqlite3_value *pValue;
98321     u8 enc = ENC(sqlite3VdbeDb(v));
98322     Column *pCol = &pTab->aCol[i];
98323     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
98324     assert( i<pTab->nCol );
98325     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
98326                          pCol->affinity, &pValue);
98327     if( pValue ){
98328       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
98329     }
98330 #ifndef SQLITE_OMIT_FLOATING_POINT
98331     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
98332       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
98333     }
98334 #endif
98335   }
98336 }
98337 
98338 /*
98339 ** Process an UPDATE statement.
98340 **
98341 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
98342 **          \_______/ \________/     \______/       \________________/
98343 *            onError   pTabList      pChanges             pWhere
98344 */
98345 SQLITE_PRIVATE void sqlite3Update(
98346   Parse *pParse,         /* The parser context */
98347   SrcList *pTabList,     /* The table in which we should change things */
98348   ExprList *pChanges,    /* Things to be changed */
98349   Expr *pWhere,          /* The WHERE clause.  May be null */
98350   int onError            /* How to handle constraint errors */
98351 ){
98352   int i, j;              /* Loop counters */
98353   Table *pTab;           /* The table to be updated */
98354   int addr = 0;          /* VDBE instruction address of the start of the loop */
98355   WhereInfo *pWInfo;     /* Information about the WHERE clause */
98356   Vdbe *v;               /* The virtual database engine */
98357   Index *pIdx;           /* For looping over indices */
98358   int nIdx;              /* Number of indices that need updating */
98359   int iCur;              /* VDBE Cursor number of pTab */
98360   sqlite3 *db;           /* The database structure */
98361   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
98362   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
98363                          ** an expression for the i-th column of the table.
98364                          ** aXRef[i]==-1 if the i-th column is not changed. */
98365   int chngRowid;         /* True if the record number is being changed */
98366   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
98367   int openAll = 0;       /* True if all indices need to be opened */
98368   AuthContext sContext;  /* The authorization context */
98369   NameContext sNC;       /* The name-context to resolve expressions in */
98370   int iDb;               /* Database containing the table being updated */
98371   int okOnePass;         /* True for one-pass algorithm without the FIFO */
98372   int hasFK;             /* True if foreign key processing is required */
98373 
98374 #ifndef SQLITE_OMIT_TRIGGER
98375   int isView;            /* True when updating a view (INSTEAD OF trigger) */
98376   Trigger *pTrigger;     /* List of triggers on pTab, if required */
98377   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
98378 #endif
98379   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
98380 
98381   /* Register Allocations */
98382   int regRowCount = 0;   /* A count of rows changed */
98383   int regOldRowid;       /* The old rowid */
98384   int regNewRowid;       /* The new rowid */
98385   int regNew;
98386   int regOld = 0;
98387   int regRowSet = 0;     /* Rowset of rows to be updated */
98388 
98389   memset(&sContext, 0, sizeof(sContext));
98390   db = pParse->db;
98391   if( pParse->nErr || db->mallocFailed ){
98392     goto update_cleanup;
98393   }
98394   assert( pTabList->nSrc==1 );
98395 
98396   /* Locate the table which we want to update.
98397   */
98398   pTab = sqlite3SrcListLookup(pParse, pTabList);
98399   if( pTab==0 ) goto update_cleanup;
98400   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98401 
98402   /* Figure out if we have any triggers and if the table being
98403   ** updated is a view.
98404   */
98405 #ifndef SQLITE_OMIT_TRIGGER
98406   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
98407   isView = pTab->pSelect!=0;
98408   assert( pTrigger || tmask==0 );
98409 #else
98410 # define pTrigger 0
98411 # define isView 0
98412 # define tmask 0
98413 #endif
98414 #ifdef SQLITE_OMIT_VIEW
98415 # undef isView
98416 # define isView 0
98417 #endif
98418 
98419   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
98420     goto update_cleanup;
98421   }
98422   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
98423     goto update_cleanup;
98424   }
98425   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
98426   if( aXRef==0 ) goto update_cleanup;
98427   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
98428 
98429   /* Allocate a cursors for the main database table and for all indices.
98430   ** The index cursors might not be used, but if they are used they
98431   ** need to occur right after the database cursor.  So go ahead and
98432   ** allocate enough space, just in case.
98433   */
98434   pTabList->a[0].iCursor = iCur = pParse->nTab++;
98435   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98436     pParse->nTab++;
98437   }
98438 
98439   /* Initialize the name-context */
98440   memset(&sNC, 0, sizeof(sNC));
98441   sNC.pParse = pParse;
98442   sNC.pSrcList = pTabList;
98443 
98444   /* Resolve the column names in all the expressions of the
98445   ** of the UPDATE statement.  Also find the column index
98446   ** for each column to be updated in the pChanges array.  For each
98447   ** column to be updated, make sure we have authorization to change
98448   ** that column.
98449   */
98450   chngRowid = 0;
98451   for(i=0; i<pChanges->nExpr; i++){
98452     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
98453       goto update_cleanup;
98454     }
98455     for(j=0; j<pTab->nCol; j++){
98456       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
98457         if( j==pTab->iPKey ){
98458           chngRowid = 1;
98459           pRowidExpr = pChanges->a[i].pExpr;
98460         }
98461         aXRef[j] = i;
98462         break;
98463       }
98464     }
98465     if( j>=pTab->nCol ){
98466       if( sqlite3IsRowid(pChanges->a[i].zName) ){
98467         chngRowid = 1;
98468         pRowidExpr = pChanges->a[i].pExpr;
98469       }else{
98470         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
98471         pParse->checkSchema = 1;
98472         goto update_cleanup;
98473       }
98474     }
98475 #ifndef SQLITE_OMIT_AUTHORIZATION
98476     {
98477       int rc;
98478       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
98479                            pTab->aCol[j].zName, db->aDb[iDb].zName);
98480       if( rc==SQLITE_DENY ){
98481         goto update_cleanup;
98482       }else if( rc==SQLITE_IGNORE ){
98483         aXRef[j] = -1;
98484       }
98485     }
98486 #endif
98487   }
98488 
98489   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
98490 
98491   /* Allocate memory for the array aRegIdx[].  There is one entry in the
98492   ** array for each index associated with table being updated.  Fill in
98493   ** the value with a register number for indices that are to be used
98494   ** and with zero for unused indices.
98495   */
98496   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
98497   if( nIdx>0 ){
98498     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
98499     if( aRegIdx==0 ) goto update_cleanup;
98500   }
98501   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
98502     int reg;
98503     if( hasFK || chngRowid ){
98504       reg = ++pParse->nMem;
98505     }else{
98506       reg = 0;
98507       for(i=0; i<pIdx->nColumn; i++){
98508         if( aXRef[pIdx->aiColumn[i]]>=0 ){
98509           reg = ++pParse->nMem;
98510           break;
98511         }
98512       }
98513     }
98514     aRegIdx[j] = reg;
98515   }
98516 
98517   /* Begin generating code. */
98518   v = sqlite3GetVdbe(pParse);
98519   if( v==0 ) goto update_cleanup;
98520   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
98521   sqlite3BeginWriteOperation(pParse, 1, iDb);
98522 
98523 #ifndef SQLITE_OMIT_VIRTUALTABLE
98524   /* Virtual tables must be handled separately */
98525   if( IsVirtual(pTab) ){
98526     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
98527                        pWhere, onError);
98528     pWhere = 0;
98529     pTabList = 0;
98530     goto update_cleanup;
98531   }
98532 #endif
98533 
98534   /* Allocate required registers. */
98535   regOldRowid = regNewRowid = ++pParse->nMem;
98536   if( pTrigger || hasFK ){
98537     regOld = pParse->nMem + 1;
98538     pParse->nMem += pTab->nCol;
98539   }
98540   if( chngRowid || pTrigger || hasFK ){
98541     regNewRowid = ++pParse->nMem;
98542   }
98543   regNew = pParse->nMem + 1;
98544   pParse->nMem += pTab->nCol;
98545 
98546   /* Start the view context. */
98547   if( isView ){
98548     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
98549   }
98550 
98551   /* If we are trying to update a view, realize that view into
98552   ** a ephemeral table.
98553   */
98554 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
98555   if( isView ){
98556     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
98557   }
98558 #endif
98559 
98560   /* Resolve the column names in all the expressions in the
98561   ** WHERE clause.
98562   */
98563   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
98564     goto update_cleanup;
98565   }
98566 
98567   /* Begin the database scan
98568   */
98569   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
98570   pWInfo = sqlite3WhereBegin(
98571       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
98572   );
98573   if( pWInfo==0 ) goto update_cleanup;
98574   okOnePass = pWInfo->okOnePass;
98575 
98576   /* Remember the rowid of every item to be updated.
98577   */
98578   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
98579   if( !okOnePass ){
98580     regRowSet = ++pParse->nMem;
98581     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
98582   }
98583 
98584   /* End the database scan loop.
98585   */
98586   sqlite3WhereEnd(pWInfo);
98587 
98588   /* Initialize the count of updated rows
98589   */
98590   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
98591     regRowCount = ++pParse->nMem;
98592     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
98593   }
98594 
98595   if( !isView ){
98596     /*
98597     ** Open every index that needs updating.  Note that if any
98598     ** index could potentially invoke a REPLACE conflict resolution
98599     ** action, then we need to open all indices because we might need
98600     ** to be deleting some records.
98601     */
98602     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
98603     if( onError==OE_Replace ){
98604       openAll = 1;
98605     }else{
98606       openAll = 0;
98607       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98608         if( pIdx->onError==OE_Replace ){
98609           openAll = 1;
98610           break;
98611         }
98612       }
98613     }
98614     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
98615       if( openAll || aRegIdx[i]>0 ){
98616         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
98617         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
98618                        (char*)pKey, P4_KEYINFO_HANDOFF);
98619         assert( pParse->nTab>iCur+i+1 );
98620       }
98621     }
98622   }
98623 
98624   /* Top of the update loop */
98625   if( okOnePass ){
98626     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
98627     addr = sqlite3VdbeAddOp0(v, OP_Goto);
98628     sqlite3VdbeJumpHere(v, a1);
98629   }else{
98630     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
98631   }
98632 
98633   /* Make cursor iCur point to the record that is being updated. If
98634   ** this record does not exist for some reason (deleted by a trigger,
98635   ** for example, then jump to the next iteration of the RowSet loop.  */
98636   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
98637 
98638   /* If the record number will change, set register regNewRowid to
98639   ** contain the new value. If the record number is not being modified,
98640   ** then regNewRowid is the same register as regOldRowid, which is
98641   ** already populated.  */
98642   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
98643   if( chngRowid ){
98644     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
98645     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
98646   }
98647 
98648   /* If there are triggers on this table, populate an array of registers
98649   ** with the required old.* column data.  */
98650   if( hasFK || pTrigger ){
98651     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
98652     oldmask |= sqlite3TriggerColmask(pParse,
98653         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
98654     );
98655     for(i=0; i<pTab->nCol; i++){
98656       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
98657         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
98658       }else{
98659         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
98660       }
98661     }
98662     if( chngRowid==0 ){
98663       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
98664     }
98665   }
98666 
98667   /* Populate the array of registers beginning at regNew with the new
98668   ** row data. This array is used to check constaints, create the new
98669   ** table and index records, and as the values for any new.* references
98670   ** made by triggers.
98671   **
98672   ** If there are one or more BEFORE triggers, then do not populate the
98673   ** registers associated with columns that are (a) not modified by
98674   ** this UPDATE statement and (b) not accessed by new.* references. The
98675   ** values for registers not modified by the UPDATE must be reloaded from
98676   ** the database after the BEFORE triggers are fired anyway (as the trigger
98677   ** may have modified them). So not loading those that are not going to
98678   ** be used eliminates some redundant opcodes.
98679   */
98680   newmask = sqlite3TriggerColmask(
98681       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
98682   );
98683   for(i=0; i<pTab->nCol; i++){
98684     if( i==pTab->iPKey ){
98685       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
98686     }else{
98687       j = aXRef[i];
98688       if( j>=0 ){
98689         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
98690       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
98691         /* This branch loads the value of a column that will not be changed
98692         ** into a register. This is done if there are no BEFORE triggers, or
98693         ** if there are one or more BEFORE triggers that use this value via
98694         ** a new.* reference in a trigger program.
98695         */
98696         testcase( i==31 );
98697         testcase( i==32 );
98698         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
98699         sqlite3ColumnDefault(v, pTab, i, regNew+i);
98700       }
98701     }
98702   }
98703 
98704   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
98705   ** verified. One could argue that this is wrong.
98706   */
98707   if( tmask&TRIGGER_BEFORE ){
98708     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
98709     sqlite3TableAffinityStr(v, pTab);
98710     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
98711         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
98712 
98713     /* The row-trigger may have deleted the row being updated. In this
98714     ** case, jump to the next row. No updates or AFTER triggers are
98715     ** required. This behaviour - what happens when the row being updated
98716     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
98717     ** documentation.
98718     */
98719     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
98720 
98721     /* If it did not delete it, the row-trigger may still have modified
98722     ** some of the columns of the row being updated. Load the values for
98723     ** all columns not modified by the update statement into their
98724     ** registers in case this has happened.
98725     */
98726     for(i=0; i<pTab->nCol; i++){
98727       if( aXRef[i]<0 && i!=pTab->iPKey ){
98728         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
98729         sqlite3ColumnDefault(v, pTab, i, regNew+i);
98730       }
98731     }
98732   }
98733 
98734   if( !isView ){
98735     int j1;                       /* Address of jump instruction */
98736 
98737     /* Do constraint checks. */
98738     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
98739         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
98740 
98741     /* Do FK constraint checks. */
98742     if( hasFK ){
98743       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
98744     }
98745 
98746     /* Delete the index entries associated with the current record.  */
98747     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
98748     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
98749 
98750     /* If changing the record number, delete the old record.  */
98751     if( hasFK || chngRowid ){
98752       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
98753     }
98754     sqlite3VdbeJumpHere(v, j1);
98755 
98756     if( hasFK ){
98757       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
98758     }
98759 
98760     /* Insert the new index entries and the new record. */
98761     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
98762 
98763     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
98764     ** handle rows (possibly in other tables) that refer via a foreign key
98765     ** to the row just updated. */
98766     if( hasFK ){
98767       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
98768     }
98769   }
98770 
98771   /* Increment the row counter
98772   */
98773   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
98774     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
98775   }
98776 
98777   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
98778       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
98779 
98780   /* Repeat the above with the next record to be updated, until
98781   ** all record selected by the WHERE clause have been updated.
98782   */
98783   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
98784   sqlite3VdbeJumpHere(v, addr);
98785 
98786   /* Close all tables */
98787   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
98788     if( openAll || aRegIdx[i]>0 ){
98789       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
98790     }
98791   }
98792   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
98793 
98794   /* Update the sqlite_sequence table by storing the content of the
98795   ** maximum rowid counter values recorded while inserting into
98796   ** autoincrement tables.
98797   */
98798   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
98799     sqlite3AutoincrementEnd(pParse);
98800   }
98801 
98802   /*
98803   ** Return the number of rows that were changed. If this routine is
98804   ** generating code because of a call to sqlite3NestedParse(), do not
98805   ** invoke the callback function.
98806   */
98807   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
98808     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
98809     sqlite3VdbeSetNumCols(v, 1);
98810     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
98811   }
98812 
98813 update_cleanup:
98814   sqlite3AuthContextPop(&sContext);
98815   sqlite3DbFree(db, aRegIdx);
98816   sqlite3DbFree(db, aXRef);
98817   sqlite3SrcListDelete(db, pTabList);
98818   sqlite3ExprListDelete(db, pChanges);
98819   sqlite3ExprDelete(db, pWhere);
98820   return;
98821 }
98822 /* Make sure "isView" and other macros defined above are undefined. Otherwise
98823 ** thely may interfere with compilation of other functions in this file
98824 ** (or in another file, if this file becomes part of the amalgamation).  */
98825 #ifdef isView
98826  #undef isView
98827 #endif
98828 #ifdef pTrigger
98829  #undef pTrigger
98830 #endif
98831 
98832 #ifndef SQLITE_OMIT_VIRTUALTABLE
98833 /*
98834 ** Generate code for an UPDATE of a virtual table.
98835 **
98836 ** The strategy is that we create an ephemerial table that contains
98837 ** for each row to be changed:
98838 **
98839 **   (A)  The original rowid of that row.
98840 **   (B)  The revised rowid for the row. (note1)
98841 **   (C)  The content of every column in the row.
98842 **
98843 ** Then we loop over this ephemeral table and for each row in
98844 ** the ephermeral table call VUpdate.
98845 **
98846 ** When finished, drop the ephemeral table.
98847 **
98848 ** (note1) Actually, if we know in advance that (A) is always the same
98849 ** as (B) we only store (A), then duplicate (A) when pulling
98850 ** it out of the ephemeral table before calling VUpdate.
98851 */
98852 static void updateVirtualTable(
98853   Parse *pParse,       /* The parsing context */
98854   SrcList *pSrc,       /* The virtual table to be modified */
98855   Table *pTab,         /* The virtual table */
98856   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
98857   Expr *pRowid,        /* Expression used to recompute the rowid */
98858   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
98859   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
98860   int onError          /* ON CONFLICT strategy */
98861 ){
98862   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
98863   ExprList *pEList = 0;     /* The result set of the SELECT statement */
98864   Select *pSelect = 0;      /* The SELECT statement */
98865   Expr *pExpr;              /* Temporary expression */
98866   int ephemTab;             /* Table holding the result of the SELECT */
98867   int i;                    /* Loop counter */
98868   int addr;                 /* Address of top of loop */
98869   int iReg;                 /* First register in set passed to OP_VUpdate */
98870   sqlite3 *db = pParse->db; /* Database connection */
98871   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
98872   SelectDest dest;
98873 
98874   /* Construct the SELECT statement that will find the new values for
98875   ** all updated rows.
98876   */
98877   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
98878   if( pRowid ){
98879     pEList = sqlite3ExprListAppend(pParse, pEList,
98880                                    sqlite3ExprDup(db, pRowid, 0));
98881   }
98882   assert( pTab->iPKey<0 );
98883   for(i=0; i<pTab->nCol; i++){
98884     if( aXRef[i]>=0 ){
98885       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
98886     }else{
98887       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
98888     }
98889     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
98890   }
98891   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
98892 
98893   /* Create the ephemeral table into which the update results will
98894   ** be stored.
98895   */
98896   assert( v );
98897   ephemTab = pParse->nTab++;
98898   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
98899   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98900 
98901   /* fill the ephemeral table
98902   */
98903   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
98904   sqlite3Select(pParse, pSelect, &dest);
98905 
98906   /* Generate code to scan the ephemeral table and call VUpdate. */
98907   iReg = ++pParse->nMem;
98908   pParse->nMem += pTab->nCol+1;
98909   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
98910   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
98911   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
98912   for(i=0; i<pTab->nCol; i++){
98913     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
98914   }
98915   sqlite3VtabMakeWritable(pParse, pTab);
98916   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
98917   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
98918   sqlite3MayAbort(pParse);
98919   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
98920   sqlite3VdbeJumpHere(v, addr);
98921   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
98922 
98923   /* Cleanup */
98924   sqlite3SelectDelete(db, pSelect);
98925 }
98926 #endif /* SQLITE_OMIT_VIRTUALTABLE */
98927 
98928 /************** End of update.c **********************************************/
98929 /************** Begin file vacuum.c ******************************************/
98930 /*
98931 ** 2003 April 6
98932 **
98933 ** The author disclaims copyright to this source code.  In place of
98934 ** a legal notice, here is a blessing:
98935 **
98936 **    May you do good and not evil.
98937 **    May you find forgiveness for yourself and forgive others.
98938 **    May you share freely, never taking more than you give.
98939 **
98940 *************************************************************************
98941 ** This file contains code used to implement the VACUUM command.
98942 **
98943 ** Most of the code in this file may be omitted by defining the
98944 ** SQLITE_OMIT_VACUUM macro.
98945 */
98946 
98947 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
98948 /*
98949 ** Finalize a prepared statement.  If there was an error, store the
98950 ** text of the error message in *pzErrMsg.  Return the result code.
98951 */
98952 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
98953   int rc;
98954   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
98955   if( rc ){
98956     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
98957   }
98958   return rc;
98959 }
98960 
98961 /*
98962 ** Execute zSql on database db. Return an error code.
98963 */
98964 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
98965   sqlite3_stmt *pStmt;
98966   VVA_ONLY( int rc; )
98967   if( !zSql ){
98968     return SQLITE_NOMEM;
98969   }
98970   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
98971     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
98972     return sqlite3_errcode(db);
98973   }
98974   VVA_ONLY( rc = ) sqlite3_step(pStmt);
98975   assert( rc!=SQLITE_ROW );
98976   return vacuumFinalize(db, pStmt, pzErrMsg);
98977 }
98978 
98979 /*
98980 ** Execute zSql on database db. The statement returns exactly
98981 ** one column. Execute this as SQL on the same database.
98982 */
98983 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
98984   sqlite3_stmt *pStmt;
98985   int rc;
98986 
98987   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
98988   if( rc!=SQLITE_OK ) return rc;
98989 
98990   while( SQLITE_ROW==sqlite3_step(pStmt) ){
98991     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
98992     if( rc!=SQLITE_OK ){
98993       vacuumFinalize(db, pStmt, pzErrMsg);
98994       return rc;
98995     }
98996   }
98997 
98998   return vacuumFinalize(db, pStmt, pzErrMsg);
98999 }
99000 
99001 /*
99002 ** The non-standard VACUUM command is used to clean up the database,
99003 ** collapse free space, etc.  It is modelled after the VACUUM command
99004 ** in PostgreSQL.
99005 **
99006 ** In version 1.0.x of SQLite, the VACUUM command would call
99007 ** gdbm_reorganize() on all the database tables.  But beginning
99008 ** with 2.0.0, SQLite no longer uses GDBM so this command has
99009 ** become a no-op.
99010 */
99011 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
99012   Vdbe *v = sqlite3GetVdbe(pParse);
99013   if( v ){
99014     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
99015   }
99016   return;
99017 }
99018 
99019 /*
99020 ** This routine implements the OP_Vacuum opcode of the VDBE.
99021 */
99022 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
99023   int rc = SQLITE_OK;     /* Return code from service routines */
99024   Btree *pMain;           /* The database being vacuumed */
99025   Btree *pTemp;           /* The temporary database we vacuum into */
99026   char *zSql = 0;         /* SQL statements */
99027   int saved_flags;        /* Saved value of the db->flags */
99028   int saved_nChange;      /* Saved value of db->nChange */
99029   int saved_nTotalChange; /* Saved value of db->nTotalChange */
99030   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
99031   Db *pDb = 0;            /* Database to detach at end of vacuum */
99032   int isMemDb;            /* True if vacuuming a :memory: database */
99033   int nRes;               /* Bytes of reserved space at the end of each page */
99034   int nDb;                /* Number of attached databases */
99035 
99036   if( !db->autoCommit ){
99037     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
99038     return SQLITE_ERROR;
99039   }
99040   if( db->activeVdbeCnt>1 ){
99041     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
99042     return SQLITE_ERROR;
99043   }
99044 
99045   /* Save the current value of the database flags so that it can be
99046   ** restored before returning. Then set the writable-schema flag, and
99047   ** disable CHECK and foreign key constraints.  */
99048   saved_flags = db->flags;
99049   saved_nChange = db->nChange;
99050   saved_nTotalChange = db->nTotalChange;
99051   saved_xTrace = db->xTrace;
99052   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
99053   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
99054   db->xTrace = 0;
99055 
99056   pMain = db->aDb[0].pBt;
99057   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
99058 
99059   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
99060   ** can be set to 'off' for this file, as it is not recovered if a crash
99061   ** occurs anyway. The integrity of the database is maintained by a
99062   ** (possibly synchronous) transaction opened on the main database before
99063   ** sqlite3BtreeCopyFile() is called.
99064   **
99065   ** An optimisation would be to use a non-journaled pager.
99066   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
99067   ** that actually made the VACUUM run slower.  Very little journalling
99068   ** actually occurs when doing a vacuum since the vacuum_db is initially
99069   ** empty.  Only the journal header is written.  Apparently it takes more
99070   ** time to parse and run the PRAGMA to turn journalling off than it does
99071   ** to write the journal header file.
99072   */
99073   nDb = db->nDb;
99074   if( sqlite3TempInMemory(db) ){
99075     zSql = "ATTACH ':memory:' AS vacuum_db;";
99076   }else{
99077     zSql = "ATTACH '' AS vacuum_db;";
99078   }
99079   rc = execSql(db, pzErrMsg, zSql);
99080   if( db->nDb>nDb ){
99081     pDb = &db->aDb[db->nDb-1];
99082     assert( strcmp(pDb->zName,"vacuum_db")==0 );
99083   }
99084   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99085   pTemp = db->aDb[db->nDb-1].pBt;
99086 
99087   /* The call to execSql() to attach the temp database has left the file
99088   ** locked (as there was more than one active statement when the transaction
99089   ** to read the schema was concluded. Unlock it here so that this doesn't
99090   ** cause problems for the call to BtreeSetPageSize() below.  */
99091   sqlite3BtreeCommit(pTemp);
99092 
99093   nRes = sqlite3BtreeGetReserve(pMain);
99094 
99095   /* A VACUUM cannot change the pagesize of an encrypted database. */
99096 #ifdef SQLITE_HAS_CODEC
99097   if( db->nextPagesize ){
99098     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
99099     int nKey;
99100     char *zKey;
99101     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
99102     if( nKey ) db->nextPagesize = 0;
99103   }
99104 #endif
99105 
99106   /* Do not attempt to change the page size for a WAL database */
99107   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
99108                                                ==PAGER_JOURNALMODE_WAL ){
99109     db->nextPagesize = 0;
99110   }
99111 
99112   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
99113    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
99114    || NEVER(db->mallocFailed)
99115   ){
99116     rc = SQLITE_NOMEM;
99117     goto end_of_vacuum;
99118   }
99119   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
99120   if( rc!=SQLITE_OK ){
99121     goto end_of_vacuum;
99122   }
99123 
99124 #ifndef SQLITE_OMIT_AUTOVACUUM
99125   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
99126                                            sqlite3BtreeGetAutoVacuum(pMain));
99127 #endif
99128 
99129   /* Begin a transaction */
99130   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
99131   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99132 
99133   /* Query the schema of the main database. Create a mirror schema
99134   ** in the temporary database.
99135   */
99136   rc = execExecSql(db, pzErrMsg,
99137       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
99138       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
99139       "   AND rootpage>0"
99140   );
99141   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99142   rc = execExecSql(db, pzErrMsg,
99143       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
99144       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
99145   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99146   rc = execExecSql(db, pzErrMsg,
99147       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
99148       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
99149   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99150 
99151   /* Loop through the tables in the main database. For each, do
99152   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
99153   ** the contents to the temporary database.
99154   */
99155   rc = execExecSql(db, pzErrMsg,
99156       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
99157       "|| ' SELECT * FROM main.' || quote(name) || ';'"
99158       "FROM main.sqlite_master "
99159       "WHERE type = 'table' AND name!='sqlite_sequence' "
99160       "  AND rootpage>0"
99161   );
99162   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99163 
99164   /* Copy over the sequence table
99165   */
99166   rc = execExecSql(db, pzErrMsg,
99167       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
99168       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
99169   );
99170   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99171   rc = execExecSql(db, pzErrMsg,
99172       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
99173       "|| ' SELECT * FROM main.' || quote(name) || ';' "
99174       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
99175   );
99176   if( rc!=SQLITE_OK ) goto end_of_vacuum;
99177 
99178 
99179   /* Copy the triggers, views, and virtual tables from the main database
99180   ** over to the temporary database.  None of these objects has any
99181   ** associated storage, so all we have to do is copy their entries
99182   ** from the SQLITE_MASTER table.
99183   */
99184   rc = execSql(db, pzErrMsg,
99185       "INSERT INTO vacuum_db.sqlite_master "
99186       "  SELECT type, name, tbl_name, rootpage, sql"
99187       "    FROM main.sqlite_master"
99188       "   WHERE type='view' OR type='trigger'"
99189       "      OR (type='table' AND rootpage=0)"
99190   );
99191   if( rc ) goto end_of_vacuum;
99192 
99193   /* At this point, unless the main db was completely empty, there is now a
99194   ** transaction open on the vacuum database, but not on the main database.
99195   ** Open a btree level transaction on the main database. This allows a
99196   ** call to sqlite3BtreeCopyFile(). The main database btree level
99197   ** transaction is then committed, so the SQL level never knows it was
99198   ** opened for writing. This way, the SQL transaction used to create the
99199   ** temporary database never needs to be committed.
99200   */
99201   {
99202     u32 meta;
99203     int i;
99204 
99205     /* This array determines which meta meta values are preserved in the
99206     ** vacuum.  Even entries are the meta value number and odd entries
99207     ** are an increment to apply to the meta value after the vacuum.
99208     ** The increment is used to increase the schema cookie so that other
99209     ** connections to the same database will know to reread the schema.
99210     */
99211     static const unsigned char aCopy[] = {
99212        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
99213        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
99214        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
99215        BTREE_USER_VERSION,       0,  /* Preserve the user version */
99216     };
99217 
99218     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
99219     assert( 1==sqlite3BtreeIsInTrans(pMain) );
99220 
99221     /* Copy Btree meta values */
99222     for(i=0; i<ArraySize(aCopy); i+=2){
99223       /* GetMeta() and UpdateMeta() cannot fail in this context because
99224       ** we already have page 1 loaded into cache and marked dirty. */
99225       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
99226       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
99227       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
99228     }
99229 
99230     rc = sqlite3BtreeCopyFile(pMain, pTemp);
99231     if( rc!=SQLITE_OK ) goto end_of_vacuum;
99232     rc = sqlite3BtreeCommit(pTemp);
99233     if( rc!=SQLITE_OK ) goto end_of_vacuum;
99234 #ifndef SQLITE_OMIT_AUTOVACUUM
99235     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
99236 #endif
99237   }
99238 
99239   assert( rc==SQLITE_OK );
99240   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
99241 
99242 end_of_vacuum:
99243   /* Restore the original value of db->flags */
99244   db->flags = saved_flags;
99245   db->nChange = saved_nChange;
99246   db->nTotalChange = saved_nTotalChange;
99247   db->xTrace = saved_xTrace;
99248   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
99249 
99250   /* Currently there is an SQL level transaction open on the vacuum
99251   ** database. No locks are held on any other files (since the main file
99252   ** was committed at the btree level). So it safe to end the transaction
99253   ** by manually setting the autoCommit flag to true and detaching the
99254   ** vacuum database. The vacuum_db journal file is deleted when the pager
99255   ** is closed by the DETACH.
99256   */
99257   db->autoCommit = 1;
99258 
99259   if( pDb ){
99260     sqlite3BtreeClose(pDb->pBt);
99261     pDb->pBt = 0;
99262     pDb->pSchema = 0;
99263   }
99264 
99265   /* This both clears the schemas and reduces the size of the db->aDb[]
99266   ** array. */
99267   sqlite3ResetInternalSchema(db, -1);
99268 
99269   return rc;
99270 }
99271 
99272 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
99273 
99274 /************** End of vacuum.c **********************************************/
99275 /************** Begin file vtab.c ********************************************/
99276 /*
99277 ** 2006 June 10
99278 **
99279 ** The author disclaims copyright to this source code.  In place of
99280 ** a legal notice, here is a blessing:
99281 **
99282 **    May you do good and not evil.
99283 **    May you find forgiveness for yourself and forgive others.
99284 **    May you share freely, never taking more than you give.
99285 **
99286 *************************************************************************
99287 ** This file contains code used to help implement virtual tables.
99288 */
99289 #ifndef SQLITE_OMIT_VIRTUALTABLE
99290 
99291 /*
99292 ** Before a virtual table xCreate() or xConnect() method is invoked, the
99293 ** sqlite3.pVtabCtx member variable is set to point to an instance of
99294 ** this struct allocated on the stack. It is used by the implementation of
99295 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
99296 ** are invoked only from within xCreate and xConnect methods.
99297 */
99298 struct VtabCtx {
99299   Table *pTab;
99300   VTable *pVTable;
99301 };
99302 
99303 /*
99304 ** The actual function that does the work of creating a new module.
99305 ** This function implements the sqlite3_create_module() and
99306 ** sqlite3_create_module_v2() interfaces.
99307 */
99308 static int createModule(
99309   sqlite3 *db,                    /* Database in which module is registered */
99310   const char *zName,              /* Name assigned to this module */
99311   const sqlite3_module *pModule,  /* The definition of the module */
99312   void *pAux,                     /* Context pointer for xCreate/xConnect */
99313   void (*xDestroy)(void *)        /* Module destructor function */
99314 ){
99315   int rc, nName;
99316   Module *pMod;
99317 
99318   sqlite3_mutex_enter(db->mutex);
99319   nName = sqlite3Strlen30(zName);
99320   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
99321   if( pMod ){
99322     Module *pDel;
99323     char *zCopy = (char *)(&pMod[1]);
99324     memcpy(zCopy, zName, nName+1);
99325     pMod->zName = zCopy;
99326     pMod->pModule = pModule;
99327     pMod->pAux = pAux;
99328     pMod->xDestroy = xDestroy;
99329     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
99330     if( pDel && pDel->xDestroy ){
99331       sqlite3ResetInternalSchema(db, -1);
99332       pDel->xDestroy(pDel->pAux);
99333     }
99334     sqlite3DbFree(db, pDel);
99335     if( pDel==pMod ){
99336       db->mallocFailed = 1;
99337     }
99338   }else if( xDestroy ){
99339     xDestroy(pAux);
99340   }
99341   rc = sqlite3ApiExit(db, SQLITE_OK);
99342   sqlite3_mutex_leave(db->mutex);
99343   return rc;
99344 }
99345 
99346 
99347 /*
99348 ** External API function used to create a new virtual-table module.
99349 */
99350 SQLITE_API int sqlite3_create_module(
99351   sqlite3 *db,                    /* Database in which module is registered */
99352   const char *zName,              /* Name assigned to this module */
99353   const sqlite3_module *pModule,  /* The definition of the module */
99354   void *pAux                      /* Context pointer for xCreate/xConnect */
99355 ){
99356   return createModule(db, zName, pModule, pAux, 0);
99357 }
99358 
99359 /*
99360 ** External API function used to create a new virtual-table module.
99361 */
99362 SQLITE_API int sqlite3_create_module_v2(
99363   sqlite3 *db,                    /* Database in which module is registered */
99364   const char *zName,              /* Name assigned to this module */
99365   const sqlite3_module *pModule,  /* The definition of the module */
99366   void *pAux,                     /* Context pointer for xCreate/xConnect */
99367   void (*xDestroy)(void *)        /* Module destructor function */
99368 ){
99369   return createModule(db, zName, pModule, pAux, xDestroy);
99370 }
99371 
99372 /*
99373 ** Lock the virtual table so that it cannot be disconnected.
99374 ** Locks nest.  Every lock should have a corresponding unlock.
99375 ** If an unlock is omitted, resources leaks will occur.
99376 **
99377 ** If a disconnect is attempted while a virtual table is locked,
99378 ** the disconnect is deferred until all locks have been removed.
99379 */
99380 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
99381   pVTab->nRef++;
99382 }
99383 
99384 
99385 /*
99386 ** pTab is a pointer to a Table structure representing a virtual-table.
99387 ** Return a pointer to the VTable object used by connection db to access
99388 ** this virtual-table, if one has been created, or NULL otherwise.
99389 */
99390 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
99391   VTable *pVtab;
99392   assert( IsVirtual(pTab) );
99393   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
99394   return pVtab;
99395 }
99396 
99397 /*
99398 ** Decrement the ref-count on a virtual table object. When the ref-count
99399 ** reaches zero, call the xDisconnect() method to delete the object.
99400 */
99401 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
99402   sqlite3 *db = pVTab->db;
99403 
99404   assert( db );
99405   assert( pVTab->nRef>0 );
99406   assert( sqlite3SafetyCheckOk(db) );
99407 
99408   pVTab->nRef--;
99409   if( pVTab->nRef==0 ){
99410     sqlite3_vtab *p = pVTab->pVtab;
99411     if( p ){
99412       p->pModule->xDisconnect(p);
99413     }
99414     sqlite3DbFree(db, pVTab);
99415   }
99416 }
99417 
99418 /*
99419 ** Table p is a virtual table. This function moves all elements in the
99420 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
99421 ** database connections to be disconnected at the next opportunity.
99422 ** Except, if argument db is not NULL, then the entry associated with
99423 ** connection db is left in the p->pVTable list.
99424 */
99425 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
99426   VTable *pRet = 0;
99427   VTable *pVTable = p->pVTable;
99428   p->pVTable = 0;
99429 
99430   /* Assert that the mutex (if any) associated with the BtShared database
99431   ** that contains table p is held by the caller. See header comments
99432   ** above function sqlite3VtabUnlockList() for an explanation of why
99433   ** this makes it safe to access the sqlite3.pDisconnect list of any
99434   ** database connection that may have an entry in the p->pVTable list.
99435   */
99436   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
99437 
99438   while( pVTable ){
99439     sqlite3 *db2 = pVTable->db;
99440     VTable *pNext = pVTable->pNext;
99441     assert( db2 );
99442     if( db2==db ){
99443       pRet = pVTable;
99444       p->pVTable = pRet;
99445       pRet->pNext = 0;
99446     }else{
99447       pVTable->pNext = db2->pDisconnect;
99448       db2->pDisconnect = pVTable;
99449     }
99450     pVTable = pNext;
99451   }
99452 
99453   assert( !db || pRet );
99454   return pRet;
99455 }
99456 
99457 
99458 /*
99459 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
99460 **
99461 ** This function may only be called when the mutexes associated with all
99462 ** shared b-tree databases opened using connection db are held by the
99463 ** caller. This is done to protect the sqlite3.pDisconnect list. The
99464 ** sqlite3.pDisconnect list is accessed only as follows:
99465 **
99466 **   1) By this function. In this case, all BtShared mutexes and the mutex
99467 **      associated with the database handle itself must be held.
99468 **
99469 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
99470 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
99471 **      associated with the database the virtual table is stored in is held
99472 **      or, if the virtual table is stored in a non-sharable database, then
99473 **      the database handle mutex is held.
99474 **
99475 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
99476 ** by multiple threads. It is thread-safe.
99477 */
99478 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
99479   VTable *p = db->pDisconnect;
99480   db->pDisconnect = 0;
99481 
99482   assert( sqlite3BtreeHoldsAllMutexes(db) );
99483   assert( sqlite3_mutex_held(db->mutex) );
99484 
99485   if( p ){
99486     sqlite3ExpirePreparedStatements(db);
99487     do {
99488       VTable *pNext = p->pNext;
99489       sqlite3VtabUnlock(p);
99490       p = pNext;
99491     }while( p );
99492   }
99493 }
99494 
99495 /*
99496 ** Clear any and all virtual-table information from the Table record.
99497 ** This routine is called, for example, just before deleting the Table
99498 ** record.
99499 **
99500 ** Since it is a virtual-table, the Table structure contains a pointer
99501 ** to the head of a linked list of VTable structures. Each VTable
99502 ** structure is associated with a single sqlite3* user of the schema.
99503 ** The reference count of the VTable structure associated with database
99504 ** connection db is decremented immediately (which may lead to the
99505 ** structure being xDisconnected and free). Any other VTable structures
99506 ** in the list are moved to the sqlite3.pDisconnect list of the associated
99507 ** database connection.
99508 */
99509 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
99510   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
99511   if( p->azModuleArg ){
99512     int i;
99513     for(i=0; i<p->nModuleArg; i++){
99514       sqlite3DbFree(db, p->azModuleArg[i]);
99515     }
99516     sqlite3DbFree(db, p->azModuleArg);
99517   }
99518 }
99519 
99520 /*
99521 ** Add a new module argument to pTable->azModuleArg[].
99522 ** The string is not copied - the pointer is stored.  The
99523 ** string will be freed automatically when the table is
99524 ** deleted.
99525 */
99526 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
99527   int i = pTable->nModuleArg++;
99528   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
99529   char **azModuleArg;
99530   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
99531   if( azModuleArg==0 ){
99532     int j;
99533     for(j=0; j<i; j++){
99534       sqlite3DbFree(db, pTable->azModuleArg[j]);
99535     }
99536     sqlite3DbFree(db, zArg);
99537     sqlite3DbFree(db, pTable->azModuleArg);
99538     pTable->nModuleArg = 0;
99539   }else{
99540     azModuleArg[i] = zArg;
99541     azModuleArg[i+1] = 0;
99542   }
99543   pTable->azModuleArg = azModuleArg;
99544 }
99545 
99546 /*
99547 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
99548 ** statement.  The module name has been parsed, but the optional list
99549 ** of parameters that follow the module name are still pending.
99550 */
99551 SQLITE_PRIVATE void sqlite3VtabBeginParse(
99552   Parse *pParse,        /* Parsing context */
99553   Token *pName1,        /* Name of new table, or database name */
99554   Token *pName2,        /* Name of new table or NULL */
99555   Token *pModuleName    /* Name of the module for the virtual table */
99556 ){
99557   int iDb;              /* The database the table is being created in */
99558   Table *pTable;        /* The new virtual table */
99559   sqlite3 *db;          /* Database connection */
99560 
99561   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
99562   pTable = pParse->pNewTable;
99563   if( pTable==0 ) return;
99564   assert( 0==pTable->pIndex );
99565 
99566   db = pParse->db;
99567   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
99568   assert( iDb>=0 );
99569 
99570   pTable->tabFlags |= TF_Virtual;
99571   pTable->nModuleArg = 0;
99572   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
99573   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
99574   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
99575   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
99576 
99577 #ifndef SQLITE_OMIT_AUTHORIZATION
99578   /* Creating a virtual table invokes the authorization callback twice.
99579   ** The first invocation, to obtain permission to INSERT a row into the
99580   ** sqlite_master table, has already been made by sqlite3StartTable().
99581   ** The second call, to obtain permission to create the table, is made now.
99582   */
99583   if( pTable->azModuleArg ){
99584     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
99585             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
99586   }
99587 #endif
99588 }
99589 
99590 /*
99591 ** This routine takes the module argument that has been accumulating
99592 ** in pParse->zArg[] and appends it to the list of arguments on the
99593 ** virtual table currently under construction in pParse->pTable.
99594 */
99595 static void addArgumentToVtab(Parse *pParse){
99596   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
99597     const char *z = (const char*)pParse->sArg.z;
99598     int n = pParse->sArg.n;
99599     sqlite3 *db = pParse->db;
99600     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
99601   }
99602 }
99603 
99604 /*
99605 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
99606 ** has been completely parsed.
99607 */
99608 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
99609   Table *pTab = pParse->pNewTable;  /* The table being constructed */
99610   sqlite3 *db = pParse->db;         /* The database connection */
99611 
99612   if( pTab==0 ) return;
99613   addArgumentToVtab(pParse);
99614   pParse->sArg.z = 0;
99615   if( pTab->nModuleArg<1 ) return;
99616 
99617   /* If the CREATE VIRTUAL TABLE statement is being entered for the
99618   ** first time (in other words if the virtual table is actually being
99619   ** created now instead of just being read out of sqlite_master) then
99620   ** do additional initialization work and store the statement text
99621   ** in the sqlite_master table.
99622   */
99623   if( !db->init.busy ){
99624     char *zStmt;
99625     char *zWhere;
99626     int iDb;
99627     Vdbe *v;
99628 
99629     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
99630     if( pEnd ){
99631       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
99632     }
99633     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
99634 
99635     /* A slot for the record has already been allocated in the
99636     ** SQLITE_MASTER table.  We just need to update that slot with all
99637     ** the information we've collected.
99638     **
99639     ** The VM register number pParse->regRowid holds the rowid of an
99640     ** entry in the sqlite_master table tht was created for this vtab
99641     ** by sqlite3StartTable().
99642     */
99643     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99644     sqlite3NestedParse(pParse,
99645       "UPDATE %Q.%s "
99646          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
99647        "WHERE rowid=#%d",
99648       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
99649       pTab->zName,
99650       pTab->zName,
99651       zStmt,
99652       pParse->regRowid
99653     );
99654     sqlite3DbFree(db, zStmt);
99655     v = sqlite3GetVdbe(pParse);
99656     sqlite3ChangeCookie(pParse, iDb);
99657 
99658     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
99659     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
99660     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
99661     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
99662                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
99663   }
99664 
99665   /* If we are rereading the sqlite_master table create the in-memory
99666   ** record of the table. The xConnect() method is not called until
99667   ** the first time the virtual table is used in an SQL statement. This
99668   ** allows a schema that contains virtual tables to be loaded before
99669   ** the required virtual table implementations are registered.  */
99670   else {
99671     Table *pOld;
99672     Schema *pSchema = pTab->pSchema;
99673     const char *zName = pTab->zName;
99674     int nName = sqlite3Strlen30(zName);
99675     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
99676     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
99677     if( pOld ){
99678       db->mallocFailed = 1;
99679       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
99680       return;
99681     }
99682     pParse->pNewTable = 0;
99683   }
99684 }
99685 
99686 /*
99687 ** The parser calls this routine when it sees the first token
99688 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
99689 */
99690 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
99691   addArgumentToVtab(pParse);
99692   pParse->sArg.z = 0;
99693   pParse->sArg.n = 0;
99694 }
99695 
99696 /*
99697 ** The parser calls this routine for each token after the first token
99698 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
99699 */
99700 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
99701   Token *pArg = &pParse->sArg;
99702   if( pArg->z==0 ){
99703     pArg->z = p->z;
99704     pArg->n = p->n;
99705   }else{
99706     assert(pArg->z < p->z);
99707     pArg->n = (int)(&p->z[p->n] - pArg->z);
99708   }
99709 }
99710 
99711 /*
99712 ** Invoke a virtual table constructor (either xCreate or xConnect). The
99713 ** pointer to the function to invoke is passed as the fourth parameter
99714 ** to this procedure.
99715 */
99716 static int vtabCallConstructor(
99717   sqlite3 *db,
99718   Table *pTab,
99719   Module *pMod,
99720   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
99721   char **pzErr
99722 ){
99723   VtabCtx sCtx;
99724   VTable *pVTable;
99725   int rc;
99726   const char *const*azArg = (const char *const*)pTab->azModuleArg;
99727   int nArg = pTab->nModuleArg;
99728   char *zErr = 0;
99729   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
99730 
99731   if( !zModuleName ){
99732     return SQLITE_NOMEM;
99733   }
99734 
99735   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
99736   if( !pVTable ){
99737     sqlite3DbFree(db, zModuleName);
99738     return SQLITE_NOMEM;
99739   }
99740   pVTable->db = db;
99741   pVTable->pMod = pMod;
99742 
99743   /* Invoke the virtual table constructor */
99744   assert( &db->pVtabCtx );
99745   assert( xConstruct );
99746   sCtx.pTab = pTab;
99747   sCtx.pVTable = pVTable;
99748   db->pVtabCtx = &sCtx;
99749   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
99750   db->pVtabCtx = 0;
99751   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
99752 
99753   if( SQLITE_OK!=rc ){
99754     if( zErr==0 ){
99755       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
99756     }else {
99757       *pzErr = sqlite3MPrintf(db, "%s", zErr);
99758       sqlite3_free(zErr);
99759     }
99760     sqlite3DbFree(db, pVTable);
99761   }else if( ALWAYS(pVTable->pVtab) ){
99762     /* Justification of ALWAYS():  A correct vtab constructor must allocate
99763     ** the sqlite3_vtab object if successful.  */
99764     pVTable->pVtab->pModule = pMod->pModule;
99765     pVTable->nRef = 1;
99766     if( sCtx.pTab ){
99767       const char *zFormat = "vtable constructor did not declare schema: %s";
99768       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
99769       sqlite3VtabUnlock(pVTable);
99770       rc = SQLITE_ERROR;
99771     }else{
99772       int iCol;
99773       /* If everything went according to plan, link the new VTable structure
99774       ** into the linked list headed by pTab->pVTable. Then loop through the
99775       ** columns of the table to see if any of them contain the token "hidden".
99776       ** If so, set the Column.isHidden flag and remove the token from
99777       ** the type string.  */
99778       pVTable->pNext = pTab->pVTable;
99779       pTab->pVTable = pVTable;
99780 
99781       for(iCol=0; iCol<pTab->nCol; iCol++){
99782         char *zType = pTab->aCol[iCol].zType;
99783         int nType;
99784         int i = 0;
99785         if( !zType ) continue;
99786         nType = sqlite3Strlen30(zType);
99787         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
99788           for(i=0; i<nType; i++){
99789             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
99790              && (zType[i+7]=='\0' || zType[i+7]==' ')
99791             ){
99792               i++;
99793               break;
99794             }
99795           }
99796         }
99797         if( i<nType ){
99798           int j;
99799           int nDel = 6 + (zType[i+6] ? 1 : 0);
99800           for(j=i; (j+nDel)<=nType; j++){
99801             zType[j] = zType[j+nDel];
99802           }
99803           if( zType[i]=='\0' && i>0 ){
99804             assert(zType[i-1]==' ');
99805             zType[i-1] = '\0';
99806           }
99807           pTab->aCol[iCol].isHidden = 1;
99808         }
99809       }
99810     }
99811   }
99812 
99813   sqlite3DbFree(db, zModuleName);
99814   return rc;
99815 }
99816 
99817 /*
99818 ** This function is invoked by the parser to call the xConnect() method
99819 ** of the virtual table pTab. If an error occurs, an error code is returned
99820 ** and an error left in pParse.
99821 **
99822 ** This call is a no-op if table pTab is not a virtual table.
99823 */
99824 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
99825   sqlite3 *db = pParse->db;
99826   const char *zMod;
99827   Module *pMod;
99828   int rc;
99829 
99830   assert( pTab );
99831   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
99832     return SQLITE_OK;
99833   }
99834 
99835   /* Locate the required virtual table module */
99836   zMod = pTab->azModuleArg[0];
99837   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
99838 
99839   if( !pMod ){
99840     const char *zModule = pTab->azModuleArg[0];
99841     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
99842     rc = SQLITE_ERROR;
99843   }else{
99844     char *zErr = 0;
99845     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
99846     if( rc!=SQLITE_OK ){
99847       sqlite3ErrorMsg(pParse, "%s", zErr);
99848     }
99849     sqlite3DbFree(db, zErr);
99850   }
99851 
99852   return rc;
99853 }
99854 /*
99855 ** Grow the db->aVTrans[] array so that there is room for at least one
99856 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
99857 */
99858 static int growVTrans(sqlite3 *db){
99859   const int ARRAY_INCR = 5;
99860 
99861   /* Grow the sqlite3.aVTrans array if required */
99862   if( (db->nVTrans%ARRAY_INCR)==0 ){
99863     VTable **aVTrans;
99864     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
99865     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
99866     if( !aVTrans ){
99867       return SQLITE_NOMEM;
99868     }
99869     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
99870     db->aVTrans = aVTrans;
99871   }
99872 
99873   return SQLITE_OK;
99874 }
99875 
99876 /*
99877 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
99878 ** have already been reserved using growVTrans().
99879 */
99880 static void addToVTrans(sqlite3 *db, VTable *pVTab){
99881   /* Add pVtab to the end of sqlite3.aVTrans */
99882   db->aVTrans[db->nVTrans++] = pVTab;
99883   sqlite3VtabLock(pVTab);
99884 }
99885 
99886 /*
99887 ** This function is invoked by the vdbe to call the xCreate method
99888 ** of the virtual table named zTab in database iDb.
99889 **
99890 ** If an error occurs, *pzErr is set to point an an English language
99891 ** description of the error and an SQLITE_XXX error code is returned.
99892 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
99893 */
99894 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
99895   int rc = SQLITE_OK;
99896   Table *pTab;
99897   Module *pMod;
99898   const char *zMod;
99899 
99900   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
99901   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
99902 
99903   /* Locate the required virtual table module */
99904   zMod = pTab->azModuleArg[0];
99905   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
99906 
99907   /* If the module has been registered and includes a Create method,
99908   ** invoke it now. If the module has not been registered, return an
99909   ** error. Otherwise, do nothing.
99910   */
99911   if( !pMod ){
99912     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
99913     rc = SQLITE_ERROR;
99914   }else{
99915     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
99916   }
99917 
99918   /* Justification of ALWAYS():  The xConstructor method is required to
99919   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
99920   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
99921     rc = growVTrans(db);
99922     if( rc==SQLITE_OK ){
99923       addToVTrans(db, sqlite3GetVTable(db, pTab));
99924     }
99925   }
99926 
99927   return rc;
99928 }
99929 
99930 /*
99931 ** This function is used to set the schema of a virtual table.  It is only
99932 ** valid to call this function from within the xCreate() or xConnect() of a
99933 ** virtual table module.
99934 */
99935 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
99936   Parse *pParse;
99937 
99938   int rc = SQLITE_OK;
99939   Table *pTab;
99940   char *zErr = 0;
99941 
99942   sqlite3_mutex_enter(db->mutex);
99943   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
99944     sqlite3Error(db, SQLITE_MISUSE, 0);
99945     sqlite3_mutex_leave(db->mutex);
99946     return SQLITE_MISUSE_BKPT;
99947   }
99948   assert( (pTab->tabFlags & TF_Virtual)!=0 );
99949 
99950   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
99951   if( pParse==0 ){
99952     rc = SQLITE_NOMEM;
99953   }else{
99954     pParse->declareVtab = 1;
99955     pParse->db = db;
99956     pParse->nQueryLoop = 1;
99957 
99958     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
99959      && pParse->pNewTable
99960      && !db->mallocFailed
99961      && !pParse->pNewTable->pSelect
99962      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
99963     ){
99964       if( !pTab->aCol ){
99965         pTab->aCol = pParse->pNewTable->aCol;
99966         pTab->nCol = pParse->pNewTable->nCol;
99967         pParse->pNewTable->nCol = 0;
99968         pParse->pNewTable->aCol = 0;
99969       }
99970       db->pVtabCtx->pTab = 0;
99971     }else{
99972       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
99973       sqlite3DbFree(db, zErr);
99974       rc = SQLITE_ERROR;
99975     }
99976     pParse->declareVtab = 0;
99977 
99978     if( pParse->pVdbe ){
99979       sqlite3VdbeFinalize(pParse->pVdbe);
99980     }
99981     sqlite3DeleteTable(db, pParse->pNewTable);
99982     sqlite3StackFree(db, pParse);
99983   }
99984 
99985   assert( (rc&0xff)==rc );
99986   rc = sqlite3ApiExit(db, rc);
99987   sqlite3_mutex_leave(db->mutex);
99988   return rc;
99989 }
99990 
99991 /*
99992 ** This function is invoked by the vdbe to call the xDestroy method
99993 ** of the virtual table named zTab in database iDb. This occurs
99994 ** when a DROP TABLE is mentioned.
99995 **
99996 ** This call is a no-op if zTab is not a virtual table.
99997 */
99998 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
99999   int rc = SQLITE_OK;
100000   Table *pTab;
100001 
100002   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
100003   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
100004     VTable *p = vtabDisconnectAll(db, pTab);
100005 
100006     assert( rc==SQLITE_OK );
100007     rc = p->pMod->pModule->xDestroy(p->pVtab);
100008 
100009     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
100010     if( rc==SQLITE_OK ){
100011       assert( pTab->pVTable==p && p->pNext==0 );
100012       p->pVtab = 0;
100013       pTab->pVTable = 0;
100014       sqlite3VtabUnlock(p);
100015     }
100016   }
100017 
100018   return rc;
100019 }
100020 
100021 /*
100022 ** This function invokes either the xRollback or xCommit method
100023 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
100024 ** called is identified by the second argument, "offset", which is
100025 ** the offset of the method to call in the sqlite3_module structure.
100026 **
100027 ** The array is cleared after invoking the callbacks.
100028 */
100029 static void callFinaliser(sqlite3 *db, int offset){
100030   int i;
100031   if( db->aVTrans ){
100032     for(i=0; i<db->nVTrans; i++){
100033       VTable *pVTab = db->aVTrans[i];
100034       sqlite3_vtab *p = pVTab->pVtab;
100035       if( p ){
100036         int (*x)(sqlite3_vtab *);
100037         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
100038         if( x ) x(p);
100039       }
100040       pVTab->iSavepoint = 0;
100041       sqlite3VtabUnlock(pVTab);
100042     }
100043     sqlite3DbFree(db, db->aVTrans);
100044     db->nVTrans = 0;
100045     db->aVTrans = 0;
100046   }
100047 }
100048 
100049 /*
100050 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
100051 ** array. Return the error code for the first error that occurs, or
100052 ** SQLITE_OK if all xSync operations are successful.
100053 **
100054 ** Set *pzErrmsg to point to a buffer that should be released using
100055 ** sqlite3DbFree() containing an error message, if one is available.
100056 */
100057 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
100058   int i;
100059   int rc = SQLITE_OK;
100060   VTable **aVTrans = db->aVTrans;
100061 
100062   db->aVTrans = 0;
100063   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
100064     int (*x)(sqlite3_vtab *);
100065     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
100066     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
100067       rc = x(pVtab);
100068       sqlite3DbFree(db, *pzErrmsg);
100069       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
100070       sqlite3_free(pVtab->zErrMsg);
100071     }
100072   }
100073   db->aVTrans = aVTrans;
100074   return rc;
100075 }
100076 
100077 /*
100078 ** Invoke the xRollback method of all virtual tables in the
100079 ** sqlite3.aVTrans array. Then clear the array itself.
100080 */
100081 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
100082   callFinaliser(db, offsetof(sqlite3_module,xRollback));
100083   return SQLITE_OK;
100084 }
100085 
100086 /*
100087 ** Invoke the xCommit method of all virtual tables in the
100088 ** sqlite3.aVTrans array. Then clear the array itself.
100089 */
100090 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
100091   callFinaliser(db, offsetof(sqlite3_module,xCommit));
100092   return SQLITE_OK;
100093 }
100094 
100095 /*
100096 ** If the virtual table pVtab supports the transaction interface
100097 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
100098 ** not currently open, invoke the xBegin method now.
100099 **
100100 ** If the xBegin call is successful, place the sqlite3_vtab pointer
100101 ** in the sqlite3.aVTrans array.
100102 */
100103 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
100104   int rc = SQLITE_OK;
100105   const sqlite3_module *pModule;
100106 
100107   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
100108   ** than zero, then this function is being called from within a
100109   ** virtual module xSync() callback. It is illegal to write to
100110   ** virtual module tables in this case, so return SQLITE_LOCKED.
100111   */
100112   if( sqlite3VtabInSync(db) ){
100113     return SQLITE_LOCKED;
100114   }
100115   if( !pVTab ){
100116     return SQLITE_OK;
100117   }
100118   pModule = pVTab->pVtab->pModule;
100119 
100120   if( pModule->xBegin ){
100121     int i;
100122 
100123     /* If pVtab is already in the aVTrans array, return early */
100124     for(i=0; i<db->nVTrans; i++){
100125       if( db->aVTrans[i]==pVTab ){
100126         return SQLITE_OK;
100127       }
100128     }
100129 
100130     /* Invoke the xBegin method. If successful, add the vtab to the
100131     ** sqlite3.aVTrans[] array. */
100132     rc = growVTrans(db);
100133     if( rc==SQLITE_OK ){
100134       rc = pModule->xBegin(pVTab->pVtab);
100135       if( rc==SQLITE_OK ){
100136         addToVTrans(db, pVTab);
100137       }
100138     }
100139   }
100140   return rc;
100141 }
100142 
100143 /*
100144 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
100145 ** virtual tables that currently have an open transaction. Pass iSavepoint
100146 ** as the second argument to the virtual table method invoked.
100147 **
100148 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
100149 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
100150 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
100151 ** an open transaction is invoked.
100152 **
100153 ** If any virtual table method returns an error code other than SQLITE_OK,
100154 ** processing is abandoned and the error returned to the caller of this
100155 ** function immediately. If all calls to virtual table methods are successful,
100156 ** SQLITE_OK is returned.
100157 */
100158 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
100159   int rc = SQLITE_OK;
100160 
100161   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
100162   assert( iSavepoint>=0 );
100163   if( db->aVTrans ){
100164     int i;
100165     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
100166       VTable *pVTab = db->aVTrans[i];
100167       const sqlite3_module *pMod = pVTab->pMod->pModule;
100168       if( pMod->iVersion>=2 ){
100169         int (*xMethod)(sqlite3_vtab *, int);
100170         switch( op ){
100171           case SAVEPOINT_BEGIN:
100172             xMethod = pMod->xSavepoint;
100173             pVTab->iSavepoint = iSavepoint+1;
100174             break;
100175           case SAVEPOINT_ROLLBACK:
100176             xMethod = pMod->xRollbackTo;
100177             break;
100178           default:
100179             xMethod = pMod->xRelease;
100180             break;
100181         }
100182         if( xMethod && pVTab->iSavepoint>iSavepoint ){
100183           rc = xMethod(db->aVTrans[i]->pVtab, iSavepoint);
100184         }
100185       }
100186     }
100187   }
100188   return rc;
100189 }
100190 
100191 /*
100192 ** The first parameter (pDef) is a function implementation.  The
100193 ** second parameter (pExpr) is the first argument to this function.
100194 ** If pExpr is a column in a virtual table, then let the virtual
100195 ** table implementation have an opportunity to overload the function.
100196 **
100197 ** This routine is used to allow virtual table implementations to
100198 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
100199 **
100200 ** Return either the pDef argument (indicating no change) or a
100201 ** new FuncDef structure that is marked as ephemeral using the
100202 ** SQLITE_FUNC_EPHEM flag.
100203 */
100204 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
100205   sqlite3 *db,    /* Database connection for reporting malloc problems */
100206   FuncDef *pDef,  /* Function to possibly overload */
100207   int nArg,       /* Number of arguments to the function */
100208   Expr *pExpr     /* First argument to the function */
100209 ){
100210   Table *pTab;
100211   sqlite3_vtab *pVtab;
100212   sqlite3_module *pMod;
100213   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
100214   void *pArg = 0;
100215   FuncDef *pNew;
100216   int rc = 0;
100217   char *zLowerName;
100218   unsigned char *z;
100219 
100220 
100221   /* Check to see the left operand is a column in a virtual table */
100222   if( NEVER(pExpr==0) ) return pDef;
100223   if( pExpr->op!=TK_COLUMN ) return pDef;
100224   pTab = pExpr->pTab;
100225   if( NEVER(pTab==0) ) return pDef;
100226   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
100227   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
100228   assert( pVtab!=0 );
100229   assert( pVtab->pModule!=0 );
100230   pMod = (sqlite3_module *)pVtab->pModule;
100231   if( pMod->xFindFunction==0 ) return pDef;
100232 
100233   /* Call the xFindFunction method on the virtual table implementation
100234   ** to see if the implementation wants to overload this function
100235   */
100236   zLowerName = sqlite3DbStrDup(db, pDef->zName);
100237   if( zLowerName ){
100238     for(z=(unsigned char*)zLowerName; *z; z++){
100239       *z = sqlite3UpperToLower[*z];
100240     }
100241     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
100242     sqlite3DbFree(db, zLowerName);
100243   }
100244   if( rc==0 ){
100245     return pDef;
100246   }
100247 
100248   /* Create a new ephemeral function definition for the overloaded
100249   ** function */
100250   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
100251                              + sqlite3Strlen30(pDef->zName) + 1);
100252   if( pNew==0 ){
100253     return pDef;
100254   }
100255   *pNew = *pDef;
100256   pNew->zName = (char *)&pNew[1];
100257   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
100258   pNew->xFunc = xFunc;
100259   pNew->pUserData = pArg;
100260   pNew->flags |= SQLITE_FUNC_EPHEM;
100261   return pNew;
100262 }
100263 
100264 /*
100265 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
100266 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
100267 ** array if it is missing.  If pTab is already in the array, this routine
100268 ** is a no-op.
100269 */
100270 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
100271   Parse *pToplevel = sqlite3ParseToplevel(pParse);
100272   int i, n;
100273   Table **apVtabLock;
100274 
100275   assert( IsVirtual(pTab) );
100276   for(i=0; i<pToplevel->nVtabLock; i++){
100277     if( pTab==pToplevel->apVtabLock[i] ) return;
100278   }
100279   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
100280   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
100281   if( apVtabLock ){
100282     pToplevel->apVtabLock = apVtabLock;
100283     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
100284   }else{
100285     pToplevel->db->mallocFailed = 1;
100286   }
100287 }
100288 
100289 /*
100290 ** Return the ON CONFLICT resolution mode in effect for the virtual
100291 ** table update operation currently in progress.
100292 **
100293 ** The results of this routine are undefined unless it is called from
100294 ** within an xUpdate method.
100295 */
100296 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
100297   static const unsigned char aMap[] = {
100298     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
100299   };
100300   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
100301   assert( OE_Ignore==4 && OE_Replace==5 );
100302   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
100303   return (int)aMap[db->vtabOnConflict-1];
100304 }
100305 
100306 /*
100307 ** Call from within the xCreate() or xConnect() methods to provide
100308 ** the SQLite core with additional information about the behavior
100309 ** of the virtual table being implemented.
100310 */
100311 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
100312   va_list ap;
100313   int rc = SQLITE_OK;
100314 
100315   sqlite3_mutex_enter(db->mutex);
100316 
100317   va_start(ap, op);
100318   switch( op ){
100319     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
100320       VtabCtx *p = db->pVtabCtx;
100321       if( !p ){
100322         rc = SQLITE_MISUSE_BKPT;
100323       }else{
100324         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
100325         p->pVTable->bConstraint = (u8)va_arg(ap, int);
100326       }
100327       break;
100328     }
100329     default:
100330       rc = SQLITE_MISUSE_BKPT;
100331       break;
100332   }
100333   va_end(ap);
100334 
100335   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
100336   sqlite3_mutex_leave(db->mutex);
100337   return rc;
100338 }
100339 
100340 #endif /* SQLITE_OMIT_VIRTUALTABLE */
100341 
100342 /************** End of vtab.c ************************************************/
100343 /************** Begin file where.c *******************************************/
100344 /*
100345 ** 2001 September 15
100346 **
100347 ** The author disclaims copyright to this source code.  In place of
100348 ** a legal notice, here is a blessing:
100349 **
100350 **    May you do good and not evil.
100351 **    May you find forgiveness for yourself and forgive others.
100352 **    May you share freely, never taking more than you give.
100353 **
100354 *************************************************************************
100355 ** This module contains C code that generates VDBE code used to process
100356 ** the WHERE clause of SQL statements.  This module is responsible for
100357 ** generating the code that loops through a table looking for applicable
100358 ** rows.  Indices are selected and used to speed the search when doing
100359 ** so is applicable.  Because this module is responsible for selecting
100360 ** indices, you might also think of this module as the "query optimizer".
100361 */
100362 
100363 
100364 /*
100365 ** Trace output macros
100366 */
100367 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
100368 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
100369 #endif
100370 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
100371 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
100372 #else
100373 # define WHERETRACE(X)
100374 #endif
100375 
100376 /* Forward reference
100377 */
100378 typedef struct WhereClause WhereClause;
100379 typedef struct WhereMaskSet WhereMaskSet;
100380 typedef struct WhereOrInfo WhereOrInfo;
100381 typedef struct WhereAndInfo WhereAndInfo;
100382 typedef struct WhereCost WhereCost;
100383 
100384 /*
100385 ** The query generator uses an array of instances of this structure to
100386 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
100387 ** clause subexpression is separated from the others by AND operators,
100388 ** usually, or sometimes subexpressions separated by OR.
100389 **
100390 ** All WhereTerms are collected into a single WhereClause structure.
100391 ** The following identity holds:
100392 **
100393 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
100394 **
100395 ** When a term is of the form:
100396 **
100397 **              X <op> <expr>
100398 **
100399 ** where X is a column name and <op> is one of certain operators,
100400 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
100401 ** cursor number and column number for X.  WhereTerm.eOperator records
100402 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
100403 ** use of a bitmask encoding for the operator allows us to search
100404 ** quickly for terms that match any of several different operators.
100405 **
100406 ** A WhereTerm might also be two or more subterms connected by OR:
100407 **
100408 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
100409 **
100410 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
100411 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
100412 ** is collected about the
100413 **
100414 ** If a term in the WHERE clause does not match either of the two previous
100415 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
100416 ** to the original subexpression content and wtFlags is set up appropriately
100417 ** but no other fields in the WhereTerm object are meaningful.
100418 **
100419 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
100420 ** but they do so indirectly.  A single WhereMaskSet structure translates
100421 ** cursor number into bits and the translated bit is stored in the prereq
100422 ** fields.  The translation is used in order to maximize the number of
100423 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
100424 ** spread out over the non-negative integers.  For example, the cursor
100425 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
100426 ** translates these sparse cursor numbers into consecutive integers
100427 ** beginning with 0 in order to make the best possible use of the available
100428 ** bits in the Bitmask.  So, in the example above, the cursor numbers
100429 ** would be mapped into integers 0 through 7.
100430 **
100431 ** The number of terms in a join is limited by the number of bits
100432 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
100433 ** is only able to process joins with 64 or fewer tables.
100434 */
100435 typedef struct WhereTerm WhereTerm;
100436 struct WhereTerm {
100437   Expr *pExpr;            /* Pointer to the subexpression that is this term */
100438   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
100439   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
100440   union {
100441     int leftColumn;         /* Column number of X in "X <op> <expr>" */
100442     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
100443     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
100444   } u;
100445   u16 eOperator;          /* A WO_xx value describing <op> */
100446   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
100447   u8 nChild;              /* Number of children that must disable us */
100448   WhereClause *pWC;       /* The clause this term is part of */
100449   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
100450   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
100451 };
100452 
100453 /*
100454 ** Allowed values of WhereTerm.wtFlags
100455 */
100456 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
100457 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
100458 #define TERM_CODED      0x04   /* This term is already coded */
100459 #define TERM_COPIED     0x08   /* Has a child */
100460 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
100461 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
100462 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
100463 #ifdef SQLITE_ENABLE_STAT2
100464 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
100465 #else
100466 #  define TERM_VNULL    0x00   /* Disabled if not using stat2 */
100467 #endif
100468 
100469 /*
100470 ** An instance of the following structure holds all information about a
100471 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
100472 */
100473 struct WhereClause {
100474   Parse *pParse;           /* The parser context */
100475   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
100476   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
100477   u8 op;                   /* Split operator.  TK_AND or TK_OR */
100478   int nTerm;               /* Number of terms */
100479   int nSlot;               /* Number of entries in a[] */
100480   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
100481 #if defined(SQLITE_SMALL_STACK)
100482   WhereTerm aStatic[1];    /* Initial static space for a[] */
100483 #else
100484   WhereTerm aStatic[8];    /* Initial static space for a[] */
100485 #endif
100486 };
100487 
100488 /*
100489 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
100490 ** a dynamically allocated instance of the following structure.
100491 */
100492 struct WhereOrInfo {
100493   WhereClause wc;          /* Decomposition into subterms */
100494   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
100495 };
100496 
100497 /*
100498 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
100499 ** a dynamically allocated instance of the following structure.
100500 */
100501 struct WhereAndInfo {
100502   WhereClause wc;          /* The subexpression broken out */
100503 };
100504 
100505 /*
100506 ** An instance of the following structure keeps track of a mapping
100507 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
100508 **
100509 ** The VDBE cursor numbers are small integers contained in
100510 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
100511 ** clause, the cursor numbers might not begin with 0 and they might
100512 ** contain gaps in the numbering sequence.  But we want to make maximum
100513 ** use of the bits in our bitmasks.  This structure provides a mapping
100514 ** from the sparse cursor numbers into consecutive integers beginning
100515 ** with 0.
100516 **
100517 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
100518 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
100519 **
100520 ** For example, if the WHERE clause expression used these VDBE
100521 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
100522 ** would map those cursor numbers into bits 0 through 5.
100523 **
100524 ** Note that the mapping is not necessarily ordered.  In the example
100525 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
100526 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
100527 ** does not really matter.  What is important is that sparse cursor
100528 ** numbers all get mapped into bit numbers that begin with 0 and contain
100529 ** no gaps.
100530 */
100531 struct WhereMaskSet {
100532   int n;                        /* Number of assigned cursor values */
100533   int ix[BMS];                  /* Cursor assigned to each bit */
100534 };
100535 
100536 /*
100537 ** A WhereCost object records a lookup strategy and the estimated
100538 ** cost of pursuing that strategy.
100539 */
100540 struct WhereCost {
100541   WherePlan plan;    /* The lookup strategy */
100542   double rCost;      /* Overall cost of pursuing this search strategy */
100543   Bitmask used;      /* Bitmask of cursors used by this plan */
100544 };
100545 
100546 /*
100547 ** Bitmasks for the operators that indices are able to exploit.  An
100548 ** OR-ed combination of these values can be used when searching for
100549 ** terms in the where clause.
100550 */
100551 #define WO_IN     0x001
100552 #define WO_EQ     0x002
100553 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
100554 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
100555 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
100556 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
100557 #define WO_MATCH  0x040
100558 #define WO_ISNULL 0x080
100559 #define WO_OR     0x100       /* Two or more OR-connected terms */
100560 #define WO_AND    0x200       /* Two or more AND-connected terms */
100561 #define WO_NOOP   0x800       /* This term does not restrict search space */
100562 
100563 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
100564 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
100565 
100566 /*
100567 ** Value for wsFlags returned by bestIndex() and stored in
100568 ** WhereLevel.wsFlags.  These flags determine which search
100569 ** strategies are appropriate.
100570 **
100571 ** The least significant 12 bits is reserved as a mask for WO_ values above.
100572 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
100573 ** But if the table is the right table of a left join, WhereLevel.wsFlags
100574 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
100575 ** the "op" parameter to findTerm when we are resolving equality constraints.
100576 ** ISNULL constraints will then not be used on the right table of a left
100577 ** join.  Tickets #2177 and #2189.
100578 */
100579 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
100580 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
100581 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
100582 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
100583 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
100584 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
100585 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
100586 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
100587 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
100588 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
100589 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
100590 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
100591 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
100592 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
100593 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
100594 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
100595 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
100596 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
100597 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
100598 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
100599 
100600 /*
100601 ** Initialize a preallocated WhereClause structure.
100602 */
100603 static void whereClauseInit(
100604   WhereClause *pWC,        /* The WhereClause to be initialized */
100605   Parse *pParse,           /* The parsing context */
100606   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
100607 ){
100608   pWC->pParse = pParse;
100609   pWC->pMaskSet = pMaskSet;
100610   pWC->nTerm = 0;
100611   pWC->nSlot = ArraySize(pWC->aStatic);
100612   pWC->a = pWC->aStatic;
100613   pWC->vmask = 0;
100614 }
100615 
100616 /* Forward reference */
100617 static void whereClauseClear(WhereClause*);
100618 
100619 /*
100620 ** Deallocate all memory associated with a WhereOrInfo object.
100621 */
100622 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
100623   whereClauseClear(&p->wc);
100624   sqlite3DbFree(db, p);
100625 }
100626 
100627 /*
100628 ** Deallocate all memory associated with a WhereAndInfo object.
100629 */
100630 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
100631   whereClauseClear(&p->wc);
100632   sqlite3DbFree(db, p);
100633 }
100634 
100635 /*
100636 ** Deallocate a WhereClause structure.  The WhereClause structure
100637 ** itself is not freed.  This routine is the inverse of whereClauseInit().
100638 */
100639 static void whereClauseClear(WhereClause *pWC){
100640   int i;
100641   WhereTerm *a;
100642   sqlite3 *db = pWC->pParse->db;
100643   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
100644     if( a->wtFlags & TERM_DYNAMIC ){
100645       sqlite3ExprDelete(db, a->pExpr);
100646     }
100647     if( a->wtFlags & TERM_ORINFO ){
100648       whereOrInfoDelete(db, a->u.pOrInfo);
100649     }else if( a->wtFlags & TERM_ANDINFO ){
100650       whereAndInfoDelete(db, a->u.pAndInfo);
100651     }
100652   }
100653   if( pWC->a!=pWC->aStatic ){
100654     sqlite3DbFree(db, pWC->a);
100655   }
100656 }
100657 
100658 /*
100659 ** Add a single new WhereTerm entry to the WhereClause object pWC.
100660 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
100661 ** The index in pWC->a[] of the new WhereTerm is returned on success.
100662 ** 0 is returned if the new WhereTerm could not be added due to a memory
100663 ** allocation error.  The memory allocation failure will be recorded in
100664 ** the db->mallocFailed flag so that higher-level functions can detect it.
100665 **
100666 ** This routine will increase the size of the pWC->a[] array as necessary.
100667 **
100668 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
100669 ** for freeing the expression p is assumed by the WhereClause object pWC.
100670 ** This is true even if this routine fails to allocate a new WhereTerm.
100671 **
100672 ** WARNING:  This routine might reallocate the space used to store
100673 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
100674 ** calling this routine.  Such pointers may be reinitialized by referencing
100675 ** the pWC->a[] array.
100676 */
100677 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
100678   WhereTerm *pTerm;
100679   int idx;
100680   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
100681   if( pWC->nTerm>=pWC->nSlot ){
100682     WhereTerm *pOld = pWC->a;
100683     sqlite3 *db = pWC->pParse->db;
100684     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
100685     if( pWC->a==0 ){
100686       if( wtFlags & TERM_DYNAMIC ){
100687         sqlite3ExprDelete(db, p);
100688       }
100689       pWC->a = pOld;
100690       return 0;
100691     }
100692     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
100693     if( pOld!=pWC->aStatic ){
100694       sqlite3DbFree(db, pOld);
100695     }
100696     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
100697   }
100698   pTerm = &pWC->a[idx = pWC->nTerm++];
100699   pTerm->pExpr = p;
100700   pTerm->wtFlags = wtFlags;
100701   pTerm->pWC = pWC;
100702   pTerm->iParent = -1;
100703   return idx;
100704 }
100705 
100706 /*
100707 ** This routine identifies subexpressions in the WHERE clause where
100708 ** each subexpression is separated by the AND operator or some other
100709 ** operator specified in the op parameter.  The WhereClause structure
100710 ** is filled with pointers to subexpressions.  For example:
100711 **
100712 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
100713 **           \________/     \_______________/     \________________/
100714 **            slot[0]            slot[1]               slot[2]
100715 **
100716 ** The original WHERE clause in pExpr is unaltered.  All this routine
100717 ** does is make slot[] entries point to substructure within pExpr.
100718 **
100719 ** In the previous sentence and in the diagram, "slot[]" refers to
100720 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
100721 ** all terms of the WHERE clause.
100722 */
100723 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
100724   pWC->op = (u8)op;
100725   if( pExpr==0 ) return;
100726   if( pExpr->op!=op ){
100727     whereClauseInsert(pWC, pExpr, 0);
100728   }else{
100729     whereSplit(pWC, pExpr->pLeft, op);
100730     whereSplit(pWC, pExpr->pRight, op);
100731   }
100732 }
100733 
100734 /*
100735 ** Initialize an expression mask set (a WhereMaskSet object)
100736 */
100737 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
100738 
100739 /*
100740 ** Return the bitmask for the given cursor number.  Return 0 if
100741 ** iCursor is not in the set.
100742 */
100743 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
100744   int i;
100745   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
100746   for(i=0; i<pMaskSet->n; i++){
100747     if( pMaskSet->ix[i]==iCursor ){
100748       return ((Bitmask)1)<<i;
100749     }
100750   }
100751   return 0;
100752 }
100753 
100754 /*
100755 ** Create a new mask for cursor iCursor.
100756 **
100757 ** There is one cursor per table in the FROM clause.  The number of
100758 ** tables in the FROM clause is limited by a test early in the
100759 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
100760 ** array will never overflow.
100761 */
100762 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
100763   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
100764   pMaskSet->ix[pMaskSet->n++] = iCursor;
100765 }
100766 
100767 /*
100768 ** This routine walks (recursively) an expression tree and generates
100769 ** a bitmask indicating which tables are used in that expression
100770 ** tree.
100771 **
100772 ** In order for this routine to work, the calling function must have
100773 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
100774 ** the header comment on that routine for additional information.
100775 ** The sqlite3ResolveExprNames() routines looks for column names and
100776 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
100777 ** the VDBE cursor number of the table.  This routine just has to
100778 ** translate the cursor numbers into bitmask values and OR all
100779 ** the bitmasks together.
100780 */
100781 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
100782 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
100783 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
100784   Bitmask mask = 0;
100785   if( p==0 ) return 0;
100786   if( p->op==TK_COLUMN ){
100787     mask = getMask(pMaskSet, p->iTable);
100788     return mask;
100789   }
100790   mask = exprTableUsage(pMaskSet, p->pRight);
100791   mask |= exprTableUsage(pMaskSet, p->pLeft);
100792   if( ExprHasProperty(p, EP_xIsSelect) ){
100793     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
100794   }else{
100795     mask |= exprListTableUsage(pMaskSet, p->x.pList);
100796   }
100797   return mask;
100798 }
100799 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
100800   int i;
100801   Bitmask mask = 0;
100802   if( pList ){
100803     for(i=0; i<pList->nExpr; i++){
100804       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
100805     }
100806   }
100807   return mask;
100808 }
100809 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
100810   Bitmask mask = 0;
100811   while( pS ){
100812     SrcList *pSrc = pS->pSrc;
100813     mask |= exprListTableUsage(pMaskSet, pS->pEList);
100814     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
100815     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
100816     mask |= exprTableUsage(pMaskSet, pS->pWhere);
100817     mask |= exprTableUsage(pMaskSet, pS->pHaving);
100818     if( ALWAYS(pSrc!=0) ){
100819       int i;
100820       for(i=0; i<pSrc->nSrc; i++){
100821         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
100822         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
100823       }
100824     }
100825     pS = pS->pPrior;
100826   }
100827   return mask;
100828 }
100829 
100830 /*
100831 ** Return TRUE if the given operator is one of the operators that is
100832 ** allowed for an indexable WHERE clause term.  The allowed operators are
100833 ** "=", "<", ">", "<=", ">=", and "IN".
100834 **
100835 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
100836 ** of one of the following forms: column = expression column > expression
100837 ** column >= expression column < expression column <= expression
100838 ** expression = column expression > column expression >= column
100839 ** expression < column expression <= column column IN
100840 ** (expression-list) column IN (subquery) column IS NULL
100841 */
100842 static int allowedOp(int op){
100843   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
100844   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
100845   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
100846   assert( TK_GE==TK_EQ+4 );
100847   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
100848 }
100849 
100850 /*
100851 ** Swap two objects of type TYPE.
100852 */
100853 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
100854 
100855 /*
100856 ** Commute a comparison operator.  Expressions of the form "X op Y"
100857 ** are converted into "Y op X".
100858 **
100859 ** If a collation sequence is associated with either the left or right
100860 ** side of the comparison, it remains associated with the same side after
100861 ** the commutation. So "Y collate NOCASE op X" becomes
100862 ** "X collate NOCASE op Y". This is because any collation sequence on
100863 ** the left hand side of a comparison overrides any collation sequence
100864 ** attached to the right. For the same reason the EP_ExpCollate flag
100865 ** is not commuted.
100866 */
100867 static void exprCommute(Parse *pParse, Expr *pExpr){
100868   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
100869   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
100870   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
100871   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
100872   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
100873   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
100874   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
100875   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
100876   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
100877   if( pExpr->op>=TK_GT ){
100878     assert( TK_LT==TK_GT+2 );
100879     assert( TK_GE==TK_LE+2 );
100880     assert( TK_GT>TK_EQ );
100881     assert( TK_GT<TK_LE );
100882     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
100883     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
100884   }
100885 }
100886 
100887 /*
100888 ** Translate from TK_xx operator to WO_xx bitmask.
100889 */
100890 static u16 operatorMask(int op){
100891   u16 c;
100892   assert( allowedOp(op) );
100893   if( op==TK_IN ){
100894     c = WO_IN;
100895   }else if( op==TK_ISNULL ){
100896     c = WO_ISNULL;
100897   }else{
100898     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
100899     c = (u16)(WO_EQ<<(op-TK_EQ));
100900   }
100901   assert( op!=TK_ISNULL || c==WO_ISNULL );
100902   assert( op!=TK_IN || c==WO_IN );
100903   assert( op!=TK_EQ || c==WO_EQ );
100904   assert( op!=TK_LT || c==WO_LT );
100905   assert( op!=TK_LE || c==WO_LE );
100906   assert( op!=TK_GT || c==WO_GT );
100907   assert( op!=TK_GE || c==WO_GE );
100908   return c;
100909 }
100910 
100911 /*
100912 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
100913 ** where X is a reference to the iColumn of table iCur and <op> is one of
100914 ** the WO_xx operator codes specified by the op parameter.
100915 ** Return a pointer to the term.  Return 0 if not found.
100916 */
100917 static WhereTerm *findTerm(
100918   WhereClause *pWC,     /* The WHERE clause to be searched */
100919   int iCur,             /* Cursor number of LHS */
100920   int iColumn,          /* Column number of LHS */
100921   Bitmask notReady,     /* RHS must not overlap with this mask */
100922   u32 op,               /* Mask of WO_xx values describing operator */
100923   Index *pIdx           /* Must be compatible with this index, if not NULL */
100924 ){
100925   WhereTerm *pTerm;
100926   int k;
100927   assert( iCur>=0 );
100928   op &= WO_ALL;
100929   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
100930     if( pTerm->leftCursor==iCur
100931        && (pTerm->prereqRight & notReady)==0
100932        && pTerm->u.leftColumn==iColumn
100933        && (pTerm->eOperator & op)!=0
100934     ){
100935       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
100936         Expr *pX = pTerm->pExpr;
100937         CollSeq *pColl;
100938         char idxaff;
100939         int j;
100940         Parse *pParse = pWC->pParse;
100941 
100942         idxaff = pIdx->pTable->aCol[iColumn].affinity;
100943         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
100944 
100945         /* Figure out the collation sequence required from an index for
100946         ** it to be useful for optimising expression pX. Store this
100947         ** value in variable pColl.
100948         */
100949         assert(pX->pLeft);
100950         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
100951         assert(pColl || pParse->nErr);
100952 
100953         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
100954           if( NEVER(j>=pIdx->nColumn) ) return 0;
100955         }
100956         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
100957       }
100958       return pTerm;
100959     }
100960   }
100961   return 0;
100962 }
100963 
100964 /* Forward reference */
100965 static void exprAnalyze(SrcList*, WhereClause*, int);
100966 
100967 /*
100968 ** Call exprAnalyze on all terms in a WHERE clause.
100969 **
100970 **
100971 */
100972 static void exprAnalyzeAll(
100973   SrcList *pTabList,       /* the FROM clause */
100974   WhereClause *pWC         /* the WHERE clause to be analyzed */
100975 ){
100976   int i;
100977   for(i=pWC->nTerm-1; i>=0; i--){
100978     exprAnalyze(pTabList, pWC, i);
100979   }
100980 }
100981 
100982 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
100983 /*
100984 ** Check to see if the given expression is a LIKE or GLOB operator that
100985 ** can be optimized using inequality constraints.  Return TRUE if it is
100986 ** so and false if not.
100987 **
100988 ** In order for the operator to be optimizible, the RHS must be a string
100989 ** literal that does not begin with a wildcard.
100990 */
100991 static int isLikeOrGlob(
100992   Parse *pParse,    /* Parsing and code generating context */
100993   Expr *pExpr,      /* Test this expression */
100994   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
100995   int *pisComplete, /* True if the only wildcard is % in the last character */
100996   int *pnoCase      /* True if uppercase is equivalent to lowercase */
100997 ){
100998   const char *z = 0;         /* String on RHS of LIKE operator */
100999   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
101000   ExprList *pList;           /* List of operands to the LIKE operator */
101001   int c;                     /* One character in z[] */
101002   int cnt;                   /* Number of non-wildcard prefix characters */
101003   char wc[3];                /* Wildcard characters */
101004   sqlite3 *db = pParse->db;  /* Database connection */
101005   sqlite3_value *pVal = 0;
101006   int op;                    /* Opcode of pRight */
101007 
101008   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
101009     return 0;
101010   }
101011 #ifdef SQLITE_EBCDIC
101012   if( *pnoCase ) return 0;
101013 #endif
101014   pList = pExpr->x.pList;
101015   pLeft = pList->a[1].pExpr;
101016   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
101017     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
101018     ** be the name of an indexed column with TEXT affinity. */
101019     return 0;
101020   }
101021   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
101022 
101023   pRight = pList->a[0].pExpr;
101024   op = pRight->op;
101025   if( op==TK_REGISTER ){
101026     op = pRight->op2;
101027   }
101028   if( op==TK_VARIABLE ){
101029     Vdbe *pReprepare = pParse->pReprepare;
101030     int iCol = pRight->iColumn;
101031     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
101032     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
101033       z = (char *)sqlite3_value_text(pVal);
101034     }
101035     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); /* IMP: R-23257-02778 */
101036     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
101037   }else if( op==TK_STRING ){
101038     z = pRight->u.zToken;
101039   }
101040   if( z ){
101041     cnt = 0;
101042     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
101043       cnt++;
101044     }
101045     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
101046       Expr *pPrefix;
101047       *pisComplete = c==wc[0] && z[cnt+1]==0;
101048       pPrefix = sqlite3Expr(db, TK_STRING, z);
101049       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
101050       *ppPrefix = pPrefix;
101051       if( op==TK_VARIABLE ){
101052         Vdbe *v = pParse->pVdbe;
101053         sqlite3VdbeSetVarmask(v, pRight->iColumn); /* IMP: R-23257-02778 */
101054         if( *pisComplete && pRight->u.zToken[1] ){
101055           /* If the rhs of the LIKE expression is a variable, and the current
101056           ** value of the variable means there is no need to invoke the LIKE
101057           ** function, then no OP_Variable will be added to the program.
101058           ** This causes problems for the sqlite3_bind_parameter_name()
101059           ** API. To workaround them, add a dummy OP_Variable here.
101060           */
101061           int r1 = sqlite3GetTempReg(pParse);
101062           sqlite3ExprCodeTarget(pParse, pRight, r1);
101063           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
101064           sqlite3ReleaseTempReg(pParse, r1);
101065         }
101066       }
101067     }else{
101068       z = 0;
101069     }
101070   }
101071 
101072   sqlite3ValueFree(pVal);
101073   return (z!=0);
101074 }
101075 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
101076 
101077 
101078 #ifndef SQLITE_OMIT_VIRTUALTABLE
101079 /*
101080 ** Check to see if the given expression is of the form
101081 **
101082 **         column MATCH expr
101083 **
101084 ** If it is then return TRUE.  If not, return FALSE.
101085 */
101086 static int isMatchOfColumn(
101087   Expr *pExpr      /* Test this expression */
101088 ){
101089   ExprList *pList;
101090 
101091   if( pExpr->op!=TK_FUNCTION ){
101092     return 0;
101093   }
101094   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
101095     return 0;
101096   }
101097   pList = pExpr->x.pList;
101098   if( pList->nExpr!=2 ){
101099     return 0;
101100   }
101101   if( pList->a[1].pExpr->op != TK_COLUMN ){
101102     return 0;
101103   }
101104   return 1;
101105 }
101106 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101107 
101108 /*
101109 ** If the pBase expression originated in the ON or USING clause of
101110 ** a join, then transfer the appropriate markings over to derived.
101111 */
101112 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
101113   pDerived->flags |= pBase->flags & EP_FromJoin;
101114   pDerived->iRightJoinTable = pBase->iRightJoinTable;
101115 }
101116 
101117 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
101118 /*
101119 ** Analyze a term that consists of two or more OR-connected
101120 ** subterms.  So in:
101121 **
101122 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
101123 **                          ^^^^^^^^^^^^^^^^^^^^
101124 **
101125 ** This routine analyzes terms such as the middle term in the above example.
101126 ** A WhereOrTerm object is computed and attached to the term under
101127 ** analysis, regardless of the outcome of the analysis.  Hence:
101128 **
101129 **     WhereTerm.wtFlags   |=  TERM_ORINFO
101130 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
101131 **
101132 ** The term being analyzed must have two or more of OR-connected subterms.
101133 ** A single subterm might be a set of AND-connected sub-subterms.
101134 ** Examples of terms under analysis:
101135 **
101136 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
101137 **     (B)     x=expr1 OR expr2=x OR x=expr3
101138 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
101139 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
101140 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
101141 **
101142 ** CASE 1:
101143 **
101144 ** If all subterms are of the form T.C=expr for some single column of C
101145 ** a single table T (as shown in example B above) then create a new virtual
101146 ** term that is an equivalent IN expression.  In other words, if the term
101147 ** being analyzed is:
101148 **
101149 **      x = expr1  OR  expr2 = x  OR  x = expr3
101150 **
101151 ** then create a new virtual term like this:
101152 **
101153 **      x IN (expr1,expr2,expr3)
101154 **
101155 ** CASE 2:
101156 **
101157 ** If all subterms are indexable by a single table T, then set
101158 **
101159 **     WhereTerm.eOperator              =  WO_OR
101160 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
101161 **
101162 ** A subterm is "indexable" if it is of the form
101163 ** "T.C <op> <expr>" where C is any column of table T and
101164 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
101165 ** A subterm is also indexable if it is an AND of two or more
101166 ** subsubterms at least one of which is indexable.  Indexable AND
101167 ** subterms have their eOperator set to WO_AND and they have
101168 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
101169 **
101170 ** From another point of view, "indexable" means that the subterm could
101171 ** potentially be used with an index if an appropriate index exists.
101172 ** This analysis does not consider whether or not the index exists; that
101173 ** is something the bestIndex() routine will determine.  This analysis
101174 ** only looks at whether subterms appropriate for indexing exist.
101175 **
101176 ** All examples A through E above all satisfy case 2.  But if a term
101177 ** also statisfies case 1 (such as B) we know that the optimizer will
101178 ** always prefer case 1, so in that case we pretend that case 2 is not
101179 ** satisfied.
101180 **
101181 ** It might be the case that multiple tables are indexable.  For example,
101182 ** (E) above is indexable on tables P, Q, and R.
101183 **
101184 ** Terms that satisfy case 2 are candidates for lookup by using
101185 ** separate indices to find rowids for each subterm and composing
101186 ** the union of all rowids using a RowSet object.  This is similar
101187 ** to "bitmap indices" in other database engines.
101188 **
101189 ** OTHERWISE:
101190 **
101191 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
101192 ** zero.  This term is not useful for search.
101193 */
101194 static void exprAnalyzeOrTerm(
101195   SrcList *pSrc,            /* the FROM clause */
101196   WhereClause *pWC,         /* the complete WHERE clause */
101197   int idxTerm               /* Index of the OR-term to be analyzed */
101198 ){
101199   Parse *pParse = pWC->pParse;            /* Parser context */
101200   sqlite3 *db = pParse->db;               /* Database connection */
101201   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
101202   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
101203   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
101204   int i;                                  /* Loop counters */
101205   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
101206   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
101207   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
101208   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
101209   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
101210 
101211   /*
101212   ** Break the OR clause into its separate subterms.  The subterms are
101213   ** stored in a WhereClause structure containing within the WhereOrInfo
101214   ** object that is attached to the original OR clause term.
101215   */
101216   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
101217   assert( pExpr->op==TK_OR );
101218   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
101219   if( pOrInfo==0 ) return;
101220   pTerm->wtFlags |= TERM_ORINFO;
101221   pOrWc = &pOrInfo->wc;
101222   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
101223   whereSplit(pOrWc, pExpr, TK_OR);
101224   exprAnalyzeAll(pSrc, pOrWc);
101225   if( db->mallocFailed ) return;
101226   assert( pOrWc->nTerm>=2 );
101227 
101228   /*
101229   ** Compute the set of tables that might satisfy cases 1 or 2.
101230   */
101231   indexable = ~(Bitmask)0;
101232   chngToIN = ~(pWC->vmask);
101233   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
101234     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
101235       WhereAndInfo *pAndInfo;
101236       assert( pOrTerm->eOperator==0 );
101237       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
101238       chngToIN = 0;
101239       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
101240       if( pAndInfo ){
101241         WhereClause *pAndWC;
101242         WhereTerm *pAndTerm;
101243         int j;
101244         Bitmask b = 0;
101245         pOrTerm->u.pAndInfo = pAndInfo;
101246         pOrTerm->wtFlags |= TERM_ANDINFO;
101247         pOrTerm->eOperator = WO_AND;
101248         pAndWC = &pAndInfo->wc;
101249         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
101250         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
101251         exprAnalyzeAll(pSrc, pAndWC);
101252         testcase( db->mallocFailed );
101253         if( !db->mallocFailed ){
101254           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
101255             assert( pAndTerm->pExpr );
101256             if( allowedOp(pAndTerm->pExpr->op) ){
101257               b |= getMask(pMaskSet, pAndTerm->leftCursor);
101258             }
101259           }
101260         }
101261         indexable &= b;
101262       }
101263     }else if( pOrTerm->wtFlags & TERM_COPIED ){
101264       /* Skip this term for now.  We revisit it when we process the
101265       ** corresponding TERM_VIRTUAL term */
101266     }else{
101267       Bitmask b;
101268       b = getMask(pMaskSet, pOrTerm->leftCursor);
101269       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
101270         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
101271         b |= getMask(pMaskSet, pOther->leftCursor);
101272       }
101273       indexable &= b;
101274       if( pOrTerm->eOperator!=WO_EQ ){
101275         chngToIN = 0;
101276       }else{
101277         chngToIN &= b;
101278       }
101279     }
101280   }
101281 
101282   /*
101283   ** Record the set of tables that satisfy case 2.  The set might be
101284   ** empty.
101285   */
101286   pOrInfo->indexable = indexable;
101287   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
101288 
101289   /*
101290   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
101291   ** we have to do some additional checking to see if case 1 really
101292   ** is satisfied.
101293   **
101294   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
101295   ** that there is no possibility of transforming the OR clause into an
101296   ** IN operator because one or more terms in the OR clause contain
101297   ** something other than == on a column in the single table.  The 1-bit
101298   ** case means that every term of the OR clause is of the form
101299   ** "table.column=expr" for some single table.  The one bit that is set
101300   ** will correspond to the common table.  We still need to check to make
101301   ** sure the same column is used on all terms.  The 2-bit case is when
101302   ** the all terms are of the form "table1.column=table2.column".  It
101303   ** might be possible to form an IN operator with either table1.column
101304   ** or table2.column as the LHS if either is common to every term of
101305   ** the OR clause.
101306   **
101307   ** Note that terms of the form "table.column1=table.column2" (the
101308   ** same table on both sizes of the ==) cannot be optimized.
101309   */
101310   if( chngToIN ){
101311     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
101312     int iColumn = -1;         /* Column index on lhs of IN operator */
101313     int iCursor = -1;         /* Table cursor common to all terms */
101314     int j = 0;                /* Loop counter */
101315 
101316     /* Search for a table and column that appears on one side or the
101317     ** other of the == operator in every subterm.  That table and column
101318     ** will be recorded in iCursor and iColumn.  There might not be any
101319     ** such table and column.  Set okToChngToIN if an appropriate table
101320     ** and column is found but leave okToChngToIN false if not found.
101321     */
101322     for(j=0; j<2 && !okToChngToIN; j++){
101323       pOrTerm = pOrWc->a;
101324       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
101325         assert( pOrTerm->eOperator==WO_EQ );
101326         pOrTerm->wtFlags &= ~TERM_OR_OK;
101327         if( pOrTerm->leftCursor==iCursor ){
101328           /* This is the 2-bit case and we are on the second iteration and
101329           ** current term is from the first iteration.  So skip this term. */
101330           assert( j==1 );
101331           continue;
101332         }
101333         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
101334           /* This term must be of the form t1.a==t2.b where t2 is in the
101335           ** chngToIN set but t1 is not.  This term will be either preceeded
101336           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
101337           ** and use its inversion. */
101338           testcase( pOrTerm->wtFlags & TERM_COPIED );
101339           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
101340           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
101341           continue;
101342         }
101343         iColumn = pOrTerm->u.leftColumn;
101344         iCursor = pOrTerm->leftCursor;
101345         break;
101346       }
101347       if( i<0 ){
101348         /* No candidate table+column was found.  This can only occur
101349         ** on the second iteration */
101350         assert( j==1 );
101351         assert( (chngToIN&(chngToIN-1))==0 );
101352         assert( chngToIN==getMask(pMaskSet, iCursor) );
101353         break;
101354       }
101355       testcase( j==1 );
101356 
101357       /* We have found a candidate table and column.  Check to see if that
101358       ** table and column is common to every term in the OR clause */
101359       okToChngToIN = 1;
101360       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
101361         assert( pOrTerm->eOperator==WO_EQ );
101362         if( pOrTerm->leftCursor!=iCursor ){
101363           pOrTerm->wtFlags &= ~TERM_OR_OK;
101364         }else if( pOrTerm->u.leftColumn!=iColumn ){
101365           okToChngToIN = 0;
101366         }else{
101367           int affLeft, affRight;
101368           /* If the right-hand side is also a column, then the affinities
101369           ** of both right and left sides must be such that no type
101370           ** conversions are required on the right.  (Ticket #2249)
101371           */
101372           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
101373           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
101374           if( affRight!=0 && affRight!=affLeft ){
101375             okToChngToIN = 0;
101376           }else{
101377             pOrTerm->wtFlags |= TERM_OR_OK;
101378           }
101379         }
101380       }
101381     }
101382 
101383     /* At this point, okToChngToIN is true if original pTerm satisfies
101384     ** case 1.  In that case, construct a new virtual term that is
101385     ** pTerm converted into an IN operator.
101386     **
101387     ** EV: R-00211-15100
101388     */
101389     if( okToChngToIN ){
101390       Expr *pDup;            /* A transient duplicate expression */
101391       ExprList *pList = 0;   /* The RHS of the IN operator */
101392       Expr *pLeft = 0;       /* The LHS of the IN operator */
101393       Expr *pNew;            /* The complete IN operator */
101394 
101395       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
101396         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
101397         assert( pOrTerm->eOperator==WO_EQ );
101398         assert( pOrTerm->leftCursor==iCursor );
101399         assert( pOrTerm->u.leftColumn==iColumn );
101400         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
101401         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
101402         pLeft = pOrTerm->pExpr->pLeft;
101403       }
101404       assert( pLeft!=0 );
101405       pDup = sqlite3ExprDup(db, pLeft, 0);
101406       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
101407       if( pNew ){
101408         int idxNew;
101409         transferJoinMarkings(pNew, pExpr);
101410         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
101411         pNew->x.pList = pList;
101412         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
101413         testcase( idxNew==0 );
101414         exprAnalyze(pSrc, pWC, idxNew);
101415         pTerm = &pWC->a[idxTerm];
101416         pWC->a[idxNew].iParent = idxTerm;
101417         pTerm->nChild = 1;
101418       }else{
101419         sqlite3ExprListDelete(db, pList);
101420       }
101421       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
101422     }
101423   }
101424 }
101425 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
101426 
101427 
101428 /*
101429 ** The input to this routine is an WhereTerm structure with only the
101430 ** "pExpr" field filled in.  The job of this routine is to analyze the
101431 ** subexpression and populate all the other fields of the WhereTerm
101432 ** structure.
101433 **
101434 ** If the expression is of the form "<expr> <op> X" it gets commuted
101435 ** to the standard form of "X <op> <expr>".
101436 **
101437 ** If the expression is of the form "X <op> Y" where both X and Y are
101438 ** columns, then the original expression is unchanged and a new virtual
101439 ** term of the form "Y <op> X" is added to the WHERE clause and
101440 ** analyzed separately.  The original term is marked with TERM_COPIED
101441 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
101442 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
101443 ** is a commuted copy of a prior term.)  The original term has nChild=1
101444 ** and the copy has idxParent set to the index of the original term.
101445 */
101446 static void exprAnalyze(
101447   SrcList *pSrc,            /* the FROM clause */
101448   WhereClause *pWC,         /* the WHERE clause */
101449   int idxTerm               /* Index of the term to be analyzed */
101450 ){
101451   WhereTerm *pTerm;                /* The term to be analyzed */
101452   WhereMaskSet *pMaskSet;          /* Set of table index masks */
101453   Expr *pExpr;                     /* The expression to be analyzed */
101454   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
101455   Bitmask prereqAll;               /* Prerequesites of pExpr */
101456   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
101457   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
101458   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
101459   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
101460   int op;                          /* Top-level operator.  pExpr->op */
101461   Parse *pParse = pWC->pParse;     /* Parsing context */
101462   sqlite3 *db = pParse->db;        /* Database connection */
101463 
101464   if( db->mallocFailed ){
101465     return;
101466   }
101467   pTerm = &pWC->a[idxTerm];
101468   pMaskSet = pWC->pMaskSet;
101469   pExpr = pTerm->pExpr;
101470   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
101471   op = pExpr->op;
101472   if( op==TK_IN ){
101473     assert( pExpr->pRight==0 );
101474     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
101475       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
101476     }else{
101477       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
101478     }
101479   }else if( op==TK_ISNULL ){
101480     pTerm->prereqRight = 0;
101481   }else{
101482     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
101483   }
101484   prereqAll = exprTableUsage(pMaskSet, pExpr);
101485   if( ExprHasProperty(pExpr, EP_FromJoin) ){
101486     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
101487     prereqAll |= x;
101488     extraRight = x-1;  /* ON clause terms may not be used with an index
101489                        ** on left table of a LEFT JOIN.  Ticket #3015 */
101490   }
101491   pTerm->prereqAll = prereqAll;
101492   pTerm->leftCursor = -1;
101493   pTerm->iParent = -1;
101494   pTerm->eOperator = 0;
101495   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
101496     Expr *pLeft = pExpr->pLeft;
101497     Expr *pRight = pExpr->pRight;
101498     if( pLeft->op==TK_COLUMN ){
101499       pTerm->leftCursor = pLeft->iTable;
101500       pTerm->u.leftColumn = pLeft->iColumn;
101501       pTerm->eOperator = operatorMask(op);
101502     }
101503     if( pRight && pRight->op==TK_COLUMN ){
101504       WhereTerm *pNew;
101505       Expr *pDup;
101506       if( pTerm->leftCursor>=0 ){
101507         int idxNew;
101508         pDup = sqlite3ExprDup(db, pExpr, 0);
101509         if( db->mallocFailed ){
101510           sqlite3ExprDelete(db, pDup);
101511           return;
101512         }
101513         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
101514         if( idxNew==0 ) return;
101515         pNew = &pWC->a[idxNew];
101516         pNew->iParent = idxTerm;
101517         pTerm = &pWC->a[idxTerm];
101518         pTerm->nChild = 1;
101519         pTerm->wtFlags |= TERM_COPIED;
101520       }else{
101521         pDup = pExpr;
101522         pNew = pTerm;
101523       }
101524       exprCommute(pParse, pDup);
101525       pLeft = pDup->pLeft;
101526       pNew->leftCursor = pLeft->iTable;
101527       pNew->u.leftColumn = pLeft->iColumn;
101528       testcase( (prereqLeft | extraRight) != prereqLeft );
101529       pNew->prereqRight = prereqLeft | extraRight;
101530       pNew->prereqAll = prereqAll;
101531       pNew->eOperator = operatorMask(pDup->op);
101532     }
101533   }
101534 
101535 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
101536   /* If a term is the BETWEEN operator, create two new virtual terms
101537   ** that define the range that the BETWEEN implements.  For example:
101538   **
101539   **      a BETWEEN b AND c
101540   **
101541   ** is converted into:
101542   **
101543   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
101544   **
101545   ** The two new terms are added onto the end of the WhereClause object.
101546   ** The new terms are "dynamic" and are children of the original BETWEEN
101547   ** term.  That means that if the BETWEEN term is coded, the children are
101548   ** skipped.  Or, if the children are satisfied by an index, the original
101549   ** BETWEEN term is skipped.
101550   */
101551   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
101552     ExprList *pList = pExpr->x.pList;
101553     int i;
101554     static const u8 ops[] = {TK_GE, TK_LE};
101555     assert( pList!=0 );
101556     assert( pList->nExpr==2 );
101557     for(i=0; i<2; i++){
101558       Expr *pNewExpr;
101559       int idxNew;
101560       pNewExpr = sqlite3PExpr(pParse, ops[i],
101561                              sqlite3ExprDup(db, pExpr->pLeft, 0),
101562                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
101563       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
101564       testcase( idxNew==0 );
101565       exprAnalyze(pSrc, pWC, idxNew);
101566       pTerm = &pWC->a[idxTerm];
101567       pWC->a[idxNew].iParent = idxTerm;
101568     }
101569     pTerm->nChild = 2;
101570   }
101571 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
101572 
101573 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
101574   /* Analyze a term that is composed of two or more subterms connected by
101575   ** an OR operator.
101576   */
101577   else if( pExpr->op==TK_OR ){
101578     assert( pWC->op==TK_AND );
101579     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
101580     pTerm = &pWC->a[idxTerm];
101581   }
101582 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
101583 
101584 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
101585   /* Add constraints to reduce the search space on a LIKE or GLOB
101586   ** operator.
101587   **
101588   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
101589   **
101590   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
101591   **
101592   ** The last character of the prefix "abc" is incremented to form the
101593   ** termination condition "abd".
101594   */
101595   if( pWC->op==TK_AND
101596    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
101597   ){
101598     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
101599     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
101600     Expr *pNewExpr1;
101601     Expr *pNewExpr2;
101602     int idxNew1;
101603     int idxNew2;
101604     CollSeq *pColl;    /* Collating sequence to use */
101605 
101606     pLeft = pExpr->x.pList->a[1].pExpr;
101607     pStr2 = sqlite3ExprDup(db, pStr1, 0);
101608     if( !db->mallocFailed ){
101609       u8 c, *pC;       /* Last character before the first wildcard */
101610       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
101611       c = *pC;
101612       if( noCase ){
101613         /* The point is to increment the last character before the first
101614         ** wildcard.  But if we increment '@', that will push it into the
101615         ** alphabetic range where case conversions will mess up the
101616         ** inequality.  To avoid this, make sure to also run the full
101617         ** LIKE on all candidate expressions by clearing the isComplete flag
101618         */
101619         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
101620 
101621 
101622         c = sqlite3UpperToLower[c];
101623       }
101624       *pC = c + 1;
101625     }
101626     pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
101627     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
101628                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
101629                      pStr1, 0);
101630     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
101631     testcase( idxNew1==0 );
101632     exprAnalyze(pSrc, pWC, idxNew1);
101633     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
101634                      sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
101635                      pStr2, 0);
101636     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
101637     testcase( idxNew2==0 );
101638     exprAnalyze(pSrc, pWC, idxNew2);
101639     pTerm = &pWC->a[idxTerm];
101640     if( isComplete ){
101641       pWC->a[idxNew1].iParent = idxTerm;
101642       pWC->a[idxNew2].iParent = idxTerm;
101643       pTerm->nChild = 2;
101644     }
101645   }
101646 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
101647 
101648 #ifndef SQLITE_OMIT_VIRTUALTABLE
101649   /* Add a WO_MATCH auxiliary term to the constraint set if the
101650   ** current expression is of the form:  column MATCH expr.
101651   ** This information is used by the xBestIndex methods of
101652   ** virtual tables.  The native query optimizer does not attempt
101653   ** to do anything with MATCH functions.
101654   */
101655   if( isMatchOfColumn(pExpr) ){
101656     int idxNew;
101657     Expr *pRight, *pLeft;
101658     WhereTerm *pNewTerm;
101659     Bitmask prereqColumn, prereqExpr;
101660 
101661     pRight = pExpr->x.pList->a[0].pExpr;
101662     pLeft = pExpr->x.pList->a[1].pExpr;
101663     prereqExpr = exprTableUsage(pMaskSet, pRight);
101664     prereqColumn = exprTableUsage(pMaskSet, pLeft);
101665     if( (prereqExpr & prereqColumn)==0 ){
101666       Expr *pNewExpr;
101667       pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
101668                               0, sqlite3ExprDup(db, pRight, 0), 0);
101669       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
101670       testcase( idxNew==0 );
101671       pNewTerm = &pWC->a[idxNew];
101672       pNewTerm->prereqRight = prereqExpr;
101673       pNewTerm->leftCursor = pLeft->iTable;
101674       pNewTerm->u.leftColumn = pLeft->iColumn;
101675       pNewTerm->eOperator = WO_MATCH;
101676       pNewTerm->iParent = idxTerm;
101677       pTerm = &pWC->a[idxTerm];
101678       pTerm->nChild = 1;
101679       pTerm->wtFlags |= TERM_COPIED;
101680       pNewTerm->prereqAll = pTerm->prereqAll;
101681     }
101682   }
101683 #endif /* SQLITE_OMIT_VIRTUALTABLE */
101684 
101685 #ifdef SQLITE_ENABLE_STAT2
101686   /* When sqlite_stat2 histogram data is available an operator of the
101687   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
101688   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
101689   ** virtual term of that form.
101690   **
101691   ** Note that the virtual term must be tagged with TERM_VNULL.  This
101692   ** TERM_VNULL tag will suppress the not-null check at the beginning
101693   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
101694   ** the start of the loop will prevent any results from being returned.
101695   */
101696   if( pExpr->op==TK_NOTNULL
101697    && pExpr->pLeft->op==TK_COLUMN
101698    && pExpr->pLeft->iColumn>=0
101699   ){
101700     Expr *pNewExpr;
101701     Expr *pLeft = pExpr->pLeft;
101702     int idxNew;
101703     WhereTerm *pNewTerm;
101704 
101705     pNewExpr = sqlite3PExpr(pParse, TK_GT,
101706                             sqlite3ExprDup(db, pLeft, 0),
101707                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
101708 
101709     idxNew = whereClauseInsert(pWC, pNewExpr,
101710                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
101711     if( idxNew ){
101712       pNewTerm = &pWC->a[idxNew];
101713       pNewTerm->prereqRight = 0;
101714       pNewTerm->leftCursor = pLeft->iTable;
101715       pNewTerm->u.leftColumn = pLeft->iColumn;
101716       pNewTerm->eOperator = WO_GT;
101717       pNewTerm->iParent = idxTerm;
101718       pTerm = &pWC->a[idxTerm];
101719       pTerm->nChild = 1;
101720       pTerm->wtFlags |= TERM_COPIED;
101721       pNewTerm->prereqAll = pTerm->prereqAll;
101722     }
101723   }
101724 #endif /* SQLITE_ENABLE_STAT2 */
101725 
101726   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
101727   ** an index for tables to the left of the join.
101728   */
101729   pTerm->prereqRight |= extraRight;
101730 }
101731 
101732 /*
101733 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
101734 ** a reference to any table other than the iBase table.
101735 */
101736 static int referencesOtherTables(
101737   ExprList *pList,          /* Search expressions in ths list */
101738   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
101739   int iFirst,               /* Be searching with the iFirst-th expression */
101740   int iBase                 /* Ignore references to this table */
101741 ){
101742   Bitmask allowed = ~getMask(pMaskSet, iBase);
101743   while( iFirst<pList->nExpr ){
101744     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
101745       return 1;
101746     }
101747   }
101748   return 0;
101749 }
101750 
101751 /*
101752 ** This function searches the expression list passed as the second argument
101753 ** for an expression of type TK_COLUMN that refers to the same column and
101754 ** uses the same collation sequence as the iCol'th column of index pIdx.
101755 ** Argument iBase is the cursor number used for the table that pIdx refers
101756 ** to.
101757 **
101758 ** If such an expression is found, its index in pList->a[] is returned. If
101759 ** no expression is found, -1 is returned.
101760 */
101761 static int findIndexCol(
101762   Parse *pParse,                  /* Parse context */
101763   ExprList *pList,                /* Expression list to search */
101764   int iBase,                      /* Cursor for table associated with pIdx */
101765   Index *pIdx,                    /* Index to match column of */
101766   int iCol                        /* Column of index to match */
101767 ){
101768   int i;
101769   const char *zColl = pIdx->azColl[iCol];
101770 
101771   for(i=0; i<pList->nExpr; i++){
101772     Expr *p = pList->a[i].pExpr;
101773     if( p->op==TK_COLUMN
101774      && p->iColumn==pIdx->aiColumn[iCol]
101775      && p->iTable==iBase
101776     ){
101777       CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
101778       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
101779         return i;
101780       }
101781     }
101782   }
101783 
101784   return -1;
101785 }
101786 
101787 /*
101788 ** This routine determines if pIdx can be used to assist in processing a
101789 ** DISTINCT qualifier. In other words, it tests whether or not using this
101790 ** index for the outer loop guarantees that rows with equal values for
101791 ** all expressions in the pDistinct list are delivered grouped together.
101792 **
101793 ** For example, the query
101794 **
101795 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
101796 **
101797 ** can benefit from any index on columns "b" and "c".
101798 */
101799 static int isDistinctIndex(
101800   Parse *pParse,                  /* Parsing context */
101801   WhereClause *pWC,               /* The WHERE clause */
101802   Index *pIdx,                    /* The index being considered */
101803   int base,                       /* Cursor number for the table pIdx is on */
101804   ExprList *pDistinct,            /* The DISTINCT expressions */
101805   int nEqCol                      /* Number of index columns with == */
101806 ){
101807   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
101808   int i;                          /* Iterator variable */
101809 
101810   if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
101811   testcase( pDistinct->nExpr==BMS-1 );
101812 
101813   /* Loop through all the expressions in the distinct list. If any of them
101814   ** are not simple column references, return early. Otherwise, test if the
101815   ** WHERE clause contains a "col=X" clause. If it does, the expression
101816   ** can be ignored. If it does not, and the column does not belong to the
101817   ** same table as index pIdx, return early. Finally, if there is no
101818   ** matching "col=X" expression and the column is on the same table as pIdx,
101819   ** set the corresponding bit in variable mask.
101820   */
101821   for(i=0; i<pDistinct->nExpr; i++){
101822     WhereTerm *pTerm;
101823     Expr *p = pDistinct->a[i].pExpr;
101824     if( p->op!=TK_COLUMN ) return 0;
101825     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
101826     if( pTerm ){
101827       Expr *pX = pTerm->pExpr;
101828       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
101829       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
101830       if( p1==p2 ) continue;
101831     }
101832     if( p->iTable!=base ) return 0;
101833     mask |= (((Bitmask)1) << i);
101834   }
101835 
101836   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
101837     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
101838     if( iExpr<0 ) break;
101839     mask &= ~(((Bitmask)1) << iExpr);
101840   }
101841 
101842   return (mask==0);
101843 }
101844 
101845 
101846 /*
101847 ** Return true if the DISTINCT expression-list passed as the third argument
101848 ** is redundant. A DISTINCT list is redundant if the database contains a
101849 ** UNIQUE index that guarantees that the result of the query will be distinct
101850 ** anyway.
101851 */
101852 static int isDistinctRedundant(
101853   Parse *pParse,
101854   SrcList *pTabList,
101855   WhereClause *pWC,
101856   ExprList *pDistinct
101857 ){
101858   Table *pTab;
101859   Index *pIdx;
101860   int i;
101861   int iBase;
101862 
101863   /* If there is more than one table or sub-select in the FROM clause of
101864   ** this query, then it will not be possible to show that the DISTINCT
101865   ** clause is redundant. */
101866   if( pTabList->nSrc!=1 ) return 0;
101867   iBase = pTabList->a[0].iCursor;
101868   pTab = pTabList->a[0].pTab;
101869 
101870   /* If any of the expressions is an IPK column on table iBase, then return
101871   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
101872   ** current SELECT is a correlated sub-query.
101873   */
101874   for(i=0; i<pDistinct->nExpr; i++){
101875     Expr *p = pDistinct->a[i].pExpr;
101876     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
101877   }
101878 
101879   /* Loop through all indices on the table, checking each to see if it makes
101880   ** the DISTINCT qualifier redundant. It does so if:
101881   **
101882   **   1. The index is itself UNIQUE, and
101883   **
101884   **   2. All of the columns in the index are either part of the pDistinct
101885   **      list, or else the WHERE clause contains a term of the form "col=X",
101886   **      where X is a constant value. The collation sequences of the
101887   **      comparison and select-list expressions must match those of the index.
101888   */
101889   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
101890     if( pIdx->onError==OE_None ) continue;
101891     for(i=0; i<pIdx->nColumn; i++){
101892       int iCol = pIdx->aiColumn[i];
101893       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
101894        && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
101895       ){
101896         break;
101897       }
101898     }
101899     if( i==pIdx->nColumn ){
101900       /* This index implies that the DISTINCT qualifier is redundant. */
101901       return 1;
101902     }
101903   }
101904 
101905   return 0;
101906 }
101907 
101908 /*
101909 ** This routine decides if pIdx can be used to satisfy the ORDER BY
101910 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
101911 ** ORDER BY clause, this routine returns 0.
101912 **
101913 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
101914 ** left-most table in the FROM clause of that same SELECT statement and
101915 ** the table has a cursor number of "base".  pIdx is an index on pTab.
101916 **
101917 ** nEqCol is the number of columns of pIdx that are used as equality
101918 ** constraints.  Any of these columns may be missing from the ORDER BY
101919 ** clause and the match can still be a success.
101920 **
101921 ** All terms of the ORDER BY that match against the index must be either
101922 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
101923 ** index do not need to satisfy this constraint.)  The *pbRev value is
101924 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
101925 ** the ORDER BY clause is all ASC.
101926 */
101927 static int isSortingIndex(
101928   Parse *pParse,          /* Parsing context */
101929   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
101930   Index *pIdx,            /* The index we are testing */
101931   int base,               /* Cursor number for the table to be sorted */
101932   ExprList *pOrderBy,     /* The ORDER BY clause */
101933   int nEqCol,             /* Number of index columns with == constraints */
101934   int wsFlags,            /* Index usages flags */
101935   int *pbRev              /* Set to 1 if ORDER BY is DESC */
101936 ){
101937   int i, j;                       /* Loop counters */
101938   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
101939   int nTerm;                      /* Number of ORDER BY terms */
101940   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
101941   sqlite3 *db = pParse->db;
101942 
101943   if( !pOrderBy ) return 0;
101944   if( wsFlags & WHERE_COLUMN_IN ) return 0;
101945   if( pIdx->bUnordered ) return 0;
101946 
101947   nTerm = pOrderBy->nExpr;
101948   assert( nTerm>0 );
101949 
101950   /* Argument pIdx must either point to a 'real' named index structure,
101951   ** or an index structure allocated on the stack by bestBtreeIndex() to
101952   ** represent the rowid index that is part of every table.  */
101953   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
101954 
101955   /* Match terms of the ORDER BY clause against columns of
101956   ** the index.
101957   **
101958   ** Note that indices have pIdx->nColumn regular columns plus
101959   ** one additional column containing the rowid.  The rowid column
101960   ** of the index is also allowed to match against the ORDER BY
101961   ** clause.
101962   */
101963   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
101964     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
101965     CollSeq *pColl;    /* The collating sequence of pExpr */
101966     int termSortOrder; /* Sort order for this term */
101967     int iColumn;       /* The i-th column of the index.  -1 for rowid */
101968     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
101969     const char *zColl; /* Name of the collating sequence for i-th index term */
101970 
101971     pExpr = pTerm->pExpr;
101972     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
101973       /* Can not use an index sort on anything that is not a column in the
101974       ** left-most table of the FROM clause */
101975       break;
101976     }
101977     pColl = sqlite3ExprCollSeq(pParse, pExpr);
101978     if( !pColl ){
101979       pColl = db->pDfltColl;
101980     }
101981     if( pIdx->zName && i<pIdx->nColumn ){
101982       iColumn = pIdx->aiColumn[i];
101983       if( iColumn==pIdx->pTable->iPKey ){
101984         iColumn = -1;
101985       }
101986       iSortOrder = pIdx->aSortOrder[i];
101987       zColl = pIdx->azColl[i];
101988     }else{
101989       iColumn = -1;
101990       iSortOrder = 0;
101991       zColl = pColl->zName;
101992     }
101993     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
101994       /* Term j of the ORDER BY clause does not match column i of the index */
101995       if( i<nEqCol ){
101996         /* If an index column that is constrained by == fails to match an
101997         ** ORDER BY term, that is OK.  Just ignore that column of the index
101998         */
101999         continue;
102000       }else if( i==pIdx->nColumn ){
102001         /* Index column i is the rowid.  All other terms match. */
102002         break;
102003       }else{
102004         /* If an index column fails to match and is not constrained by ==
102005         ** then the index cannot satisfy the ORDER BY constraint.
102006         */
102007         return 0;
102008       }
102009     }
102010     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
102011     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
102012     assert( iSortOrder==0 || iSortOrder==1 );
102013     termSortOrder = iSortOrder ^ pTerm->sortOrder;
102014     if( i>nEqCol ){
102015       if( termSortOrder!=sortOrder ){
102016         /* Indices can only be used if all ORDER BY terms past the
102017         ** equality constraints are all either DESC or ASC. */
102018         return 0;
102019       }
102020     }else{
102021       sortOrder = termSortOrder;
102022     }
102023     j++;
102024     pTerm++;
102025     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
102026       /* If the indexed column is the primary key and everything matches
102027       ** so far and none of the ORDER BY terms to the right reference other
102028       ** tables in the join, then we are assured that the index can be used
102029       ** to sort because the primary key is unique and so none of the other
102030       ** columns will make any difference
102031       */
102032       j = nTerm;
102033     }
102034   }
102035 
102036   *pbRev = sortOrder!=0;
102037   if( j>=nTerm ){
102038     /* All terms of the ORDER BY clause are covered by this index so
102039     ** this index can be used for sorting. */
102040     return 1;
102041   }
102042   if( pIdx->onError!=OE_None && i==pIdx->nColumn
102043       && (wsFlags & WHERE_COLUMN_NULL)==0
102044       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
102045     /* All terms of this index match some prefix of the ORDER BY clause
102046     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
102047     ** clause reference other tables in a join.  If this is all true then
102048     ** the order by clause is superfluous.  Not that if the matching
102049     ** condition is IS NULL then the result is not necessarily unique
102050     ** even on a UNIQUE index, so disallow those cases. */
102051     return 1;
102052   }
102053   return 0;
102054 }
102055 
102056 /*
102057 ** Prepare a crude estimate of the logarithm of the input value.
102058 ** The results need not be exact.  This is only used for estimating
102059 ** the total cost of performing operations with O(logN) or O(NlogN)
102060 ** complexity.  Because N is just a guess, it is no great tragedy if
102061 ** logN is a little off.
102062 */
102063 static double estLog(double N){
102064   double logN = 1;
102065   double x = 10;
102066   while( N>x ){
102067     logN += 1;
102068     x *= 10;
102069   }
102070   return logN;
102071 }
102072 
102073 /*
102074 ** Two routines for printing the content of an sqlite3_index_info
102075 ** structure.  Used for testing and debugging only.  If neither
102076 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
102077 ** are no-ops.
102078 */
102079 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
102080 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
102081   int i;
102082   if( !sqlite3WhereTrace ) return;
102083   for(i=0; i<p->nConstraint; i++){
102084     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
102085        i,
102086        p->aConstraint[i].iColumn,
102087        p->aConstraint[i].iTermOffset,
102088        p->aConstraint[i].op,
102089        p->aConstraint[i].usable);
102090   }
102091   for(i=0; i<p->nOrderBy; i++){
102092     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
102093        i,
102094        p->aOrderBy[i].iColumn,
102095        p->aOrderBy[i].desc);
102096   }
102097 }
102098 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
102099   int i;
102100   if( !sqlite3WhereTrace ) return;
102101   for(i=0; i<p->nConstraint; i++){
102102     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
102103        i,
102104        p->aConstraintUsage[i].argvIndex,
102105        p->aConstraintUsage[i].omit);
102106   }
102107   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
102108   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
102109   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
102110   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
102111 }
102112 #else
102113 #define TRACE_IDX_INPUTS(A)
102114 #define TRACE_IDX_OUTPUTS(A)
102115 #endif
102116 
102117 /*
102118 ** Required because bestIndex() is called by bestOrClauseIndex()
102119 */
102120 static void bestIndex(
102121     Parse*, WhereClause*, struct SrcList_item*,
102122     Bitmask, Bitmask, ExprList*, WhereCost*);
102123 
102124 /*
102125 ** This routine attempts to find an scanning strategy that can be used
102126 ** to optimize an 'OR' expression that is part of a WHERE clause.
102127 **
102128 ** The table associated with FROM clause term pSrc may be either a
102129 ** regular B-Tree table or a virtual table.
102130 */
102131 static void bestOrClauseIndex(
102132   Parse *pParse,              /* The parsing context */
102133   WhereClause *pWC,           /* The WHERE clause */
102134   struct SrcList_item *pSrc,  /* The FROM clause term to search */
102135   Bitmask notReady,           /* Mask of cursors not available for indexing */
102136   Bitmask notValid,           /* Cursors not available for any purpose */
102137   ExprList *pOrderBy,         /* The ORDER BY clause */
102138   WhereCost *pCost            /* Lowest cost query plan */
102139 ){
102140 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
102141   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
102142   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
102143   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
102144   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
102145 
102146   /* No OR-clause optimization allowed if the INDEXED BY or NOT INDEXED clauses
102147   ** are used */
102148   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
102149     return;
102150   }
102151 
102152   /* Search the WHERE clause terms for a usable WO_OR term. */
102153   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102154     if( pTerm->eOperator==WO_OR
102155      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
102156      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
102157     ){
102158       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
102159       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
102160       WhereTerm *pOrTerm;
102161       int flags = WHERE_MULTI_OR;
102162       double rTotal = 0;
102163       double nRow = 0;
102164       Bitmask used = 0;
102165 
102166       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
102167         WhereCost sTermCost;
102168         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
102169           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
102170         ));
102171         if( pOrTerm->eOperator==WO_AND ){
102172           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
102173           bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
102174         }else if( pOrTerm->leftCursor==iCur ){
102175           WhereClause tempWC;
102176           tempWC.pParse = pWC->pParse;
102177           tempWC.pMaskSet = pWC->pMaskSet;
102178           tempWC.op = TK_AND;
102179           tempWC.a = pOrTerm;
102180           tempWC.nTerm = 1;
102181           bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
102182         }else{
102183           continue;
102184         }
102185         rTotal += sTermCost.rCost;
102186         nRow += sTermCost.plan.nRow;
102187         used |= sTermCost.used;
102188         if( rTotal>=pCost->rCost ) break;
102189       }
102190 
102191       /* If there is an ORDER BY clause, increase the scan cost to account
102192       ** for the cost of the sort. */
102193       if( pOrderBy!=0 ){
102194         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
102195                     rTotal, rTotal+nRow*estLog(nRow)));
102196         rTotal += nRow*estLog(nRow);
102197       }
102198 
102199       /* If the cost of scanning using this OR term for optimization is
102200       ** less than the current cost stored in pCost, replace the contents
102201       ** of pCost. */
102202       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
102203       if( rTotal<pCost->rCost ){
102204         pCost->rCost = rTotal;
102205         pCost->used = used;
102206         pCost->plan.nRow = nRow;
102207         pCost->plan.wsFlags = flags;
102208         pCost->plan.u.pTerm = pTerm;
102209       }
102210     }
102211   }
102212 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
102213 }
102214 
102215 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102216 /*
102217 ** Return TRUE if the WHERE clause term pTerm is of a form where it
102218 ** could be used with an index to access pSrc, assuming an appropriate
102219 ** index existed.
102220 */
102221 static int termCanDriveIndex(
102222   WhereTerm *pTerm,              /* WHERE clause term to check */
102223   struct SrcList_item *pSrc,     /* Table we are trying to access */
102224   Bitmask notReady               /* Tables in outer loops of the join */
102225 ){
102226   char aff;
102227   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
102228   if( pTerm->eOperator!=WO_EQ ) return 0;
102229   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
102230   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
102231   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
102232   return 1;
102233 }
102234 #endif
102235 
102236 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102237 /*
102238 ** If the query plan for pSrc specified in pCost is a full table scan
102239 ** and indexing is allows (if there is no NOT INDEXED clause) and it
102240 ** possible to construct a transient index that would perform better
102241 ** than a full table scan even when the cost of constructing the index
102242 ** is taken into account, then alter the query plan to use the
102243 ** transient index.
102244 */
102245 static void bestAutomaticIndex(
102246   Parse *pParse,              /* The parsing context */
102247   WhereClause *pWC,           /* The WHERE clause */
102248   struct SrcList_item *pSrc,  /* The FROM clause term to search */
102249   Bitmask notReady,           /* Mask of cursors that are not available */
102250   WhereCost *pCost            /* Lowest cost query plan */
102251 ){
102252   double nTableRow;           /* Rows in the input table */
102253   double logN;                /* log(nTableRow) */
102254   double costTempIdx;         /* per-query cost of the transient index */
102255   WhereTerm *pTerm;           /* A single term of the WHERE clause */
102256   WhereTerm *pWCEnd;          /* End of pWC->a[] */
102257   Table *pTable;              /* Table tht might be indexed */
102258 
102259   if( pParse->nQueryLoop<=(double)1 ){
102260     /* There is no point in building an automatic index for a single scan */
102261     return;
102262   }
102263   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
102264     /* Automatic indices are disabled at run-time */
102265     return;
102266   }
102267   if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
102268     /* We already have some kind of index in use for this query. */
102269     return;
102270   }
102271   if( pSrc->notIndexed ){
102272     /* The NOT INDEXED clause appears in the SQL. */
102273     return;
102274   }
102275   if( pSrc->isCorrelated ){
102276     /* The source is a correlated sub-query. No point in indexing it. */
102277     return;
102278   }
102279 
102280   assert( pParse->nQueryLoop >= (double)1 );
102281   pTable = pSrc->pTab;
102282   nTableRow = pTable->nRowEst;
102283   logN = estLog(nTableRow);
102284   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
102285   if( costTempIdx>=pCost->rCost ){
102286     /* The cost of creating the transient table would be greater than
102287     ** doing the full table scan */
102288     return;
102289   }
102290 
102291   /* Search for any equality comparison term */
102292   pWCEnd = &pWC->a[pWC->nTerm];
102293   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102294     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102295       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
102296                     pCost->rCost, costTempIdx));
102297       pCost->rCost = costTempIdx;
102298       pCost->plan.nRow = logN + 1;
102299       pCost->plan.wsFlags = WHERE_TEMP_INDEX;
102300       pCost->used = pTerm->prereqRight;
102301       break;
102302     }
102303   }
102304 }
102305 #else
102306 # define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
102307 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
102308 
102309 
102310 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
102311 /*
102312 ** Generate code to construct the Index object for an automatic index
102313 ** and to set up the WhereLevel object pLevel so that the code generator
102314 ** makes use of the automatic index.
102315 */
102316 static void constructAutomaticIndex(
102317   Parse *pParse,              /* The parsing context */
102318   WhereClause *pWC,           /* The WHERE clause */
102319   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
102320   Bitmask notReady,           /* Mask of cursors that are not available */
102321   WhereLevel *pLevel          /* Write new index here */
102322 ){
102323   int nColumn;                /* Number of columns in the constructed index */
102324   WhereTerm *pTerm;           /* A single term of the WHERE clause */
102325   WhereTerm *pWCEnd;          /* End of pWC->a[] */
102326   int nByte;                  /* Byte of memory needed for pIdx */
102327   Index *pIdx;                /* Object describing the transient index */
102328   Vdbe *v;                    /* Prepared statement under construction */
102329   int regIsInit;              /* Register set by initialization */
102330   int addrInit;               /* Address of the initialization bypass jump */
102331   Table *pTable;              /* The table being indexed */
102332   KeyInfo *pKeyinfo;          /* Key information for the index */
102333   int addrTop;                /* Top of the index fill loop */
102334   int regRecord;              /* Register holding an index record */
102335   int n;                      /* Column counter */
102336   int i;                      /* Loop counter */
102337   int mxBitCol;               /* Maximum column in pSrc->colUsed */
102338   CollSeq *pColl;             /* Collating sequence to on a column */
102339   Bitmask idxCols;            /* Bitmap of columns used for indexing */
102340   Bitmask extraCols;          /* Bitmap of additional columns */
102341 
102342   /* Generate code to skip over the creation and initialization of the
102343   ** transient index on 2nd and subsequent iterations of the loop. */
102344   v = pParse->pVdbe;
102345   assert( v!=0 );
102346   regIsInit = ++pParse->nMem;
102347   addrInit = sqlite3VdbeAddOp1(v, OP_Once, regIsInit);
102348 
102349   /* Count the number of columns that will be added to the index
102350   ** and used to match WHERE clause constraints */
102351   nColumn = 0;
102352   pTable = pSrc->pTab;
102353   pWCEnd = &pWC->a[pWC->nTerm];
102354   idxCols = 0;
102355   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102356     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102357       int iCol = pTerm->u.leftColumn;
102358       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
102359       testcase( iCol==BMS );
102360       testcase( iCol==BMS-1 );
102361       if( (idxCols & cMask)==0 ){
102362         nColumn++;
102363         idxCols |= cMask;
102364       }
102365     }
102366   }
102367   assert( nColumn>0 );
102368   pLevel->plan.nEq = nColumn;
102369 
102370   /* Count the number of additional columns needed to create a
102371   ** covering index.  A "covering index" is an index that contains all
102372   ** columns that are needed by the query.  With a covering index, the
102373   ** original table never needs to be accessed.  Automatic indices must
102374   ** be a covering index because the index will not be updated if the
102375   ** original table changes and the index and table cannot both be used
102376   ** if they go out of sync.
102377   */
102378   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
102379   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
102380   testcase( pTable->nCol==BMS-1 );
102381   testcase( pTable->nCol==BMS-2 );
102382   for(i=0; i<mxBitCol; i++){
102383     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
102384   }
102385   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
102386     nColumn += pTable->nCol - BMS + 1;
102387   }
102388   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
102389 
102390   /* Construct the Index object to describe this index */
102391   nByte = sizeof(Index);
102392   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
102393   nByte += nColumn*sizeof(char*);   /* Index.azColl */
102394   nByte += nColumn;                 /* Index.aSortOrder */
102395   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
102396   if( pIdx==0 ) return;
102397   pLevel->plan.u.pIdx = pIdx;
102398   pIdx->azColl = (char**)&pIdx[1];
102399   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
102400   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
102401   pIdx->zName = "auto-index";
102402   pIdx->nColumn = nColumn;
102403   pIdx->pTable = pTable;
102404   n = 0;
102405   idxCols = 0;
102406   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
102407     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
102408       int iCol = pTerm->u.leftColumn;
102409       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
102410       if( (idxCols & cMask)==0 ){
102411         Expr *pX = pTerm->pExpr;
102412         idxCols |= cMask;
102413         pIdx->aiColumn[n] = pTerm->u.leftColumn;
102414         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
102415         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
102416         n++;
102417       }
102418     }
102419   }
102420   assert( (u32)n==pLevel->plan.nEq );
102421 
102422   /* Add additional columns needed to make the automatic index into
102423   ** a covering index */
102424   for(i=0; i<mxBitCol; i++){
102425     if( extraCols & (((Bitmask)1)<<i) ){
102426       pIdx->aiColumn[n] = i;
102427       pIdx->azColl[n] = "BINARY";
102428       n++;
102429     }
102430   }
102431   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
102432     for(i=BMS-1; i<pTable->nCol; i++){
102433       pIdx->aiColumn[n] = i;
102434       pIdx->azColl[n] = "BINARY";
102435       n++;
102436     }
102437   }
102438   assert( n==nColumn );
102439 
102440   /* Create the automatic index */
102441   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
102442   assert( pLevel->iIdxCur>=0 );
102443   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
102444                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
102445   VdbeComment((v, "for %s", pTable->zName));
102446 
102447   /* Fill the automatic index with content */
102448   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
102449   regRecord = sqlite3GetTempReg(pParse);
102450   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
102451   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
102452   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
102453   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
102454   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
102455   sqlite3VdbeJumpHere(v, addrTop);
102456   sqlite3ReleaseTempReg(pParse, regRecord);
102457 
102458   /* Jump here when skipping the initialization */
102459   sqlite3VdbeJumpHere(v, addrInit);
102460 }
102461 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
102462 
102463 #ifndef SQLITE_OMIT_VIRTUALTABLE
102464 /*
102465 ** Allocate and populate an sqlite3_index_info structure. It is the
102466 ** responsibility of the caller to eventually release the structure
102467 ** by passing the pointer returned by this function to sqlite3_free().
102468 */
102469 static sqlite3_index_info *allocateIndexInfo(
102470   Parse *pParse,
102471   WhereClause *pWC,
102472   struct SrcList_item *pSrc,
102473   ExprList *pOrderBy
102474 ){
102475   int i, j;
102476   int nTerm;
102477   struct sqlite3_index_constraint *pIdxCons;
102478   struct sqlite3_index_orderby *pIdxOrderBy;
102479   struct sqlite3_index_constraint_usage *pUsage;
102480   WhereTerm *pTerm;
102481   int nOrderBy;
102482   sqlite3_index_info *pIdxInfo;
102483 
102484   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
102485 
102486   /* Count the number of possible WHERE clause constraints referring
102487   ** to this virtual table */
102488   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
102489     if( pTerm->leftCursor != pSrc->iCursor ) continue;
102490     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
102491     testcase( pTerm->eOperator==WO_IN );
102492     testcase( pTerm->eOperator==WO_ISNULL );
102493     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
102494     if( pTerm->wtFlags & TERM_VNULL ) continue;
102495     nTerm++;
102496   }
102497 
102498   /* If the ORDER BY clause contains only columns in the current
102499   ** virtual table then allocate space for the aOrderBy part of
102500   ** the sqlite3_index_info structure.
102501   */
102502   nOrderBy = 0;
102503   if( pOrderBy ){
102504     for(i=0; i<pOrderBy->nExpr; i++){
102505       Expr *pExpr = pOrderBy->a[i].pExpr;
102506       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
102507     }
102508     if( i==pOrderBy->nExpr ){
102509       nOrderBy = pOrderBy->nExpr;
102510     }
102511   }
102512 
102513   /* Allocate the sqlite3_index_info structure
102514   */
102515   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
102516                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
102517                            + sizeof(*pIdxOrderBy)*nOrderBy );
102518   if( pIdxInfo==0 ){
102519     sqlite3ErrorMsg(pParse, "out of memory");
102520     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
102521     return 0;
102522   }
102523 
102524   /* Initialize the structure.  The sqlite3_index_info structure contains
102525   ** many fields that are declared "const" to prevent xBestIndex from
102526   ** changing them.  We have to do some funky casting in order to
102527   ** initialize those fields.
102528   */
102529   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
102530   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
102531   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
102532   *(int*)&pIdxInfo->nConstraint = nTerm;
102533   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
102534   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
102535   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
102536   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
102537                                                                    pUsage;
102538 
102539   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
102540     if( pTerm->leftCursor != pSrc->iCursor ) continue;
102541     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
102542     testcase( pTerm->eOperator==WO_IN );
102543     testcase( pTerm->eOperator==WO_ISNULL );
102544     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
102545     if( pTerm->wtFlags & TERM_VNULL ) continue;
102546     pIdxCons[j].iColumn = pTerm->u.leftColumn;
102547     pIdxCons[j].iTermOffset = i;
102548     pIdxCons[j].op = (u8)pTerm->eOperator;
102549     /* The direct assignment in the previous line is possible only because
102550     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
102551     ** following asserts verify this fact. */
102552     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
102553     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
102554     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
102555     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
102556     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
102557     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
102558     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
102559     j++;
102560   }
102561   for(i=0; i<nOrderBy; i++){
102562     Expr *pExpr = pOrderBy->a[i].pExpr;
102563     pIdxOrderBy[i].iColumn = pExpr->iColumn;
102564     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
102565   }
102566 
102567   return pIdxInfo;
102568 }
102569 
102570 /*
102571 ** The table object reference passed as the second argument to this function
102572 ** must represent a virtual table. This function invokes the xBestIndex()
102573 ** method of the virtual table with the sqlite3_index_info pointer passed
102574 ** as the argument.
102575 **
102576 ** If an error occurs, pParse is populated with an error message and a
102577 ** non-zero value is returned. Otherwise, 0 is returned and the output
102578 ** part of the sqlite3_index_info structure is left populated.
102579 **
102580 ** Whether or not an error is returned, it is the responsibility of the
102581 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
102582 ** that this is required.
102583 */
102584 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
102585   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
102586   int i;
102587   int rc;
102588 
102589   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
102590   TRACE_IDX_INPUTS(p);
102591   rc = pVtab->pModule->xBestIndex(pVtab, p);
102592   TRACE_IDX_OUTPUTS(p);
102593 
102594   if( rc!=SQLITE_OK ){
102595     if( rc==SQLITE_NOMEM ){
102596       pParse->db->mallocFailed = 1;
102597     }else if( !pVtab->zErrMsg ){
102598       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
102599     }else{
102600       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
102601     }
102602   }
102603   sqlite3_free(pVtab->zErrMsg);
102604   pVtab->zErrMsg = 0;
102605 
102606   for(i=0; i<p->nConstraint; i++){
102607     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
102608       sqlite3ErrorMsg(pParse,
102609           "table %s: xBestIndex returned an invalid plan", pTab->zName);
102610     }
102611   }
102612 
102613   return pParse->nErr;
102614 }
102615 
102616 
102617 /*
102618 ** Compute the best index for a virtual table.
102619 **
102620 ** The best index is computed by the xBestIndex method of the virtual
102621 ** table module.  This routine is really just a wrapper that sets up
102622 ** the sqlite3_index_info structure that is used to communicate with
102623 ** xBestIndex.
102624 **
102625 ** In a join, this routine might be called multiple times for the
102626 ** same virtual table.  The sqlite3_index_info structure is created
102627 ** and initialized on the first invocation and reused on all subsequent
102628 ** invocations.  The sqlite3_index_info structure is also used when
102629 ** code is generated to access the virtual table.  The whereInfoDelete()
102630 ** routine takes care of freeing the sqlite3_index_info structure after
102631 ** everybody has finished with it.
102632 */
102633 static void bestVirtualIndex(
102634   Parse *pParse,                  /* The parsing context */
102635   WhereClause *pWC,               /* The WHERE clause */
102636   struct SrcList_item *pSrc,      /* The FROM clause term to search */
102637   Bitmask notReady,               /* Mask of cursors not available for index */
102638   Bitmask notValid,               /* Cursors not valid for any purpose */
102639   ExprList *pOrderBy,             /* The order by clause */
102640   WhereCost *pCost,               /* Lowest cost query plan */
102641   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
102642 ){
102643   Table *pTab = pSrc->pTab;
102644   sqlite3_index_info *pIdxInfo;
102645   struct sqlite3_index_constraint *pIdxCons;
102646   struct sqlite3_index_constraint_usage *pUsage;
102647   WhereTerm *pTerm;
102648   int i, j;
102649   int nOrderBy;
102650   double rCost;
102651 
102652   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
102653   ** malloc in allocateIndexInfo() fails and this function returns leaving
102654   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
102655   */
102656   memset(pCost, 0, sizeof(*pCost));
102657   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
102658 
102659   /* If the sqlite3_index_info structure has not been previously
102660   ** allocated and initialized, then allocate and initialize it now.
102661   */
102662   pIdxInfo = *ppIdxInfo;
102663   if( pIdxInfo==0 ){
102664     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
102665   }
102666   if( pIdxInfo==0 ){
102667     return;
102668   }
102669 
102670   /* At this point, the sqlite3_index_info structure that pIdxInfo points
102671   ** to will have been initialized, either during the current invocation or
102672   ** during some prior invocation.  Now we just have to customize the
102673   ** details of pIdxInfo for the current invocation and pass it to
102674   ** xBestIndex.
102675   */
102676 
102677   /* The module name must be defined. Also, by this point there must
102678   ** be a pointer to an sqlite3_vtab structure. Otherwise
102679   ** sqlite3ViewGetColumnNames() would have picked up the error.
102680   */
102681   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
102682   assert( sqlite3GetVTable(pParse->db, pTab) );
102683 
102684   /* Set the aConstraint[].usable fields and initialize all
102685   ** output variables to zero.
102686   **
102687   ** aConstraint[].usable is true for constraints where the right-hand
102688   ** side contains only references to tables to the left of the current
102689   ** table.  In other words, if the constraint is of the form:
102690   **
102691   **           column = expr
102692   **
102693   ** and we are evaluating a join, then the constraint on column is
102694   ** only valid if all tables referenced in expr occur to the left
102695   ** of the table containing column.
102696   **
102697   ** The aConstraints[] array contains entries for all constraints
102698   ** on the current table.  That way we only have to compute it once
102699   ** even though we might try to pick the best index multiple times.
102700   ** For each attempt at picking an index, the order of tables in the
102701   ** join might be different so we have to recompute the usable flag
102702   ** each time.
102703   */
102704   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
102705   pUsage = pIdxInfo->aConstraintUsage;
102706   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
102707     j = pIdxCons->iTermOffset;
102708     pTerm = &pWC->a[j];
102709     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
102710   }
102711   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
102712   if( pIdxInfo->needToFreeIdxStr ){
102713     sqlite3_free(pIdxInfo->idxStr);
102714   }
102715   pIdxInfo->idxStr = 0;
102716   pIdxInfo->idxNum = 0;
102717   pIdxInfo->needToFreeIdxStr = 0;
102718   pIdxInfo->orderByConsumed = 0;
102719   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
102720   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
102721   nOrderBy = pIdxInfo->nOrderBy;
102722   if( !pOrderBy ){
102723     pIdxInfo->nOrderBy = 0;
102724   }
102725 
102726   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
102727     return;
102728   }
102729 
102730   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
102731   for(i=0; i<pIdxInfo->nConstraint; i++){
102732     if( pUsage[i].argvIndex>0 ){
102733       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
102734     }
102735   }
102736 
102737   /* If there is an ORDER BY clause, and the selected virtual table index
102738   ** does not satisfy it, increase the cost of the scan accordingly. This
102739   ** matches the processing for non-virtual tables in bestBtreeIndex().
102740   */
102741   rCost = pIdxInfo->estimatedCost;
102742   if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
102743     rCost += estLog(rCost)*rCost;
102744   }
102745 
102746   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
102747   ** inital value of lowestCost in this loop. If it is, then the
102748   ** (cost<lowestCost) test below will never be true.
102749   **
102750   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
102751   ** is defined.
102752   */
102753   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
102754     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
102755   }else{
102756     pCost->rCost = rCost;
102757   }
102758   pCost->plan.u.pVtabIdx = pIdxInfo;
102759   if( pIdxInfo->orderByConsumed ){
102760     pCost->plan.wsFlags |= WHERE_ORDERBY;
102761   }
102762   pCost->plan.nEq = 0;
102763   pIdxInfo->nOrderBy = nOrderBy;
102764 
102765   /* Try to find a more efficient access pattern by using multiple indexes
102766   ** to optimize an OR expression within the WHERE clause.
102767   */
102768   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
102769 }
102770 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102771 
102772 /*
102773 ** Argument pIdx is a pointer to an index structure that has an array of
102774 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
102775 ** stored in Index.aSample. These samples divide the domain of values stored
102776 ** the index into (SQLITE_INDEX_SAMPLES+1) regions.
102777 ** Region 0 contains all values less than the first sample value. Region
102778 ** 1 contains values between the first and second samples.  Region 2 contains
102779 ** values between samples 2 and 3.  And so on.  Region SQLITE_INDEX_SAMPLES
102780 ** contains values larger than the last sample.
102781 **
102782 ** If the index contains many duplicates of a single value, then it is
102783 ** possible that two or more adjacent samples can hold the same value.
102784 ** When that is the case, the smallest possible region code is returned
102785 ** when roundUp is false and the largest possible region code is returned
102786 ** when roundUp is true.
102787 **
102788 ** If successful, this function determines which of the regions value
102789 ** pVal lies in, sets *piRegion to the region index (a value between 0
102790 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
102791 ** Or, if an OOM occurs while converting text values between encodings,
102792 ** SQLITE_NOMEM is returned and *piRegion is undefined.
102793 */
102794 #ifdef SQLITE_ENABLE_STAT2
102795 static int whereRangeRegion(
102796   Parse *pParse,              /* Database connection */
102797   Index *pIdx,                /* Index to consider domain of */
102798   sqlite3_value *pVal,        /* Value to consider */
102799   int roundUp,                /* Return largest valid region if true */
102800   int *piRegion               /* OUT: Region of domain in which value lies */
102801 ){
102802   assert( roundUp==0 || roundUp==1 );
102803   if( ALWAYS(pVal) ){
102804     IndexSample *aSample = pIdx->aSample;
102805     int i = 0;
102806     int eType = sqlite3_value_type(pVal);
102807 
102808     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
102809       double r = sqlite3_value_double(pVal);
102810       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
102811         if( aSample[i].eType==SQLITE_NULL ) continue;
102812         if( aSample[i].eType>=SQLITE_TEXT ) break;
102813         if( roundUp ){
102814           if( aSample[i].u.r>r ) break;
102815         }else{
102816           if( aSample[i].u.r>=r ) break;
102817         }
102818       }
102819     }else if( eType==SQLITE_NULL ){
102820       i = 0;
102821       if( roundUp ){
102822         while( i<SQLITE_INDEX_SAMPLES && aSample[i].eType==SQLITE_NULL ) i++;
102823       }
102824     }else{
102825       sqlite3 *db = pParse->db;
102826       CollSeq *pColl;
102827       const u8 *z;
102828       int n;
102829 
102830       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
102831       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
102832 
102833       if( eType==SQLITE_BLOB ){
102834         z = (const u8 *)sqlite3_value_blob(pVal);
102835         pColl = db->pDfltColl;
102836         assert( pColl->enc==SQLITE_UTF8 );
102837       }else{
102838         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
102839         if( pColl==0 ){
102840           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
102841                           *pIdx->azColl);
102842           return SQLITE_ERROR;
102843         }
102844         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
102845         if( !z ){
102846           return SQLITE_NOMEM;
102847         }
102848         assert( z && pColl && pColl->xCmp );
102849       }
102850       n = sqlite3ValueBytes(pVal, pColl->enc);
102851 
102852       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
102853         int c;
102854         int eSampletype = aSample[i].eType;
102855         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
102856         if( (eSampletype!=eType) ) break;
102857 #ifndef SQLITE_OMIT_UTF16
102858         if( pColl->enc!=SQLITE_UTF8 ){
102859           int nSample;
102860           char *zSample = sqlite3Utf8to16(
102861               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
102862           );
102863           if( !zSample ){
102864             assert( db->mallocFailed );
102865             return SQLITE_NOMEM;
102866           }
102867           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
102868           sqlite3DbFree(db, zSample);
102869         }else
102870 #endif
102871         {
102872           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
102873         }
102874         if( c-roundUp>=0 ) break;
102875       }
102876     }
102877 
102878     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
102879     *piRegion = i;
102880   }
102881   return SQLITE_OK;
102882 }
102883 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
102884 
102885 /*
102886 ** If expression pExpr represents a literal value, set *pp to point to
102887 ** an sqlite3_value structure containing the same value, with affinity
102888 ** aff applied to it, before returning. It is the responsibility of the
102889 ** caller to eventually release this structure by passing it to
102890 ** sqlite3ValueFree().
102891 **
102892 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
102893 ** is an SQL variable that currently has a non-NULL value bound to it,
102894 ** create an sqlite3_value structure containing this value, again with
102895 ** affinity aff applied to it, instead.
102896 **
102897 ** If neither of the above apply, set *pp to NULL.
102898 **
102899 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
102900 */
102901 #ifdef SQLITE_ENABLE_STAT2
102902 static int valueFromExpr(
102903   Parse *pParse,
102904   Expr *pExpr,
102905   u8 aff,
102906   sqlite3_value **pp
102907 ){
102908   if( pExpr->op==TK_VARIABLE
102909    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
102910   ){
102911     int iVar = pExpr->iColumn;
102912     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar); /* IMP: R-23257-02778 */
102913     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
102914     return SQLITE_OK;
102915   }
102916   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
102917 }
102918 #endif
102919 
102920 /*
102921 ** This function is used to estimate the number of rows that will be visited
102922 ** by scanning an index for a range of values. The range may have an upper
102923 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
102924 ** and lower bounds are represented by pLower and pUpper respectively. For
102925 ** example, assuming that index p is on t1(a):
102926 **
102927 **   ... FROM t1 WHERE a > ? AND a < ? ...
102928 **                    |_____|   |_____|
102929 **                       |         |
102930 **                     pLower    pUpper
102931 **
102932 ** If either of the upper or lower bound is not present, then NULL is passed in
102933 ** place of the corresponding WhereTerm.
102934 **
102935 ** The nEq parameter is passed the index of the index column subject to the
102936 ** range constraint. Or, equivalently, the number of equality constraints
102937 ** optimized by the proposed index scan. For example, assuming index p is
102938 ** on t1(a, b), and the SQL query is:
102939 **
102940 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
102941 **
102942 ** then nEq should be passed the value 1 (as the range restricted column,
102943 ** b, is the second left-most column of the index). Or, if the query is:
102944 **
102945 **   ... FROM t1 WHERE a > ? AND a < ? ...
102946 **
102947 ** then nEq should be passed 0.
102948 **
102949 ** The returned value is an integer between 1 and 100, inclusive. A return
102950 ** value of 1 indicates that the proposed range scan is expected to visit
102951 ** approximately 1/100th (1%) of the rows selected by the nEq equality
102952 ** constraints (if any). A return value of 100 indicates that it is expected
102953 ** that the range scan will visit every row (100%) selected by the equality
102954 ** constraints.
102955 **
102956 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
102957 ** reduces the search space by 3/4ths.  Hence a single constraint (x>?)
102958 ** results in a return of 25 and a range constraint (x>? AND x<?) results
102959 ** in a return of 6.
102960 */
102961 static int whereRangeScanEst(
102962   Parse *pParse,       /* Parsing & code generating context */
102963   Index *p,            /* The index containing the range-compared column; "x" */
102964   int nEq,             /* index into p->aCol[] of the range-compared column */
102965   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
102966   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
102967   int *piEst           /* OUT: Return value */
102968 ){
102969   int rc = SQLITE_OK;
102970 
102971 #ifdef SQLITE_ENABLE_STAT2
102972 
102973   if( nEq==0 && p->aSample ){
102974     sqlite3_value *pLowerVal = 0;
102975     sqlite3_value *pUpperVal = 0;
102976     int iEst;
102977     int iLower = 0;
102978     int iUpper = SQLITE_INDEX_SAMPLES;
102979     int roundUpUpper = 0;
102980     int roundUpLower = 0;
102981     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
102982 
102983     if( pLower ){
102984       Expr *pExpr = pLower->pExpr->pRight;
102985       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
102986       assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
102987       roundUpLower = (pLower->eOperator==WO_GT) ?1:0;
102988     }
102989     if( rc==SQLITE_OK && pUpper ){
102990       Expr *pExpr = pUpper->pExpr->pRight;
102991       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
102992       assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
102993       roundUpUpper = (pUpper->eOperator==WO_LE) ?1:0;
102994     }
102995 
102996     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
102997       sqlite3ValueFree(pLowerVal);
102998       sqlite3ValueFree(pUpperVal);
102999       goto range_est_fallback;
103000     }else if( pLowerVal==0 ){
103001       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
103002       if( pLower ) iLower = iUpper/2;
103003     }else if( pUpperVal==0 ){
103004       rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
103005       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
103006     }else{
103007       rc = whereRangeRegion(pParse, p, pUpperVal, roundUpUpper, &iUpper);
103008       if( rc==SQLITE_OK ){
103009         rc = whereRangeRegion(pParse, p, pLowerVal, roundUpLower, &iLower);
103010       }
103011     }
103012     WHERETRACE(("range scan regions: %d..%d\n", iLower, iUpper));
103013 
103014     iEst = iUpper - iLower;
103015     testcase( iEst==SQLITE_INDEX_SAMPLES );
103016     assert( iEst<=SQLITE_INDEX_SAMPLES );
103017     if( iEst<1 ){
103018       *piEst = 50/SQLITE_INDEX_SAMPLES;
103019     }else{
103020       *piEst = (iEst*100)/SQLITE_INDEX_SAMPLES;
103021     }
103022     sqlite3ValueFree(pLowerVal);
103023     sqlite3ValueFree(pUpperVal);
103024     return rc;
103025   }
103026 range_est_fallback:
103027 #else
103028   UNUSED_PARAMETER(pParse);
103029   UNUSED_PARAMETER(p);
103030   UNUSED_PARAMETER(nEq);
103031 #endif
103032   assert( pLower || pUpper );
103033   *piEst = 100;
103034   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *piEst /= 4;
103035   if( pUpper ) *piEst /= 4;
103036   return rc;
103037 }
103038 
103039 #ifdef SQLITE_ENABLE_STAT2
103040 /*
103041 ** Estimate the number of rows that will be returned based on
103042 ** an equality constraint x=VALUE and where that VALUE occurs in
103043 ** the histogram data.  This only works when x is the left-most
103044 ** column of an index and sqlite_stat2 histogram data is available
103045 ** for that index.  When pExpr==NULL that means the constraint is
103046 ** "x IS NULL" instead of "x=VALUE".
103047 **
103048 ** Write the estimated row count into *pnRow and return SQLITE_OK.
103049 ** If unable to make an estimate, leave *pnRow unchanged and return
103050 ** non-zero.
103051 **
103052 ** This routine can fail if it is unable to load a collating sequence
103053 ** required for string comparison, or if unable to allocate memory
103054 ** for a UTF conversion required for comparison.  The error is stored
103055 ** in the pParse structure.
103056 */
103057 static int whereEqualScanEst(
103058   Parse *pParse,       /* Parsing & code generating context */
103059   Index *p,            /* The index whose left-most column is pTerm */
103060   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
103061   double *pnRow        /* Write the revised row estimate here */
103062 ){
103063   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
103064   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
103065   u8 aff;                   /* Column affinity */
103066   int rc;                   /* Subfunction return code */
103067   double nRowEst;           /* New estimate of the number of rows */
103068 
103069   assert( p->aSample!=0 );
103070   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
103071   if( pExpr ){
103072     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
103073     if( rc ) goto whereEqualScanEst_cancel;
103074   }else{
103075     pRhs = sqlite3ValueNew(pParse->db);
103076   }
103077   if( pRhs==0 ) return SQLITE_NOTFOUND;
103078   rc = whereRangeRegion(pParse, p, pRhs, 0, &iLower);
103079   if( rc ) goto whereEqualScanEst_cancel;
103080   rc = whereRangeRegion(pParse, p, pRhs, 1, &iUpper);
103081   if( rc ) goto whereEqualScanEst_cancel;
103082   WHERETRACE(("equality scan regions: %d..%d\n", iLower, iUpper));
103083   if( iLower>=iUpper ){
103084     nRowEst = p->aiRowEst[0]/(SQLITE_INDEX_SAMPLES*2);
103085     if( nRowEst<*pnRow ) *pnRow = nRowEst;
103086   }else{
103087     nRowEst = (iUpper-iLower)*p->aiRowEst[0]/SQLITE_INDEX_SAMPLES;
103088     *pnRow = nRowEst;
103089   }
103090 
103091 whereEqualScanEst_cancel:
103092   sqlite3ValueFree(pRhs);
103093   return rc;
103094 }
103095 #endif /* defined(SQLITE_ENABLE_STAT2) */
103096 
103097 #ifdef SQLITE_ENABLE_STAT2
103098 /*
103099 ** Estimate the number of rows that will be returned based on
103100 ** an IN constraint where the right-hand side of the IN operator
103101 ** is a list of values.  Example:
103102 **
103103 **        WHERE x IN (1,2,3,4)
103104 **
103105 ** Write the estimated row count into *pnRow and return SQLITE_OK.
103106 ** If unable to make an estimate, leave *pnRow unchanged and return
103107 ** non-zero.
103108 **
103109 ** This routine can fail if it is unable to load a collating sequence
103110 ** required for string comparison, or if unable to allocate memory
103111 ** for a UTF conversion required for comparison.  The error is stored
103112 ** in the pParse structure.
103113 */
103114 static int whereInScanEst(
103115   Parse *pParse,       /* Parsing & code generating context */
103116   Index *p,            /* The index whose left-most column is pTerm */
103117   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
103118   double *pnRow        /* Write the revised row estimate here */
103119 ){
103120   sqlite3_value *pVal = 0;  /* One value from list */
103121   int iLower, iUpper;       /* Range of histogram regions containing pRhs */
103122   u8 aff;                   /* Column affinity */
103123   int rc = SQLITE_OK;       /* Subfunction return code */
103124   double nRowEst;           /* New estimate of the number of rows */
103125   int nSpan = 0;            /* Number of histogram regions spanned */
103126   int nSingle = 0;          /* Histogram regions hit by a single value */
103127   int nNotFound = 0;        /* Count of values that are not constants */
103128   int i;                               /* Loop counter */
103129   u8 aSpan[SQLITE_INDEX_SAMPLES+1];    /* Histogram regions that are spanned */
103130   u8 aSingle[SQLITE_INDEX_SAMPLES+1];  /* Histogram regions hit once */
103131 
103132   assert( p->aSample!=0 );
103133   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
103134   memset(aSpan, 0, sizeof(aSpan));
103135   memset(aSingle, 0, sizeof(aSingle));
103136   for(i=0; i<pList->nExpr; i++){
103137     sqlite3ValueFree(pVal);
103138     rc = valueFromExpr(pParse, pList->a[i].pExpr, aff, &pVal);
103139     if( rc ) break;
103140     if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){
103141       nNotFound++;
103142       continue;
103143     }
103144     rc = whereRangeRegion(pParse, p, pVal, 0, &iLower);
103145     if( rc ) break;
103146     rc = whereRangeRegion(pParse, p, pVal, 1, &iUpper);
103147     if( rc ) break;
103148     if( iLower>=iUpper ){
103149       aSingle[iLower] = 1;
103150     }else{
103151       assert( iLower>=0 && iUpper<=SQLITE_INDEX_SAMPLES );
103152       while( iLower<iUpper ) aSpan[iLower++] = 1;
103153     }
103154   }
103155   if( rc==SQLITE_OK ){
103156     for(i=nSpan=0; i<=SQLITE_INDEX_SAMPLES; i++){
103157       if( aSpan[i] ){
103158         nSpan++;
103159       }else if( aSingle[i] ){
103160         nSingle++;
103161       }
103162     }
103163     nRowEst = (nSpan*2+nSingle)*p->aiRowEst[0]/(2*SQLITE_INDEX_SAMPLES)
103164                + nNotFound*p->aiRowEst[1];
103165     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
103166     *pnRow = nRowEst;
103167     WHERETRACE(("IN row estimate: nSpan=%d, nSingle=%d, nNotFound=%d, est=%g\n",
103168                  nSpan, nSingle, nNotFound, nRowEst));
103169   }
103170   sqlite3ValueFree(pVal);
103171   return rc;
103172 }
103173 #endif /* defined(SQLITE_ENABLE_STAT2) */
103174 
103175 
103176 /*
103177 ** Find the best query plan for accessing a particular table.  Write the
103178 ** best query plan and its cost into the WhereCost object supplied as the
103179 ** last parameter.
103180 **
103181 ** The lowest cost plan wins.  The cost is an estimate of the amount of
103182 ** CPU and disk I/O needed to process the requested result.
103183 ** Factors that influence cost include:
103184 **
103185 **    *  The estimated number of rows that will be retrieved.  (The
103186 **       fewer the better.)
103187 **
103188 **    *  Whether or not sorting must occur.
103189 **
103190 **    *  Whether or not there must be separate lookups in the
103191 **       index and in the main table.
103192 **
103193 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
103194 ** the SQL statement, then this function only considers plans using the
103195 ** named index. If no such plan is found, then the returned cost is
103196 ** SQLITE_BIG_DBL. If a plan is found that uses the named index,
103197 ** then the cost is calculated in the usual way.
103198 **
103199 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
103200 ** in the SELECT statement, then no indexes are considered. However, the
103201 ** selected plan may still take advantage of the built-in rowid primary key
103202 ** index.
103203 */
103204 static void bestBtreeIndex(
103205   Parse *pParse,              /* The parsing context */
103206   WhereClause *pWC,           /* The WHERE clause */
103207   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103208   Bitmask notReady,           /* Mask of cursors not available for indexing */
103209   Bitmask notValid,           /* Cursors not available for any purpose */
103210   ExprList *pOrderBy,         /* The ORDER BY clause */
103211   ExprList *pDistinct,        /* The select-list if query is DISTINCT */
103212   WhereCost *pCost            /* Lowest cost query plan */
103213 ){
103214   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
103215   Index *pProbe;              /* An index we are evaluating */
103216   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
103217   int eqTermMask;             /* Current mask of valid equality operators */
103218   int idxEqTermMask;          /* Index mask of valid equality operators */
103219   Index sPk;                  /* A fake index object for the primary key */
103220   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
103221   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
103222   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
103223 
103224   /* Initialize the cost to a worst-case value */
103225   memset(pCost, 0, sizeof(*pCost));
103226   pCost->rCost = SQLITE_BIG_DBL;
103227 
103228   /* If the pSrc table is the right table of a LEFT JOIN then we may not
103229   ** use an index to satisfy IS NULL constraints on that table.  This is
103230   ** because columns might end up being NULL if the table does not match -
103231   ** a circumstance which the index cannot help us discover.  Ticket #2177.
103232   */
103233   if( pSrc->jointype & JT_LEFT ){
103234     idxEqTermMask = WO_EQ|WO_IN;
103235   }else{
103236     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
103237   }
103238 
103239   if( pSrc->pIndex ){
103240     /* An INDEXED BY clause specifies a particular index to use */
103241     pIdx = pProbe = pSrc->pIndex;
103242     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
103243     eqTermMask = idxEqTermMask;
103244   }else{
103245     /* There is no INDEXED BY clause.  Create a fake Index object in local
103246     ** variable sPk to represent the rowid primary key index.  Make this
103247     ** fake index the first in a chain of Index objects with all of the real
103248     ** indices to follow */
103249     Index *pFirst;                  /* First of real indices on the table */
103250     memset(&sPk, 0, sizeof(Index));
103251     sPk.nColumn = 1;
103252     sPk.aiColumn = &aiColumnPk;
103253     sPk.aiRowEst = aiRowEstPk;
103254     sPk.onError = OE_Replace;
103255     sPk.pTable = pSrc->pTab;
103256     aiRowEstPk[0] = pSrc->pTab->nRowEst;
103257     aiRowEstPk[1] = 1;
103258     pFirst = pSrc->pTab->pIndex;
103259     if( pSrc->notIndexed==0 ){
103260       /* The real indices of the table are only considered if the
103261       ** NOT INDEXED qualifier is omitted from the FROM clause */
103262       sPk.pNext = pFirst;
103263     }
103264     pProbe = &sPk;
103265     wsFlagMask = ~(
103266         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
103267     );
103268     eqTermMask = WO_EQ|WO_IN;
103269     pIdx = 0;
103270   }
103271 
103272   /* Loop over all indices looking for the best one to use
103273   */
103274   for(; pProbe; pIdx=pProbe=pProbe->pNext){
103275     const unsigned int * const aiRowEst = pProbe->aiRowEst;
103276     double cost;                /* Cost of using pProbe */
103277     double nRow;                /* Estimated number of rows in result set */
103278     double log10N;              /* base-10 logarithm of nRow (inexact) */
103279     int rev;                    /* True to scan in reverse order */
103280     int wsFlags = 0;
103281     Bitmask used = 0;
103282 
103283     /* The following variables are populated based on the properties of
103284     ** index being evaluated. They are then used to determine the expected
103285     ** cost and number of rows returned.
103286     **
103287     **  nEq:
103288     **    Number of equality terms that can be implemented using the index.
103289     **    In other words, the number of initial fields in the index that
103290     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
103291     **
103292     **  nInMul:
103293     **    The "in-multiplier". This is an estimate of how many seek operations
103294     **    SQLite must perform on the index in question. For example, if the
103295     **    WHERE clause is:
103296     **
103297     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
103298     **
103299     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
103300     **    set to 9. Given the same schema and either of the following WHERE
103301     **    clauses:
103302     **
103303     **      WHERE a =  1
103304     **      WHERE a >= 2
103305     **
103306     **    nInMul is set to 1.
103307     **
103308     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
103309     **    the sub-select is assumed to return 25 rows for the purposes of
103310     **    determining nInMul.
103311     **
103312     **  bInEst:
103313     **    Set to true if there was at least one "x IN (SELECT ...)" term used
103314     **    in determining the value of nInMul.  Note that the RHS of the
103315     **    IN operator must be a SELECT, not a value list, for this variable
103316     **    to be true.
103317     **
103318     **  estBound:
103319     **    An estimate on the amount of the table that must be searched.  A
103320     **    value of 100 means the entire table is searched.  Range constraints
103321     **    might reduce this to a value less than 100 to indicate that only
103322     **    a fraction of the table needs searching.  In the absence of
103323     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
103324     **    space to 1/4rd its original size.  So an x>? constraint reduces
103325     **    estBound to 25.  Two constraints (x>? AND x<?) reduce estBound to 6.
103326     **
103327     **  bSort:
103328     **    Boolean. True if there is an ORDER BY clause that will require an
103329     **    external sort (i.e. scanning the index being evaluated will not
103330     **    correctly order records).
103331     **
103332     **  bLookup:
103333     **    Boolean. True if a table lookup is required for each index entry
103334     **    visited.  In other words, true if this is not a covering index.
103335     **    This is always false for the rowid primary key index of a table.
103336     **    For other indexes, it is true unless all the columns of the table
103337     **    used by the SELECT statement are present in the index (such an
103338     **    index is sometimes described as a covering index).
103339     **    For example, given the index on (a, b), the second of the following
103340     **    two queries requires table b-tree lookups in order to find the value
103341     **    of column c, but the first does not because columns a and b are
103342     **    both available in the index.
103343     **
103344     **             SELECT a, b    FROM tbl WHERE a = 1;
103345     **             SELECT a, b, c FROM tbl WHERE a = 1;
103346     */
103347     int nEq;                      /* Number of == or IN terms matching index */
103348     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
103349     int nInMul = 1;               /* Number of distinct equalities to lookup */
103350     int estBound = 100;           /* Estimated reduction in search space */
103351     int nBound = 0;               /* Number of range constraints seen */
103352     int bSort = !!pOrderBy;       /* True if external sort required */
103353     int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
103354     int bLookup = 0;              /* True if not a covering index */
103355     WhereTerm *pTerm;             /* A single term of the WHERE clause */
103356 #ifdef SQLITE_ENABLE_STAT2
103357     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
103358 #endif
103359 
103360     /* Determine the values of nEq and nInMul */
103361     for(nEq=0; nEq<pProbe->nColumn; nEq++){
103362       int j = pProbe->aiColumn[nEq];
103363       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
103364       if( pTerm==0 ) break;
103365       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
103366       if( pTerm->eOperator & WO_IN ){
103367         Expr *pExpr = pTerm->pExpr;
103368         wsFlags |= WHERE_COLUMN_IN;
103369         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103370           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
103371           nInMul *= 25;
103372           bInEst = 1;
103373         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
103374           /* "x IN (value, value, ...)" */
103375           nInMul *= pExpr->x.pList->nExpr;
103376         }
103377       }else if( pTerm->eOperator & WO_ISNULL ){
103378         wsFlags |= WHERE_COLUMN_NULL;
103379       }
103380 #ifdef SQLITE_ENABLE_STAT2
103381       if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
103382 #endif
103383       used |= pTerm->prereqRight;
103384     }
103385 
103386     /* Determine the value of estBound. */
103387     if( nEq<pProbe->nColumn && pProbe->bUnordered==0 ){
103388       int j = pProbe->aiColumn[nEq];
103389       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
103390         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
103391         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
103392         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &estBound);
103393         if( pTop ){
103394           nBound = 1;
103395           wsFlags |= WHERE_TOP_LIMIT;
103396           used |= pTop->prereqRight;
103397         }
103398         if( pBtm ){
103399           nBound++;
103400           wsFlags |= WHERE_BTM_LIMIT;
103401           used |= pBtm->prereqRight;
103402         }
103403         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
103404       }
103405     }else if( pProbe->onError!=OE_None ){
103406       testcase( wsFlags & WHERE_COLUMN_IN );
103407       testcase( wsFlags & WHERE_COLUMN_NULL );
103408       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
103409         wsFlags |= WHERE_UNIQUE;
103410       }
103411     }
103412 
103413     /* If there is an ORDER BY clause and the index being considered will
103414     ** naturally scan rows in the required order, set the appropriate flags
103415     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
103416     ** will scan rows in a different order, set the bSort variable.  */
103417     if( isSortingIndex(
103418           pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
103419     ){
103420       bSort = 0;
103421       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
103422       wsFlags |= (rev ? WHERE_REVERSE : 0);
103423     }
103424 
103425     /* If there is a DISTINCT qualifier and this index will scan rows in
103426     ** order of the DISTINCT expressions, clear bDist and set the appropriate
103427     ** flags in wsFlags. */
103428     if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq) ){
103429       bDist = 0;
103430       wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
103431     }
103432 
103433     /* If currently calculating the cost of using an index (not the IPK
103434     ** index), determine if all required column data may be obtained without
103435     ** using the main table (i.e. if the index is a covering
103436     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
103437     ** wsFlags. Otherwise, set the bLookup variable to true.  */
103438     if( pIdx && wsFlags ){
103439       Bitmask m = pSrc->colUsed;
103440       int j;
103441       for(j=0; j<pIdx->nColumn; j++){
103442         int x = pIdx->aiColumn[j];
103443         if( x<BMS-1 ){
103444           m &= ~(((Bitmask)1)<<x);
103445         }
103446       }
103447       if( m==0 ){
103448         wsFlags |= WHERE_IDX_ONLY;
103449       }else{
103450         bLookup = 1;
103451       }
103452     }
103453 
103454     /*
103455     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
103456     ** constraint, do not let the estimate exceed half the rows in the table.
103457     */
103458     nRow = (double)(aiRowEst[nEq] * nInMul);
103459     if( bInEst && nRow*2>aiRowEst[0] ){
103460       nRow = aiRowEst[0]/2;
103461       nInMul = (int)(nRow / aiRowEst[nEq]);
103462     }
103463 
103464 #ifdef SQLITE_ENABLE_STAT2
103465     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
103466     ** and we do not think that values of x are unique and if histogram
103467     ** data is available for column x, then it might be possible
103468     ** to get a better estimate on the number of rows based on
103469     ** VALUE and how common that value is according to the histogram.
103470     */
103471     if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
103472       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
103473         testcase( pFirstTerm->eOperator==WO_EQ );
103474         testcase( pFirstTerm->eOperator==WO_ISNULL );
103475         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
103476       }else if( pFirstTerm->eOperator==WO_IN && bInEst==0 ){
103477         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
103478       }
103479     }
103480 #endif /* SQLITE_ENABLE_STAT2 */
103481 
103482     /* Adjust the number of output rows and downward to reflect rows
103483     ** that are excluded by range constraints.
103484     */
103485     nRow = (nRow * (double)estBound) / (double)100;
103486     if( nRow<1 ) nRow = 1;
103487 
103488     /* Experiments run on real SQLite databases show that the time needed
103489     ** to do a binary search to locate a row in a table or index is roughly
103490     ** log10(N) times the time to move from one row to the next row within
103491     ** a table or index.  The actual times can vary, with the size of
103492     ** records being an important factor.  Both moves and searches are
103493     ** slower with larger records, presumably because fewer records fit
103494     ** on one page and hence more pages have to be fetched.
103495     **
103496     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat2 tables do
103497     ** not give us data on the relative sizes of table and index records.
103498     ** So this computation assumes table records are about twice as big
103499     ** as index records
103500     */
103501     if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
103502       /* The cost of a full table scan is a number of move operations equal
103503       ** to the number of rows in the table.
103504       **
103505       ** We add an additional 4x penalty to full table scans.  This causes
103506       ** the cost function to err on the side of choosing an index over
103507       ** choosing a full scan.  This 4x full-scan penalty is an arguable
103508       ** decision and one which we expect to revisit in the future.  But
103509       ** it seems to be working well enough at the moment.
103510       */
103511       cost = aiRowEst[0]*4;
103512     }else{
103513       log10N = estLog(aiRowEst[0]);
103514       cost = nRow;
103515       if( pIdx ){
103516         if( bLookup ){
103517           /* For an index lookup followed by a table lookup:
103518           **    nInMul index searches to find the start of each index range
103519           **  + nRow steps through the index
103520           **  + nRow table searches to lookup the table entry using the rowid
103521           */
103522           cost += (nInMul + nRow)*log10N;
103523         }else{
103524           /* For a covering index:
103525           **     nInMul index searches to find the initial entry
103526           **   + nRow steps through the index
103527           */
103528           cost += nInMul*log10N;
103529         }
103530       }else{
103531         /* For a rowid primary key lookup:
103532         **    nInMult table searches to find the initial entry for each range
103533         **  + nRow steps through the table
103534         */
103535         cost += nInMul*log10N;
103536       }
103537     }
103538 
103539     /* Add in the estimated cost of sorting the result.  Actual experimental
103540     ** measurements of sorting performance in SQLite show that sorting time
103541     ** adds C*N*log10(N) to the cost, where N is the number of rows to be
103542     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
103543     ** difference and select C of 3.0.
103544     */
103545     if( bSort ){
103546       cost += nRow*estLog(nRow)*3;
103547     }
103548     if( bDist ){
103549       cost += nRow*estLog(nRow)*3;
103550     }
103551 
103552     /**** Cost of using this index has now been computed ****/
103553 
103554     /* If there are additional constraints on this table that cannot
103555     ** be used with the current index, but which might lower the number
103556     ** of output rows, adjust the nRow value accordingly.  This only
103557     ** matters if the current index is the least costly, so do not bother
103558     ** with this step if we already know this index will not be chosen.
103559     ** Also, never reduce the output row count below 2 using this step.
103560     **
103561     ** It is critical that the notValid mask be used here instead of
103562     ** the notReady mask.  When computing an "optimal" index, the notReady
103563     ** mask will only have one bit set - the bit for the current table.
103564     ** The notValid mask, on the other hand, always has all bits set for
103565     ** tables that are not in outer loops.  If notReady is used here instead
103566     ** of notValid, then a optimal index that depends on inner joins loops
103567     ** might be selected even when there exists an optimal index that has
103568     ** no such dependency.
103569     */
103570     if( nRow>2 && cost<=pCost->rCost ){
103571       int k;                       /* Loop counter */
103572       int nSkipEq = nEq;           /* Number of == constraints to skip */
103573       int nSkipRange = nBound;     /* Number of < constraints to skip */
103574       Bitmask thisTab;             /* Bitmap for pSrc */
103575 
103576       thisTab = getMask(pWC->pMaskSet, iCur);
103577       for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
103578         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
103579         if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
103580         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
103581           if( nSkipEq ){
103582             /* Ignore the first nEq equality matches since the index
103583             ** has already accounted for these */
103584             nSkipEq--;
103585           }else{
103586             /* Assume each additional equality match reduces the result
103587             ** set size by a factor of 10 */
103588             nRow /= 10;
103589           }
103590         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
103591           if( nSkipRange ){
103592             /* Ignore the first nSkipRange range constraints since the index
103593             ** has already accounted for these */
103594             nSkipRange--;
103595           }else{
103596             /* Assume each additional range constraint reduces the result
103597             ** set size by a factor of 3.  Indexed range constraints reduce
103598             ** the search space by a larger factor: 4.  We make indexed range
103599             ** more selective intentionally because of the subjective
103600             ** observation that indexed range constraints really are more
103601             ** selective in practice, on average. */
103602             nRow /= 3;
103603           }
103604         }else if( pTerm->eOperator!=WO_NOOP ){
103605           /* Any other expression lowers the output row count by half */
103606           nRow /= 2;
103607         }
103608       }
103609       if( nRow<2 ) nRow = 2;
103610     }
103611 
103612 
103613     WHERETRACE((
103614       "%s(%s): nEq=%d nInMul=%d estBound=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
103615       "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
103616       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
103617       nEq, nInMul, estBound, bSort, bLookup, wsFlags,
103618       notReady, log10N, nRow, cost, used
103619     ));
103620 
103621     /* If this index is the best we have seen so far, then record this
103622     ** index and its cost in the pCost structure.
103623     */
103624     if( (!pIdx || wsFlags)
103625      && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
103626     ){
103627       pCost->rCost = cost;
103628       pCost->used = used;
103629       pCost->plan.nRow = nRow;
103630       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
103631       pCost->plan.nEq = nEq;
103632       pCost->plan.u.pIdx = pIdx;
103633     }
103634 
103635     /* If there was an INDEXED BY clause, then only that one index is
103636     ** considered. */
103637     if( pSrc->pIndex ) break;
103638 
103639     /* Reset masks for the next index in the loop */
103640     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
103641     eqTermMask = idxEqTermMask;
103642   }
103643 
103644   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
103645   ** is set, then reverse the order that the index will be scanned
103646   ** in. This is used for application testing, to help find cases
103647   ** where application behaviour depends on the (undefined) order that
103648   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
103649   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
103650     pCost->plan.wsFlags |= WHERE_REVERSE;
103651   }
103652 
103653   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
103654   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
103655   assert( pSrc->pIndex==0
103656        || pCost->plan.u.pIdx==0
103657        || pCost->plan.u.pIdx==pSrc->pIndex
103658   );
103659 
103660   WHERETRACE(("best index is: %s\n",
103661     ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
103662          pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
103663   ));
103664 
103665   bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
103666   bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
103667   pCost->plan.wsFlags |= eqTermMask;
103668 }
103669 
103670 /*
103671 ** Find the query plan for accessing table pSrc->pTab. Write the
103672 ** best query plan and its cost into the WhereCost object supplied
103673 ** as the last parameter. This function may calculate the cost of
103674 ** both real and virtual table scans.
103675 */
103676 static void bestIndex(
103677   Parse *pParse,              /* The parsing context */
103678   WhereClause *pWC,           /* The WHERE clause */
103679   struct SrcList_item *pSrc,  /* The FROM clause term to search */
103680   Bitmask notReady,           /* Mask of cursors not available for indexing */
103681   Bitmask notValid,           /* Cursors not available for any purpose */
103682   ExprList *pOrderBy,         /* The ORDER BY clause */
103683   WhereCost *pCost            /* Lowest cost query plan */
103684 ){
103685 #ifndef SQLITE_OMIT_VIRTUALTABLE
103686   if( IsVirtual(pSrc->pTab) ){
103687     sqlite3_index_info *p = 0;
103688     bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
103689     if( p->needToFreeIdxStr ){
103690       sqlite3_free(p->idxStr);
103691     }
103692     sqlite3DbFree(pParse->db, p);
103693   }else
103694 #endif
103695   {
103696     bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
103697   }
103698 }
103699 
103700 /*
103701 ** Disable a term in the WHERE clause.  Except, do not disable the term
103702 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
103703 ** or USING clause of that join.
103704 **
103705 ** Consider the term t2.z='ok' in the following queries:
103706 **
103707 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
103708 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
103709 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
103710 **
103711 ** The t2.z='ok' is disabled in the in (2) because it originates
103712 ** in the ON clause.  The term is disabled in (3) because it is not part
103713 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
103714 **
103715 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
103716 ** completely satisfied by indices.
103717 **
103718 ** Disabling a term causes that term to not be tested in the inner loop
103719 ** of the join.  Disabling is an optimization.  When terms are satisfied
103720 ** by indices, we disable them to prevent redundant tests in the inner
103721 ** loop.  We would get the correct results if nothing were ever disabled,
103722 ** but joins might run a little slower.  The trick is to disable as much
103723 ** as we can without disabling too much.  If we disabled in (1), we'd get
103724 ** the wrong answer.  See ticket #813.
103725 */
103726 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
103727   if( pTerm
103728       && (pTerm->wtFlags & TERM_CODED)==0
103729       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
103730   ){
103731     pTerm->wtFlags |= TERM_CODED;
103732     if( pTerm->iParent>=0 ){
103733       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
103734       if( (--pOther->nChild)==0 ){
103735         disableTerm(pLevel, pOther);
103736       }
103737     }
103738   }
103739 }
103740 
103741 /*
103742 ** Code an OP_Affinity opcode to apply the column affinity string zAff
103743 ** to the n registers starting at base.
103744 **
103745 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
103746 ** beginning and end of zAff are ignored.  If all entries in zAff are
103747 ** SQLITE_AFF_NONE, then no code gets generated.
103748 **
103749 ** This routine makes its own copy of zAff so that the caller is free
103750 ** to modify zAff after this routine returns.
103751 */
103752 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
103753   Vdbe *v = pParse->pVdbe;
103754   if( zAff==0 ){
103755     assert( pParse->db->mallocFailed );
103756     return;
103757   }
103758   assert( v!=0 );
103759 
103760   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
103761   ** and end of the affinity string.
103762   */
103763   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
103764     n--;
103765     base++;
103766     zAff++;
103767   }
103768   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
103769     n--;
103770   }
103771 
103772   /* Code the OP_Affinity opcode if there is anything left to do. */
103773   if( n>0 ){
103774     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
103775     sqlite3VdbeChangeP4(v, -1, zAff, n);
103776     sqlite3ExprCacheAffinityChange(pParse, base, n);
103777   }
103778 }
103779 
103780 
103781 /*
103782 ** Generate code for a single equality term of the WHERE clause.  An equality
103783 ** term can be either X=expr or X IN (...).   pTerm is the term to be
103784 ** coded.
103785 **
103786 ** The current value for the constraint is left in register iReg.
103787 **
103788 ** For a constraint of the form X=expr, the expression is evaluated and its
103789 ** result is left on the stack.  For constraints of the form X IN (...)
103790 ** this routine sets up a loop that will iterate over all values of X.
103791 */
103792 static int codeEqualityTerm(
103793   Parse *pParse,      /* The parsing context */
103794   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
103795   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
103796   int iTarget         /* Attempt to leave results in this register */
103797 ){
103798   Expr *pX = pTerm->pExpr;
103799   Vdbe *v = pParse->pVdbe;
103800   int iReg;                  /* Register holding results */
103801 
103802   assert( iTarget>0 );
103803   if( pX->op==TK_EQ ){
103804     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
103805   }else if( pX->op==TK_ISNULL ){
103806     iReg = iTarget;
103807     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
103808 #ifndef SQLITE_OMIT_SUBQUERY
103809   }else{
103810     int eType;
103811     int iTab;
103812     struct InLoop *pIn;
103813 
103814     assert( pX->op==TK_IN );
103815     iReg = iTarget;
103816     eType = sqlite3FindInIndex(pParse, pX, 0);
103817     iTab = pX->iTable;
103818     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
103819     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
103820     if( pLevel->u.in.nIn==0 ){
103821       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
103822     }
103823     pLevel->u.in.nIn++;
103824     pLevel->u.in.aInLoop =
103825        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
103826                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
103827     pIn = pLevel->u.in.aInLoop;
103828     if( pIn ){
103829       pIn += pLevel->u.in.nIn - 1;
103830       pIn->iCur = iTab;
103831       if( eType==IN_INDEX_ROWID ){
103832         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
103833       }else{
103834         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
103835       }
103836       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
103837     }else{
103838       pLevel->u.in.nIn = 0;
103839     }
103840 #endif
103841   }
103842   disableTerm(pLevel, pTerm);
103843   return iReg;
103844 }
103845 
103846 /*
103847 ** Generate code that will evaluate all == and IN constraints for an
103848 ** index.
103849 **
103850 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
103851 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
103852 ** The index has as many as three equality constraints, but in this
103853 ** example, the third "c" value is an inequality.  So only two
103854 ** constraints are coded.  This routine will generate code to evaluate
103855 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
103856 ** in consecutive registers and the index of the first register is returned.
103857 **
103858 ** In the example above nEq==2.  But this subroutine works for any value
103859 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
103860 ** The only thing it does is allocate the pLevel->iMem memory cell and
103861 ** compute the affinity string.
103862 **
103863 ** This routine always allocates at least one memory cell and returns
103864 ** the index of that memory cell. The code that
103865 ** calls this routine will use that memory cell to store the termination
103866 ** key value of the loop.  If one or more IN operators appear, then
103867 ** this routine allocates an additional nEq memory cells for internal
103868 ** use.
103869 **
103870 ** Before returning, *pzAff is set to point to a buffer containing a
103871 ** copy of the column affinity string of the index allocated using
103872 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
103873 ** with equality constraints that use NONE affinity are set to
103874 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
103875 **
103876 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
103877 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
103878 **
103879 ** In the example above, the index on t1(a) has TEXT affinity. But since
103880 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
103881 ** no conversion should be attempted before using a t2.b value as part of
103882 ** a key to search the index. Hence the first byte in the returned affinity
103883 ** string in this example would be set to SQLITE_AFF_NONE.
103884 */
103885 static int codeAllEqualityTerms(
103886   Parse *pParse,        /* Parsing context */
103887   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
103888   WhereClause *pWC,     /* The WHERE clause */
103889   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
103890   int nExtraReg,        /* Number of extra registers to allocate */
103891   char **pzAff          /* OUT: Set to point to affinity string */
103892 ){
103893   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
103894   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
103895   Index *pIdx;                  /* The index being used for this loop */
103896   int iCur = pLevel->iTabCur;   /* The cursor of the table */
103897   WhereTerm *pTerm;             /* A single constraint term */
103898   int j;                        /* Loop counter */
103899   int regBase;                  /* Base register */
103900   int nReg;                     /* Number of registers to allocate */
103901   char *zAff;                   /* Affinity string to return */
103902 
103903   /* This module is only called on query plans that use an index. */
103904   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
103905   pIdx = pLevel->plan.u.pIdx;
103906 
103907   /* Figure out how many memory cells we will need then allocate them.
103908   */
103909   regBase = pParse->nMem + 1;
103910   nReg = pLevel->plan.nEq + nExtraReg;
103911   pParse->nMem += nReg;
103912 
103913   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
103914   if( !zAff ){
103915     pParse->db->mallocFailed = 1;
103916   }
103917 
103918   /* Evaluate the equality constraints
103919   */
103920   assert( pIdx->nColumn>=nEq );
103921   for(j=0; j<nEq; j++){
103922     int r1;
103923     int k = pIdx->aiColumn[j];
103924     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
103925     if( NEVER(pTerm==0) ) break;
103926     /* The following true for indices with redundant columns.
103927     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
103928     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
103929     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
103930     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
103931     if( r1!=regBase+j ){
103932       if( nReg==1 ){
103933         sqlite3ReleaseTempReg(pParse, regBase);
103934         regBase = r1;
103935       }else{
103936         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
103937       }
103938     }
103939     testcase( pTerm->eOperator & WO_ISNULL );
103940     testcase( pTerm->eOperator & WO_IN );
103941     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
103942       Expr *pRight = pTerm->pExpr->pRight;
103943       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
103944       if( zAff ){
103945         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
103946           zAff[j] = SQLITE_AFF_NONE;
103947         }
103948         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
103949           zAff[j] = SQLITE_AFF_NONE;
103950         }
103951       }
103952     }
103953   }
103954   *pzAff = zAff;
103955   return regBase;
103956 }
103957 
103958 #ifndef SQLITE_OMIT_EXPLAIN
103959 /*
103960 ** This routine is a helper for explainIndexRange() below
103961 **
103962 ** pStr holds the text of an expression that we are building up one term
103963 ** at a time.  This routine adds a new term to the end of the expression.
103964 ** Terms are separated by AND so add the "AND" text for second and subsequent
103965 ** terms only.
103966 */
103967 static void explainAppendTerm(
103968   StrAccum *pStr,             /* The text expression being built */
103969   int iTerm,                  /* Index of this term.  First is zero */
103970   const char *zColumn,        /* Name of the column */
103971   const char *zOp             /* Name of the operator */
103972 ){
103973   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
103974   sqlite3StrAccumAppend(pStr, zColumn, -1);
103975   sqlite3StrAccumAppend(pStr, zOp, 1);
103976   sqlite3StrAccumAppend(pStr, "?", 1);
103977 }
103978 
103979 /*
103980 ** Argument pLevel describes a strategy for scanning table pTab. This
103981 ** function returns a pointer to a string buffer containing a description
103982 ** of the subset of table rows scanned by the strategy in the form of an
103983 ** SQL expression. Or, if all rows are scanned, NULL is returned.
103984 **
103985 ** For example, if the query:
103986 **
103987 **   SELECT * FROM t1 WHERE a=1 AND b>2;
103988 **
103989 ** is run and there is an index on (a, b), then this function returns a
103990 ** string similar to:
103991 **
103992 **   "a=? AND b>?"
103993 **
103994 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
103995 ** It is the responsibility of the caller to free the buffer when it is
103996 ** no longer required.
103997 */
103998 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
103999   WherePlan *pPlan = &pLevel->plan;
104000   Index *pIndex = pPlan->u.pIdx;
104001   int nEq = pPlan->nEq;
104002   int i, j;
104003   Column *aCol = pTab->aCol;
104004   int *aiColumn = pIndex->aiColumn;
104005   StrAccum txt;
104006 
104007   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
104008     return 0;
104009   }
104010   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
104011   txt.db = db;
104012   sqlite3StrAccumAppend(&txt, " (", 2);
104013   for(i=0; i<nEq; i++){
104014     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
104015   }
104016 
104017   j = i;
104018   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
104019     explainAppendTerm(&txt, i++, aCol[aiColumn[j]].zName, ">");
104020   }
104021   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
104022     explainAppendTerm(&txt, i, aCol[aiColumn[j]].zName, "<");
104023   }
104024   sqlite3StrAccumAppend(&txt, ")", 1);
104025   return sqlite3StrAccumFinish(&txt);
104026 }
104027 
104028 /*
104029 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
104030 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
104031 ** record is added to the output to describe the table scan strategy in
104032 ** pLevel.
104033 */
104034 static void explainOneScan(
104035   Parse *pParse,                  /* Parse context */
104036   SrcList *pTabList,              /* Table list this loop refers to */
104037   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
104038   int iLevel,                     /* Value for "level" column of output */
104039   int iFrom,                      /* Value for "from" column of output */
104040   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
104041 ){
104042   if( pParse->explain==2 ){
104043     u32 flags = pLevel->plan.wsFlags;
104044     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
104045     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
104046     sqlite3 *db = pParse->db;     /* Database handle */
104047     char *zMsg;                   /* Text to add to EQP output */
104048     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
104049     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
104050     int isSearch;                 /* True for a SEARCH. False for SCAN. */
104051 
104052     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
104053 
104054     isSearch = (pLevel->plan.nEq>0)
104055              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
104056              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
104057 
104058     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
104059     if( pItem->pSelect ){
104060       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
104061     }else{
104062       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
104063     }
104064 
104065     if( pItem->zAlias ){
104066       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
104067     }
104068     if( (flags & WHERE_INDEXED)!=0 ){
104069       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
104070       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
104071           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
104072           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
104073           ((flags & WHERE_TEMP_INDEX)?"":" "),
104074           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
104075           zWhere
104076       );
104077       sqlite3DbFree(db, zWhere);
104078     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
104079       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
104080 
104081       if( flags&WHERE_ROWID_EQ ){
104082         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
104083       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
104084         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
104085       }else if( flags&WHERE_BTM_LIMIT ){
104086         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
104087       }else if( flags&WHERE_TOP_LIMIT ){
104088         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
104089       }
104090     }
104091 #ifndef SQLITE_OMIT_VIRTUALTABLE
104092     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
104093       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
104094       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
104095                   pVtabIdx->idxNum, pVtabIdx->idxStr);
104096     }
104097 #endif
104098     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
104099       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
104100       nRow = 1;
104101     }else{
104102       nRow = (sqlite3_int64)pLevel->plan.nRow;
104103     }
104104     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
104105     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
104106   }
104107 }
104108 #else
104109 # define explainOneScan(u,v,w,x,y,z)
104110 #endif /* SQLITE_OMIT_EXPLAIN */
104111 
104112 
104113 /*
104114 ** Generate code for the start of the iLevel-th loop in the WHERE clause
104115 ** implementation described by pWInfo.
104116 */
104117 static Bitmask codeOneLoopStart(
104118   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
104119   int iLevel,          /* Which level of pWInfo->a[] should be coded */
104120   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
104121   Bitmask notReady     /* Which tables are currently available */
104122 ){
104123   int j, k;            /* Loop counters */
104124   int iCur;            /* The VDBE cursor for the table */
104125   int addrNxt;         /* Where to jump to continue with the next IN case */
104126   int omitTable;       /* True if we use the index only */
104127   int bRev;            /* True if we need to scan in reverse order */
104128   WhereLevel *pLevel;  /* The where level to be coded */
104129   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
104130   WhereTerm *pTerm;               /* A WHERE clause term */
104131   Parse *pParse;                  /* Parsing context */
104132   Vdbe *v;                        /* The prepared stmt under constructions */
104133   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
104134   int addrBrk;                    /* Jump here to break out of the loop */
104135   int addrCont;                   /* Jump here to continue with next cycle */
104136   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
104137   int iReleaseReg = 0;      /* Temp register to free before returning */
104138 
104139   pParse = pWInfo->pParse;
104140   v = pParse->pVdbe;
104141   pWC = pWInfo->pWC;
104142   pLevel = &pWInfo->a[iLevel];
104143   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
104144   iCur = pTabItem->iCursor;
104145   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
104146   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
104147            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
104148 
104149   /* Create labels for the "break" and "continue" instructions
104150   ** for the current loop.  Jump to addrBrk to break out of a loop.
104151   ** Jump to cont to go immediately to the next iteration of the
104152   ** loop.
104153   **
104154   ** When there is an IN operator, we also have a "addrNxt" label that
104155   ** means to continue with the next IN value combination.  When
104156   ** there are no IN operators in the constraints, the "addrNxt" label
104157   ** is the same as "addrBrk".
104158   */
104159   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
104160   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
104161 
104162   /* If this is the right table of a LEFT OUTER JOIN, allocate and
104163   ** initialize a memory cell that records if this table matches any
104164   ** row of the left table of the join.
104165   */
104166   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
104167     pLevel->iLeftJoin = ++pParse->nMem;
104168     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
104169     VdbeComment((v, "init LEFT JOIN no-match flag"));
104170   }
104171 
104172 #ifndef SQLITE_OMIT_VIRTUALTABLE
104173   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
104174     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
104175     **          to access the data.
104176     */
104177     int iReg;   /* P3 Value for OP_VFilter */
104178     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
104179     int nConstraint = pVtabIdx->nConstraint;
104180     struct sqlite3_index_constraint_usage *aUsage =
104181                                                 pVtabIdx->aConstraintUsage;
104182     const struct sqlite3_index_constraint *aConstraint =
104183                                                 pVtabIdx->aConstraint;
104184 
104185     sqlite3ExprCachePush(pParse);
104186     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
104187     for(j=1; j<=nConstraint; j++){
104188       for(k=0; k<nConstraint; k++){
104189         if( aUsage[k].argvIndex==j ){
104190           int iTerm = aConstraint[k].iTermOffset;
104191           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
104192           break;
104193         }
104194       }
104195       if( k==nConstraint ) break;
104196     }
104197     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
104198     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
104199     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
104200                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
104201     pVtabIdx->needToFreeIdxStr = 0;
104202     for(j=0; j<nConstraint; j++){
104203       if( aUsage[j].omit ){
104204         int iTerm = aConstraint[j].iTermOffset;
104205         disableTerm(pLevel, &pWC->a[iTerm]);
104206       }
104207     }
104208     pLevel->op = OP_VNext;
104209     pLevel->p1 = iCur;
104210     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
104211     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
104212     sqlite3ExprCachePop(pParse, 1);
104213   }else
104214 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104215 
104216   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
104217     /* Case 1:  We can directly reference a single row using an
104218     **          equality comparison against the ROWID field.  Or
104219     **          we reference multiple rows using a "rowid IN (...)"
104220     **          construct.
104221     */
104222     iReleaseReg = sqlite3GetTempReg(pParse);
104223     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
104224     assert( pTerm!=0 );
104225     assert( pTerm->pExpr!=0 );
104226     assert( pTerm->leftCursor==iCur );
104227     assert( omitTable==0 );
104228     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104229     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
104230     addrNxt = pLevel->addrNxt;
104231     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
104232     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
104233     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104234     VdbeComment((v, "pk"));
104235     pLevel->op = OP_Noop;
104236   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
104237     /* Case 2:  We have an inequality comparison against the ROWID field.
104238     */
104239     int testOp = OP_Noop;
104240     int start;
104241     int memEndValue = 0;
104242     WhereTerm *pStart, *pEnd;
104243 
104244     assert( omitTable==0 );
104245     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
104246     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
104247     if( bRev ){
104248       pTerm = pStart;
104249       pStart = pEnd;
104250       pEnd = pTerm;
104251     }
104252     if( pStart ){
104253       Expr *pX;             /* The expression that defines the start bound */
104254       int r1, rTemp;        /* Registers for holding the start boundary */
104255 
104256       /* The following constant maps TK_xx codes into corresponding
104257       ** seek opcodes.  It depends on a particular ordering of TK_xx
104258       */
104259       const u8 aMoveOp[] = {
104260            /* TK_GT */  OP_SeekGt,
104261            /* TK_LE */  OP_SeekLe,
104262            /* TK_LT */  OP_SeekLt,
104263            /* TK_GE */  OP_SeekGe
104264       };
104265       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
104266       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
104267       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
104268 
104269       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104270       pX = pStart->pExpr;
104271       assert( pX!=0 );
104272       assert( pStart->leftCursor==iCur );
104273       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
104274       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
104275       VdbeComment((v, "pk"));
104276       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
104277       sqlite3ReleaseTempReg(pParse, rTemp);
104278       disableTerm(pLevel, pStart);
104279     }else{
104280       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
104281     }
104282     if( pEnd ){
104283       Expr *pX;
104284       pX = pEnd->pExpr;
104285       assert( pX!=0 );
104286       assert( pEnd->leftCursor==iCur );
104287       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104288       memEndValue = ++pParse->nMem;
104289       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
104290       if( pX->op==TK_LT || pX->op==TK_GT ){
104291         testOp = bRev ? OP_Le : OP_Ge;
104292       }else{
104293         testOp = bRev ? OP_Lt : OP_Gt;
104294       }
104295       disableTerm(pLevel, pEnd);
104296     }
104297     start = sqlite3VdbeCurrentAddr(v);
104298     pLevel->op = bRev ? OP_Prev : OP_Next;
104299     pLevel->p1 = iCur;
104300     pLevel->p2 = start;
104301     if( pStart==0 && pEnd==0 ){
104302       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
104303     }else{
104304       assert( pLevel->p5==0 );
104305     }
104306     if( testOp!=OP_Noop ){
104307       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
104308       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
104309       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104310       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
104311       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
104312     }
104313   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
104314     /* Case 3: A scan using an index.
104315     **
104316     **         The WHERE clause may contain zero or more equality
104317     **         terms ("==" or "IN" operators) that refer to the N
104318     **         left-most columns of the index. It may also contain
104319     **         inequality constraints (>, <, >= or <=) on the indexed
104320     **         column that immediately follows the N equalities. Only
104321     **         the right-most column can be an inequality - the rest must
104322     **         use the "==" and "IN" operators. For example, if the
104323     **         index is on (x,y,z), then the following clauses are all
104324     **         optimized:
104325     **
104326     **            x=5
104327     **            x=5 AND y=10
104328     **            x=5 AND y<10
104329     **            x=5 AND y>5 AND y<10
104330     **            x=5 AND y=5 AND z<=10
104331     **
104332     **         The z<10 term of the following cannot be used, only
104333     **         the x=5 term:
104334     **
104335     **            x=5 AND z<10
104336     **
104337     **         N may be zero if there are inequality constraints.
104338     **         If there are no inequality constraints, then N is at
104339     **         least one.
104340     **
104341     **         This case is also used when there are no WHERE clause
104342     **         constraints but an index is selected anyway, in order
104343     **         to force the output order to conform to an ORDER BY.
104344     */
104345     static const u8 aStartOp[] = {
104346       0,
104347       0,
104348       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
104349       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
104350       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
104351       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
104352       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
104353       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
104354     };
104355     static const u8 aEndOp[] = {
104356       OP_Noop,             /* 0: (!end_constraints) */
104357       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
104358       OP_IdxLT             /* 2: (end_constraints && bRev) */
104359     };
104360     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
104361     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
104362     int regBase;                 /* Base register holding constraint values */
104363     int r1;                      /* Temp register */
104364     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
104365     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
104366     int startEq;                 /* True if range start uses ==, >= or <= */
104367     int endEq;                   /* True if range end uses ==, >= or <= */
104368     int start_constraints;       /* Start of range is constrained */
104369     int nConstraint;             /* Number of constraint terms */
104370     Index *pIdx;                 /* The index we will be using */
104371     int iIdxCur;                 /* The VDBE cursor for the index */
104372     int nExtraReg = 0;           /* Number of extra registers needed */
104373     int op;                      /* Instruction opcode */
104374     char *zStartAff;             /* Affinity for start of range constraint */
104375     char *zEndAff;               /* Affinity for end of range constraint */
104376 
104377     pIdx = pLevel->plan.u.pIdx;
104378     iIdxCur = pLevel->iIdxCur;
104379     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
104380 
104381     /* If this loop satisfies a sort order (pOrderBy) request that
104382     ** was passed to this function to implement a "SELECT min(x) ..."
104383     ** query, then the caller will only allow the loop to run for
104384     ** a single iteration. This means that the first row returned
104385     ** should not have a NULL value stored in 'x'. If column 'x' is
104386     ** the first one after the nEq equality constraints in the index,
104387     ** this requires some special handling.
104388     */
104389     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
104390      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
104391      && (pIdx->nColumn>nEq)
104392     ){
104393       /* assert( pOrderBy->nExpr==1 ); */
104394       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
104395       isMinQuery = 1;
104396       nExtraReg = 1;
104397     }
104398 
104399     /* Find any inequality constraint terms for the start and end
104400     ** of the range.
104401     */
104402     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
104403       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
104404       nExtraReg = 1;
104405     }
104406     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
104407       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
104408       nExtraReg = 1;
104409     }
104410 
104411     /* Generate code to evaluate all constraint terms using == or IN
104412     ** and store the values of those terms in an array of registers
104413     ** starting at regBase.
104414     */
104415     regBase = codeAllEqualityTerms(
104416         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
104417     );
104418     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
104419     addrNxt = pLevel->addrNxt;
104420 
104421     /* If we are doing a reverse order scan on an ascending index, or
104422     ** a forward order scan on a descending index, interchange the
104423     ** start and end terms (pRangeStart and pRangeEnd).
104424     */
104425     if( nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
104426       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
104427     }
104428 
104429     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
104430     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
104431     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
104432     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
104433     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
104434     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
104435     start_constraints = pRangeStart || nEq>0;
104436 
104437     /* Seek the index cursor to the start of the range. */
104438     nConstraint = nEq;
104439     if( pRangeStart ){
104440       Expr *pRight = pRangeStart->pExpr->pRight;
104441       sqlite3ExprCode(pParse, pRight, regBase+nEq);
104442       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
104443         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
104444       }
104445       if( zStartAff ){
104446         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
104447           /* Since the comparison is to be performed with no conversions
104448           ** applied to the operands, set the affinity to apply to pRight to
104449           ** SQLITE_AFF_NONE.  */
104450           zStartAff[nEq] = SQLITE_AFF_NONE;
104451         }
104452         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
104453           zStartAff[nEq] = SQLITE_AFF_NONE;
104454         }
104455       }
104456       nConstraint++;
104457       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104458     }else if( isMinQuery ){
104459       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
104460       nConstraint++;
104461       startEq = 0;
104462       start_constraints = 1;
104463     }
104464     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
104465     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
104466     assert( op!=0 );
104467     testcase( op==OP_Rewind );
104468     testcase( op==OP_Last );
104469     testcase( op==OP_SeekGt );
104470     testcase( op==OP_SeekGe );
104471     testcase( op==OP_SeekLe );
104472     testcase( op==OP_SeekLt );
104473     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
104474 
104475     /* Load the value for the inequality constraint at the end of the
104476     ** range (if any).
104477     */
104478     nConstraint = nEq;
104479     if( pRangeEnd ){
104480       Expr *pRight = pRangeEnd->pExpr->pRight;
104481       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
104482       sqlite3ExprCode(pParse, pRight, regBase+nEq);
104483       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
104484         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
104485       }
104486       if( zEndAff ){
104487         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
104488           /* Since the comparison is to be performed with no conversions
104489           ** applied to the operands, set the affinity to apply to pRight to
104490           ** SQLITE_AFF_NONE.  */
104491           zEndAff[nEq] = SQLITE_AFF_NONE;
104492         }
104493         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
104494           zEndAff[nEq] = SQLITE_AFF_NONE;
104495         }
104496       }
104497       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
104498       nConstraint++;
104499       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
104500     }
104501     sqlite3DbFree(pParse->db, zStartAff);
104502     sqlite3DbFree(pParse->db, zEndAff);
104503 
104504     /* Top of the loop body */
104505     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
104506 
104507     /* Check if the index cursor is past the end of the range. */
104508     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
104509     testcase( op==OP_Noop );
104510     testcase( op==OP_IdxGE );
104511     testcase( op==OP_IdxLT );
104512     if( op!=OP_Noop ){
104513       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
104514       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
104515     }
104516 
104517     /* If there are inequality constraints, check that the value
104518     ** of the table column that the inequality contrains is not NULL.
104519     ** If it is, jump to the next iteration of the loop.
104520     */
104521     r1 = sqlite3GetTempReg(pParse);
104522     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
104523     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
104524     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
104525       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
104526       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
104527     }
104528     sqlite3ReleaseTempReg(pParse, r1);
104529 
104530     /* Seek the table cursor, if required */
104531     disableTerm(pLevel, pRangeStart);
104532     disableTerm(pLevel, pRangeEnd);
104533     if( !omitTable ){
104534       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
104535       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
104536       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
104537       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
104538     }
104539 
104540     /* Record the instruction used to terminate the loop. Disable
104541     ** WHERE clause terms made redundant by the index range scan.
104542     */
104543     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
104544       pLevel->op = OP_Noop;
104545     }else if( bRev ){
104546       pLevel->op = OP_Prev;
104547     }else{
104548       pLevel->op = OP_Next;
104549     }
104550     pLevel->p1 = iIdxCur;
104551   }else
104552 
104553 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
104554   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
104555     /* Case 4:  Two or more separately indexed terms connected by OR
104556     **
104557     ** Example:
104558     **
104559     **   CREATE TABLE t1(a,b,c,d);
104560     **   CREATE INDEX i1 ON t1(a);
104561     **   CREATE INDEX i2 ON t1(b);
104562     **   CREATE INDEX i3 ON t1(c);
104563     **
104564     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
104565     **
104566     ** In the example, there are three indexed terms connected by OR.
104567     ** The top of the loop looks like this:
104568     **
104569     **          Null       1                # Zero the rowset in reg 1
104570     **
104571     ** Then, for each indexed term, the following. The arguments to
104572     ** RowSetTest are such that the rowid of the current row is inserted
104573     ** into the RowSet. If it is already present, control skips the
104574     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
104575     **
104576     **        sqlite3WhereBegin(<term>)
104577     **          RowSetTest                  # Insert rowid into rowset
104578     **          Gosub      2 A
104579     **        sqlite3WhereEnd()
104580     **
104581     ** Following the above, code to terminate the loop. Label A, the target
104582     ** of the Gosub above, jumps to the instruction right after the Goto.
104583     **
104584     **          Null       1                # Zero the rowset in reg 1
104585     **          Goto       B                # The loop is finished.
104586     **
104587     **       A: <loop body>                 # Return data, whatever.
104588     **
104589     **          Return     2                # Jump back to the Gosub
104590     **
104591     **       B: <after the loop>
104592     **
104593     */
104594     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
104595     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
104596 
104597     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
104598     int regRowset = 0;                        /* Register for RowSet object */
104599     int regRowid = 0;                         /* Register holding rowid */
104600     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
104601     int iRetInit;                             /* Address of regReturn init */
104602     int untestedTerms = 0;             /* Some terms not completely tested */
104603     int ii;
104604 
104605     pTerm = pLevel->plan.u.pTerm;
104606     assert( pTerm!=0 );
104607     assert( pTerm->eOperator==WO_OR );
104608     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
104609     pOrWc = &pTerm->u.pOrInfo->wc;
104610     pLevel->op = OP_Return;
104611     pLevel->p1 = regReturn;
104612 
104613     /* Set up a new SrcList ni pOrTab containing the table being scanned
104614     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
104615     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
104616     */
104617     if( pWInfo->nLevel>1 ){
104618       int nNotReady;                 /* The number of notReady tables */
104619       struct SrcList_item *origSrc;     /* Original list of tables */
104620       nNotReady = pWInfo->nLevel - iLevel - 1;
104621       pOrTab = sqlite3StackAllocRaw(pParse->db,
104622                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
104623       if( pOrTab==0 ) return notReady;
104624       pOrTab->nAlloc = (i16)(nNotReady + 1);
104625       pOrTab->nSrc = pOrTab->nAlloc;
104626       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
104627       origSrc = pWInfo->pTabList->a;
104628       for(k=1; k<=nNotReady; k++){
104629         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
104630       }
104631     }else{
104632       pOrTab = pWInfo->pTabList;
104633     }
104634 
104635     /* Initialize the rowset register to contain NULL. An SQL NULL is
104636     ** equivalent to an empty rowset.
104637     **
104638     ** Also initialize regReturn to contain the address of the instruction
104639     ** immediately following the OP_Return at the bottom of the loop. This
104640     ** is required in a few obscure LEFT JOIN cases where control jumps
104641     ** over the top of the loop into the body of it. In this case the
104642     ** correct response for the end-of-loop code (the OP_Return) is to
104643     ** fall through to the next instruction, just as an OP_Next does if
104644     ** called on an uninitialized cursor.
104645     */
104646     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
104647       regRowset = ++pParse->nMem;
104648       regRowid = ++pParse->nMem;
104649       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
104650     }
104651     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
104652 
104653     for(ii=0; ii<pOrWc->nTerm; ii++){
104654       WhereTerm *pOrTerm = &pOrWc->a[ii];
104655       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
104656         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
104657         /* Loop through table entries that match term pOrTerm. */
104658         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0, 0,
104659                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
104660                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
104661         if( pSubWInfo ){
104662           explainOneScan(
104663               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
104664           );
104665           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
104666             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
104667             int r;
104668             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
104669                                          regRowid);
104670             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
104671                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
104672           }
104673           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
104674 
104675           /* The pSubWInfo->untestedTerms flag means that this OR term
104676           ** contained one or more AND term from a notReady table.  The
104677           ** terms from the notReady table could not be tested and will
104678           ** need to be tested later.
104679           */
104680           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
104681 
104682           /* Finish the loop through table entries that match term pOrTerm. */
104683           sqlite3WhereEnd(pSubWInfo);
104684         }
104685       }
104686     }
104687     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
104688     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
104689     sqlite3VdbeResolveLabel(v, iLoopBody);
104690 
104691     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
104692     if( !untestedTerms ) disableTerm(pLevel, pTerm);
104693   }else
104694 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104695 
104696   {
104697     /* Case 5:  There is no usable index.  We must do a complete
104698     **          scan of the entire table.
104699     */
104700     static const u8 aStep[] = { OP_Next, OP_Prev };
104701     static const u8 aStart[] = { OP_Rewind, OP_Last };
104702     assert( bRev==0 || bRev==1 );
104703     assert( omitTable==0 );
104704     pLevel->op = aStep[bRev];
104705     pLevel->p1 = iCur;
104706     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
104707     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
104708   }
104709   notReady &= ~getMask(pWC->pMaskSet, iCur);
104710 
104711   /* Insert code to test every subexpression that can be completely
104712   ** computed using the current set of tables.
104713   **
104714   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
104715   ** the use of indices become tests that are evaluated against each row of
104716   ** the relevant input tables.
104717   */
104718   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
104719     Expr *pE;
104720     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
104721     testcase( pTerm->wtFlags & TERM_CODED );
104722     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
104723     if( (pTerm->prereqAll & notReady)!=0 ){
104724       testcase( pWInfo->untestedTerms==0
104725                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
104726       pWInfo->untestedTerms = 1;
104727       continue;
104728     }
104729     pE = pTerm->pExpr;
104730     assert( pE!=0 );
104731     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
104732       continue;
104733     }
104734     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
104735     pTerm->wtFlags |= TERM_CODED;
104736   }
104737 
104738   /* For a LEFT OUTER JOIN, generate code that will record the fact that
104739   ** at least one row of the right table has matched the left table.
104740   */
104741   if( pLevel->iLeftJoin ){
104742     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
104743     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
104744     VdbeComment((v, "record LEFT JOIN hit"));
104745     sqlite3ExprCacheClear(pParse);
104746     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
104747       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
104748       testcase( pTerm->wtFlags & TERM_CODED );
104749       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
104750       if( (pTerm->prereqAll & notReady)!=0 ){
104751         assert( pWInfo->untestedTerms );
104752         continue;
104753       }
104754       assert( pTerm->pExpr );
104755       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
104756       pTerm->wtFlags |= TERM_CODED;
104757     }
104758   }
104759   sqlite3ReleaseTempReg(pParse, iReleaseReg);
104760 
104761   return notReady;
104762 }
104763 
104764 #if defined(SQLITE_TEST)
104765 /*
104766 ** The following variable holds a text description of query plan generated
104767 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
104768 ** overwrites the previous.  This information is used for testing and
104769 ** analysis only.
104770 */
104771 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
104772 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
104773 
104774 #endif /* SQLITE_TEST */
104775 
104776 
104777 /*
104778 ** Free a WhereInfo structure
104779 */
104780 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
104781   if( ALWAYS(pWInfo) ){
104782     int i;
104783     for(i=0; i<pWInfo->nLevel; i++){
104784       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
104785       if( pInfo ){
104786         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
104787         if( pInfo->needToFreeIdxStr ){
104788           sqlite3_free(pInfo->idxStr);
104789         }
104790         sqlite3DbFree(db, pInfo);
104791       }
104792       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
104793         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
104794         if( pIdx ){
104795           sqlite3DbFree(db, pIdx->zColAff);
104796           sqlite3DbFree(db, pIdx);
104797         }
104798       }
104799     }
104800     whereClauseClear(pWInfo->pWC);
104801     sqlite3DbFree(db, pWInfo);
104802   }
104803 }
104804 
104805 
104806 /*
104807 ** Generate the beginning of the loop used for WHERE clause processing.
104808 ** The return value is a pointer to an opaque structure that contains
104809 ** information needed to terminate the loop.  Later, the calling routine
104810 ** should invoke sqlite3WhereEnd() with the return value of this function
104811 ** in order to complete the WHERE clause processing.
104812 **
104813 ** If an error occurs, this routine returns NULL.
104814 **
104815 ** The basic idea is to do a nested loop, one loop for each table in
104816 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
104817 ** same as a SELECT with only a single table in the FROM clause.)  For
104818 ** example, if the SQL is this:
104819 **
104820 **       SELECT * FROM t1, t2, t3 WHERE ...;
104821 **
104822 ** Then the code generated is conceptually like the following:
104823 **
104824 **      foreach row1 in t1 do       \    Code generated
104825 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
104826 **          foreach row3 in t3 do   /
104827 **            ...
104828 **          end                     \    Code generated
104829 **        end                        |-- by sqlite3WhereEnd()
104830 **      end                         /
104831 **
104832 ** Note that the loops might not be nested in the order in which they
104833 ** appear in the FROM clause if a different order is better able to make
104834 ** use of indices.  Note also that when the IN operator appears in
104835 ** the WHERE clause, it might result in additional nested loops for
104836 ** scanning through all values on the right-hand side of the IN.
104837 **
104838 ** There are Btree cursors associated with each table.  t1 uses cursor
104839 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
104840 ** And so forth.  This routine generates code to open those VDBE cursors
104841 ** and sqlite3WhereEnd() generates the code to close them.
104842 **
104843 ** The code that sqlite3WhereBegin() generates leaves the cursors named
104844 ** in pTabList pointing at their appropriate entries.  The [...] code
104845 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
104846 ** data from the various tables of the loop.
104847 **
104848 ** If the WHERE clause is empty, the foreach loops must each scan their
104849 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
104850 ** the tables have indices and there are terms in the WHERE clause that
104851 ** refer to those indices, a complete table scan can be avoided and the
104852 ** code will run much faster.  Most of the work of this routine is checking
104853 ** to see if there are indices that can be used to speed up the loop.
104854 **
104855 ** Terms of the WHERE clause are also used to limit which rows actually
104856 ** make it to the "..." in the middle of the loop.  After each "foreach",
104857 ** terms of the WHERE clause that use only terms in that loop and outer
104858 ** loops are evaluated and if false a jump is made around all subsequent
104859 ** inner loops (or around the "..." if the test occurs within the inner-
104860 ** most loop)
104861 **
104862 ** OUTER JOINS
104863 **
104864 ** An outer join of tables t1 and t2 is conceptally coded as follows:
104865 **
104866 **    foreach row1 in t1 do
104867 **      flag = 0
104868 **      foreach row2 in t2 do
104869 **        start:
104870 **          ...
104871 **          flag = 1
104872 **      end
104873 **      if flag==0 then
104874 **        move the row2 cursor to a null row
104875 **        goto start
104876 **      fi
104877 **    end
104878 **
104879 ** ORDER BY CLAUSE PROCESSING
104880 **
104881 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
104882 ** if there is one.  If there is no ORDER BY clause or if this routine
104883 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
104884 **
104885 ** If an index can be used so that the natural output order of the table
104886 ** scan is correct for the ORDER BY clause, then that index is used and
104887 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
104888 ** unnecessary sort of the result set if an index appropriate for the
104889 ** ORDER BY clause already exists.
104890 **
104891 ** If the where clause loops cannot be arranged to provide the correct
104892 ** output order, then the *ppOrderBy is unchanged.
104893 */
104894 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
104895   Parse *pParse,        /* The parser context */
104896   SrcList *pTabList,    /* A list of all tables to be scanned */
104897   Expr *pWhere,         /* The WHERE clause */
104898   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
104899   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
104900   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
104901 ){
104902   int i;                     /* Loop counter */
104903   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
104904   int nTabList;              /* Number of elements in pTabList */
104905   WhereInfo *pWInfo;         /* Will become the return value of this function */
104906   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
104907   Bitmask notReady;          /* Cursors that are not yet positioned */
104908   WhereMaskSet *pMaskSet;    /* The expression mask set */
104909   WhereClause *pWC;               /* Decomposition of the WHERE clause */
104910   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
104911   WhereLevel *pLevel;             /* A single level in the pWInfo list */
104912   int iFrom;                      /* First unused FROM clause element */
104913   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
104914   sqlite3 *db;               /* Database connection */
104915 
104916   /* The number of tables in the FROM clause is limited by the number of
104917   ** bits in a Bitmask
104918   */
104919   testcase( pTabList->nSrc==BMS );
104920   if( pTabList->nSrc>BMS ){
104921     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
104922     return 0;
104923   }
104924 
104925   /* This function normally generates a nested loop for all tables in
104926   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
104927   ** only generate code for the first table in pTabList and assume that
104928   ** any cursors associated with subsequent tables are uninitialized.
104929   */
104930   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
104931 
104932   /* Allocate and initialize the WhereInfo structure that will become the
104933   ** return value. A single allocation is used to store the WhereInfo
104934   ** struct, the contents of WhereInfo.a[], the WhereClause structure
104935   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
104936   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
104937   ** some architectures. Hence the ROUND8() below.
104938   */
104939   db = pParse->db;
104940   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
104941   pWInfo = sqlite3DbMallocZero(db,
104942       nByteWInfo +
104943       sizeof(WhereClause) +
104944       sizeof(WhereMaskSet)
104945   );
104946   if( db->mallocFailed ){
104947     sqlite3DbFree(db, pWInfo);
104948     pWInfo = 0;
104949     goto whereBeginError;
104950   }
104951   pWInfo->nLevel = nTabList;
104952   pWInfo->pParse = pParse;
104953   pWInfo->pTabList = pTabList;
104954   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
104955   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
104956   pWInfo->wctrlFlags = wctrlFlags;
104957   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
104958   pMaskSet = (WhereMaskSet*)&pWC[1];
104959 
104960   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
104961   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
104962   if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
104963 
104964   /* Split the WHERE clause into separate subexpressions where each
104965   ** subexpression is separated by an AND operator.
104966   */
104967   initMaskSet(pMaskSet);
104968   whereClauseInit(pWC, pParse, pMaskSet);
104969   sqlite3ExprCodeConstants(pParse, pWhere);
104970   whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
104971 
104972   /* Special case: a WHERE clause that is constant.  Evaluate the
104973   ** expression and either jump over all of the code or fall thru.
104974   */
104975   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
104976     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
104977     pWhere = 0;
104978   }
104979 
104980   /* Assign a bit from the bitmask to every term in the FROM clause.
104981   **
104982   ** When assigning bitmask values to FROM clause cursors, it must be
104983   ** the case that if X is the bitmask for the N-th FROM clause term then
104984   ** the bitmask for all FROM clause terms to the left of the N-th term
104985   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
104986   ** its Expr.iRightJoinTable value to find the bitmask of the right table
104987   ** of the join.  Subtracting one from the right table bitmask gives a
104988   ** bitmask for all tables to the left of the join.  Knowing the bitmask
104989   ** for all tables to the left of a left join is important.  Ticket #3015.
104990   **
104991   ** Configure the WhereClause.vmask variable so that bits that correspond
104992   ** to virtual table cursors are set. This is used to selectively disable
104993   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
104994   ** with virtual tables.
104995   **
104996   ** Note that bitmasks are created for all pTabList->nSrc tables in
104997   ** pTabList, not just the first nTabList tables.  nTabList is normally
104998   ** equal to pTabList->nSrc but might be shortened to 1 if the
104999   ** WHERE_ONETABLE_ONLY flag is set.
105000   */
105001   assert( pWC->vmask==0 && pMaskSet->n==0 );
105002   for(i=0; i<pTabList->nSrc; i++){
105003     createMask(pMaskSet, pTabList->a[i].iCursor);
105004 #ifndef SQLITE_OMIT_VIRTUALTABLE
105005     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
105006       pWC->vmask |= ((Bitmask)1 << i);
105007     }
105008 #endif
105009   }
105010 #ifndef NDEBUG
105011   {
105012     Bitmask toTheLeft = 0;
105013     for(i=0; i<pTabList->nSrc; i++){
105014       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
105015       assert( (m-1)==toTheLeft );
105016       toTheLeft |= m;
105017     }
105018   }
105019 #endif
105020 
105021   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
105022   ** add new virtual terms onto the end of the WHERE clause.  We do not
105023   ** want to analyze these virtual terms, so start analyzing at the end
105024   ** and work forward so that the added virtual terms are never processed.
105025   */
105026   exprAnalyzeAll(pTabList, pWC);
105027   if( db->mallocFailed ){
105028     goto whereBeginError;
105029   }
105030 
105031   /* Check if the DISTINCT qualifier, if there is one, is redundant.
105032   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
105033   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
105034   */
105035   if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
105036     pDistinct = 0;
105037     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
105038   }
105039 
105040   /* Chose the best index to use for each table in the FROM clause.
105041   **
105042   ** This loop fills in the following fields:
105043   **
105044   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
105045   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
105046   **   pWInfo->a[].nEq       The number of == and IN constraints
105047   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
105048   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
105049   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
105050   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
105051   **
105052   ** This loop also figures out the nesting order of tables in the FROM
105053   ** clause.
105054   */
105055   notReady = ~(Bitmask)0;
105056   andFlags = ~0;
105057   WHERETRACE(("*** Optimizer Start ***\n"));
105058   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
105059     WhereCost bestPlan;         /* Most efficient plan seen so far */
105060     Index *pIdx;                /* Index for FROM table at pTabItem */
105061     int j;                      /* For looping over FROM tables */
105062     int bestJ = -1;             /* The value of j */
105063     Bitmask m;                  /* Bitmask value for j or bestJ */
105064     int isOptimal;              /* Iterator for optimal/non-optimal search */
105065     int nUnconstrained;         /* Number tables without INDEXED BY */
105066     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
105067 
105068     memset(&bestPlan, 0, sizeof(bestPlan));
105069     bestPlan.rCost = SQLITE_BIG_DBL;
105070     WHERETRACE(("*** Begin search for loop %d ***\n", i));
105071 
105072     /* Loop through the remaining entries in the FROM clause to find the
105073     ** next nested loop. The loop tests all FROM clause entries
105074     ** either once or twice.
105075     **
105076     ** The first test is always performed if there are two or more entries
105077     ** remaining and never performed if there is only one FROM clause entry
105078     ** to choose from.  The first test looks for an "optimal" scan.  In
105079     ** this context an optimal scan is one that uses the same strategy
105080     ** for the given FROM clause entry as would be selected if the entry
105081     ** were used as the innermost nested loop.  In other words, a table
105082     ** is chosen such that the cost of running that table cannot be reduced
105083     ** by waiting for other tables to run first.  This "optimal" test works
105084     ** by first assuming that the FROM clause is on the inner loop and finding
105085     ** its query plan, then checking to see if that query plan uses any
105086     ** other FROM clause terms that are notReady.  If no notReady terms are
105087     ** used then the "optimal" query plan works.
105088     **
105089     ** Note that the WhereCost.nRow parameter for an optimal scan might
105090     ** not be as small as it would be if the table really were the innermost
105091     ** join.  The nRow value can be reduced by WHERE clause constraints
105092     ** that do not use indices.  But this nRow reduction only happens if the
105093     ** table really is the innermost join.
105094     **
105095     ** The second loop iteration is only performed if no optimal scan
105096     ** strategies were found by the first iteration. This second iteration
105097     ** is used to search for the lowest cost scan overall.
105098     **
105099     ** Previous versions of SQLite performed only the second iteration -
105100     ** the next outermost loop was always that with the lowest overall
105101     ** cost. However, this meant that SQLite could select the wrong plan
105102     ** for scripts such as the following:
105103     **
105104     **   CREATE TABLE t1(a, b);
105105     **   CREATE TABLE t2(c, d);
105106     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
105107     **
105108     ** The best strategy is to iterate through table t1 first. However it
105109     ** is not possible to determine this with a simple greedy algorithm.
105110     ** Since the cost of a linear scan through table t2 is the same
105111     ** as the cost of a linear scan through table t1, a simple greedy
105112     ** algorithm may choose to use t2 for the outer loop, which is a much
105113     ** costlier approach.
105114     */
105115     nUnconstrained = 0;
105116     notIndexed = 0;
105117     for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
105118       Bitmask mask;             /* Mask of tables not yet ready */
105119       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
105120         int doNotReorder;    /* True if this table should not be reordered */
105121         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
105122         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
105123         ExprList *pDist;     /* DISTINCT clause for index to optimize */
105124 
105125         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
105126         if( j!=iFrom && doNotReorder ) break;
105127         m = getMask(pMaskSet, pTabItem->iCursor);
105128         if( (m & notReady)==0 ){
105129           if( j==iFrom ) iFrom++;
105130           continue;
105131         }
105132         mask = (isOptimal ? m : notReady);
105133         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
105134         pDist = (i==0 ? pDistinct : 0);
105135         if( pTabItem->pIndex==0 ) nUnconstrained++;
105136 
105137         WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
105138                     j, isOptimal));
105139         assert( pTabItem->pTab );
105140 #ifndef SQLITE_OMIT_VIRTUALTABLE
105141         if( IsVirtual(pTabItem->pTab) ){
105142           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
105143           bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
105144                            &sCost, pp);
105145         }else
105146 #endif
105147         {
105148           bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
105149               pDist, &sCost);
105150         }
105151         assert( isOptimal || (sCost.used&notReady)==0 );
105152 
105153         /* If an INDEXED BY clause is present, then the plan must use that
105154         ** index if it uses any index at all */
105155         assert( pTabItem->pIndex==0
105156                   || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
105157                   || sCost.plan.u.pIdx==pTabItem->pIndex );
105158 
105159         if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105160           notIndexed |= m;
105161         }
105162 
105163         /* Conditions under which this table becomes the best so far:
105164         **
105165         **   (1) The table must not depend on other tables that have not
105166         **       yet run.
105167         **
105168         **   (2) A full-table-scan plan cannot supercede indexed plan unless
105169         **       the full-table-scan is an "optimal" plan as defined above.
105170         **
105171         **   (3) All tables have an INDEXED BY clause or this table lacks an
105172         **       INDEXED BY clause or this table uses the specific
105173         **       index specified by its INDEXED BY clause.  This rule ensures
105174         **       that a best-so-far is always selected even if an impossible
105175         **       combination of INDEXED BY clauses are given.  The error
105176         **       will be detected and relayed back to the application later.
105177         **       The NEVER() comes about because rule (2) above prevents
105178         **       An indexable full-table-scan from reaching rule (3).
105179         **
105180         **   (4) The plan cost must be lower than prior plans or else the
105181         **       cost must be the same and the number of rows must be lower.
105182         */
105183         if( (sCost.used&notReady)==0                       /* (1) */
105184             && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
105185                 || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
105186                 || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
105187             && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
105188                 || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
105189             && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
105190                 || (sCost.rCost<=bestPlan.rCost
105191                  && sCost.plan.nRow<bestPlan.plan.nRow))
105192         ){
105193           WHERETRACE(("=== table %d is best so far"
105194                       " with cost=%g and nRow=%g\n",
105195                       j, sCost.rCost, sCost.plan.nRow));
105196           bestPlan = sCost;
105197           bestJ = j;
105198         }
105199         if( doNotReorder ) break;
105200       }
105201     }
105202     assert( bestJ>=0 );
105203     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
105204     WHERETRACE(("*** Optimizer selects table %d for loop %d"
105205                 " with cost=%g and nRow=%g\n",
105206                 bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
105207     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
105208       *ppOrderBy = 0;
105209     }
105210     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
105211       assert( pWInfo->eDistinct==0 );
105212       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
105213     }
105214     andFlags &= bestPlan.plan.wsFlags;
105215     pLevel->plan = bestPlan.plan;
105216     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
105217     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
105218     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
105219       pLevel->iIdxCur = pParse->nTab++;
105220     }else{
105221       pLevel->iIdxCur = -1;
105222     }
105223     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
105224     pLevel->iFrom = (u8)bestJ;
105225     if( bestPlan.plan.nRow>=(double)1 ){
105226       pParse->nQueryLoop *= bestPlan.plan.nRow;
105227     }
105228 
105229     /* Check that if the table scanned by this loop iteration had an
105230     ** INDEXED BY clause attached to it, that the named index is being
105231     ** used for the scan. If not, then query compilation has failed.
105232     ** Return an error.
105233     */
105234     pIdx = pTabList->a[bestJ].pIndex;
105235     if( pIdx ){
105236       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
105237         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
105238         goto whereBeginError;
105239       }else{
105240         /* If an INDEXED BY clause is used, the bestIndex() function is
105241         ** guaranteed to find the index specified in the INDEXED BY clause
105242         ** if it find an index at all. */
105243         assert( bestPlan.plan.u.pIdx==pIdx );
105244       }
105245     }
105246   }
105247   WHERETRACE(("*** Optimizer Finished ***\n"));
105248   if( pParse->nErr || db->mallocFailed ){
105249     goto whereBeginError;
105250   }
105251 
105252   /* If the total query only selects a single row, then the ORDER BY
105253   ** clause is irrelevant.
105254   */
105255   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
105256     *ppOrderBy = 0;
105257   }
105258 
105259   /* If the caller is an UPDATE or DELETE statement that is requesting
105260   ** to use a one-pass algorithm, determine if this is appropriate.
105261   ** The one-pass algorithm only works if the WHERE clause constraints
105262   ** the statement to update a single row.
105263   */
105264   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
105265   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
105266     pWInfo->okOnePass = 1;
105267     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
105268   }
105269 
105270   /* Open all tables in the pTabList and any indices selected for
105271   ** searching those tables.
105272   */
105273   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
105274   notReady = ~(Bitmask)0;
105275   pWInfo->nRowOut = (double)1;
105276   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
105277     Table *pTab;     /* Table to open */
105278     int iDb;         /* Index of database containing table/index */
105279 
105280     pTabItem = &pTabList->a[pLevel->iFrom];
105281     pTab = pTabItem->pTab;
105282     pLevel->iTabCur = pTabItem->iCursor;
105283     pWInfo->nRowOut *= pLevel->plan.nRow;
105284     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105285     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
105286       /* Do nothing */
105287     }else
105288 #ifndef SQLITE_OMIT_VIRTUALTABLE
105289     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
105290       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
105291       int iCur = pTabItem->iCursor;
105292       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
105293     }else
105294 #endif
105295     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105296          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
105297       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
105298       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
105299       testcase( pTab->nCol==BMS-1 );
105300       testcase( pTab->nCol==BMS );
105301       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
105302         Bitmask b = pTabItem->colUsed;
105303         int n = 0;
105304         for(; b; b=b>>1, n++){}
105305         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
105306                             SQLITE_INT_TO_PTR(n), P4_INT32);
105307         assert( n<=pTab->nCol );
105308       }
105309     }else{
105310       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
105311     }
105312 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
105313     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
105314       constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
105315     }else
105316 #endif
105317     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
105318       Index *pIx = pLevel->plan.u.pIdx;
105319       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
105320       int iIdxCur = pLevel->iIdxCur;
105321       assert( pIx->pSchema==pTab->pSchema );
105322       assert( iIdxCur>=0 );
105323       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
105324                         (char*)pKey, P4_KEYINFO_HANDOFF);
105325       VdbeComment((v, "%s", pIx->zName));
105326     }
105327     sqlite3CodeVerifySchema(pParse, iDb);
105328     notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
105329   }
105330   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
105331   if( db->mallocFailed ) goto whereBeginError;
105332 
105333   /* Generate the code to do the search.  Each iteration of the for
105334   ** loop below generates code for a single nested loop of the VM
105335   ** program.
105336   */
105337   notReady = ~(Bitmask)0;
105338   for(i=0; i<nTabList; i++){
105339     pLevel = &pWInfo->a[i];
105340     explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
105341     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
105342     pWInfo->iContinue = pLevel->addrCont;
105343   }
105344 
105345 #ifdef SQLITE_TEST  /* For testing and debugging use only */
105346   /* Record in the query plan information about the current table
105347   ** and the index used to access it (if any).  If the table itself
105348   ** is not used, its name is just '{}'.  If no index is used
105349   ** the index is listed as "{}".  If the primary key is used the
105350   ** index name is '*'.
105351   */
105352   for(i=0; i<nTabList; i++){
105353     char *z;
105354     int n;
105355     pLevel = &pWInfo->a[i];
105356     pTabItem = &pTabList->a[pLevel->iFrom];
105357     z = pTabItem->zAlias;
105358     if( z==0 ) z = pTabItem->pTab->zName;
105359     n = sqlite3Strlen30(z);
105360     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
105361       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
105362         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
105363         nQPlan += 2;
105364       }else{
105365         memcpy(&sqlite3_query_plan[nQPlan], z, n);
105366         nQPlan += n;
105367       }
105368       sqlite3_query_plan[nQPlan++] = ' ';
105369     }
105370     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
105371     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
105372     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
105373       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
105374       nQPlan += 2;
105375     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
105376       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
105377       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
105378         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
105379         nQPlan += n;
105380         sqlite3_query_plan[nQPlan++] = ' ';
105381       }
105382     }else{
105383       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
105384       nQPlan += 3;
105385     }
105386   }
105387   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
105388     sqlite3_query_plan[--nQPlan] = 0;
105389   }
105390   sqlite3_query_plan[nQPlan] = 0;
105391   nQPlan = 0;
105392 #endif /* SQLITE_TEST // Testing and debugging use only */
105393 
105394   /* Record the continuation address in the WhereInfo structure.  Then
105395   ** clean up and return.
105396   */
105397   return pWInfo;
105398 
105399   /* Jump here if malloc fails */
105400 whereBeginError:
105401   if( pWInfo ){
105402     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
105403     whereInfoFree(db, pWInfo);
105404   }
105405   return 0;
105406 }
105407 
105408 /*
105409 ** Generate the end of the WHERE loop.  See comments on
105410 ** sqlite3WhereBegin() for additional information.
105411 */
105412 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
105413   Parse *pParse = pWInfo->pParse;
105414   Vdbe *v = pParse->pVdbe;
105415   int i;
105416   WhereLevel *pLevel;
105417   SrcList *pTabList = pWInfo->pTabList;
105418   sqlite3 *db = pParse->db;
105419 
105420   /* Generate loop termination code.
105421   */
105422   sqlite3ExprCacheClear(pParse);
105423   for(i=pWInfo->nLevel-1; i>=0; i--){
105424     pLevel = &pWInfo->a[i];
105425     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
105426     if( pLevel->op!=OP_Noop ){
105427       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
105428       sqlite3VdbeChangeP5(v, pLevel->p5);
105429     }
105430     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
105431       struct InLoop *pIn;
105432       int j;
105433       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
105434       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
105435         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
105436         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
105437         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
105438       }
105439       sqlite3DbFree(db, pLevel->u.in.aInLoop);
105440     }
105441     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
105442     if( pLevel->iLeftJoin ){
105443       int addr;
105444       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
105445       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105446            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
105447       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
105448         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
105449       }
105450       if( pLevel->iIdxCur>=0 ){
105451         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
105452       }
105453       if( pLevel->op==OP_Return ){
105454         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
105455       }else{
105456         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
105457       }
105458       sqlite3VdbeJumpHere(v, addr);
105459     }
105460   }
105461 
105462   /* The "break" point is here, just past the end of the outer loop.
105463   ** Set it.
105464   */
105465   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
105466 
105467   /* Close all of the cursors that were opened by sqlite3WhereBegin.
105468   */
105469   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
105470   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
105471     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
105472     Table *pTab = pTabItem->pTab;
105473     assert( pTab!=0 );
105474     if( (pTab->tabFlags & TF_Ephemeral)==0
105475      && pTab->pSelect==0
105476      && (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0
105477     ){
105478       int ws = pLevel->plan.wsFlags;
105479       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
105480         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
105481       }
105482       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
105483         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
105484       }
105485     }
105486 
105487     /* If this scan uses an index, make code substitutions to read data
105488     ** from the index in preference to the table. Sometimes, this means
105489     ** the table need never be read from. This is a performance boost,
105490     ** as the vdbe level waits until the table is read before actually
105491     ** seeking the table cursor to the record corresponding to the current
105492     ** position in the index.
105493     **
105494     ** Calls to the code generator in between sqlite3WhereBegin and
105495     ** sqlite3WhereEnd will have created code that references the table
105496     ** directly.  This loop scans all that code looking for opcodes
105497     ** that reference the table and converts them into opcodes that
105498     ** reference the index.
105499     */
105500     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
105501       int k, j, last;
105502       VdbeOp *pOp;
105503       Index *pIdx = pLevel->plan.u.pIdx;
105504 
105505       assert( pIdx!=0 );
105506       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
105507       last = sqlite3VdbeCurrentAddr(v);
105508       for(k=pWInfo->iTop; k<last; k++, pOp++){
105509         if( pOp->p1!=pLevel->iTabCur ) continue;
105510         if( pOp->opcode==OP_Column ){
105511           for(j=0; j<pIdx->nColumn; j++){
105512             if( pOp->p2==pIdx->aiColumn[j] ){
105513               pOp->p2 = j;
105514               pOp->p1 = pLevel->iIdxCur;
105515               break;
105516             }
105517           }
105518           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
105519                || j<pIdx->nColumn );
105520         }else if( pOp->opcode==OP_Rowid ){
105521           pOp->p1 = pLevel->iIdxCur;
105522           pOp->opcode = OP_IdxRowid;
105523         }
105524       }
105525     }
105526   }
105527 
105528   /* Final cleanup
105529   */
105530   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
105531   whereInfoFree(db, pWInfo);
105532   return;
105533 }
105534 
105535 /************** End of where.c ***********************************************/
105536 /************** Begin file parse.c *******************************************/
105537 /* Driver template for the LEMON parser generator.
105538 ** The author disclaims copyright to this source code.
105539 **
105540 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
105541 ** The only modifications are the addition of a couple of NEVER()
105542 ** macros to disable tests that are needed in the case of a general
105543 ** LALR(1) grammar but which are always false in the
105544 ** specific grammar used by SQLite.
105545 */
105546 /* First off, code is included that follows the "include" declaration
105547 ** in the input grammar file. */
105548 /* #include <stdio.h> */
105549 
105550 
105551 /*
105552 ** Disable all error recovery processing in the parser push-down
105553 ** automaton.
105554 */
105555 #define YYNOERRORRECOVERY 1
105556 
105557 /*
105558 ** Make yytestcase() the same as testcase()
105559 */
105560 #define yytestcase(X) testcase(X)
105561 
105562 /*
105563 ** An instance of this structure holds information about the
105564 ** LIMIT clause of a SELECT statement.
105565 */
105566 struct LimitVal {
105567   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
105568   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
105569 };
105570 
105571 /*
105572 ** An instance of this structure is used to store the LIKE,
105573 ** GLOB, NOT LIKE, and NOT GLOB operators.
105574 */
105575 struct LikeOp {
105576   Token eOperator;  /* "like" or "glob" or "regexp" */
105577   int not;         /* True if the NOT keyword is present */
105578 };
105579 
105580 /*
105581 ** An instance of the following structure describes the event of a
105582 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
105583 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
105584 **
105585 **      UPDATE ON (a,b,c)
105586 **
105587 ** Then the "b" IdList records the list "a,b,c".
105588 */
105589 struct TrigEvent { int a; IdList * b; };
105590 
105591 /*
105592 ** An instance of this structure holds the ATTACH key and the key type.
105593 */
105594 struct AttachKey { int type;  Token key; };
105595 
105596 
105597   /* This is a utility routine used to set the ExprSpan.zStart and
105598   ** ExprSpan.zEnd values of pOut so that the span covers the complete
105599   ** range of text beginning with pStart and going to the end of pEnd.
105600   */
105601   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
105602     pOut->zStart = pStart->z;
105603     pOut->zEnd = &pEnd->z[pEnd->n];
105604   }
105605 
105606   /* Construct a new Expr object from a single identifier.  Use the
105607   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
105608   ** that created the expression.
105609   */
105610   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
105611     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
105612     pOut->zStart = pValue->z;
105613     pOut->zEnd = &pValue->z[pValue->n];
105614   }
105615 
105616   /* This routine constructs a binary expression node out of two ExprSpan
105617   ** objects and uses the result to populate a new ExprSpan object.
105618   */
105619   static void spanBinaryExpr(
105620     ExprSpan *pOut,     /* Write the result here */
105621     Parse *pParse,      /* The parsing context.  Errors accumulate here */
105622     int op,             /* The binary operation */
105623     ExprSpan *pLeft,    /* The left operand */
105624     ExprSpan *pRight    /* The right operand */
105625   ){
105626     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
105627     pOut->zStart = pLeft->zStart;
105628     pOut->zEnd = pRight->zEnd;
105629   }
105630 
105631   /* Construct an expression node for a unary postfix operator
105632   */
105633   static void spanUnaryPostfix(
105634     ExprSpan *pOut,        /* Write the new expression node here */
105635     Parse *pParse,         /* Parsing context to record errors */
105636     int op,                /* The operator */
105637     ExprSpan *pOperand,    /* The operand */
105638     Token *pPostOp         /* The operand token for setting the span */
105639   ){
105640     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
105641     pOut->zStart = pOperand->zStart;
105642     pOut->zEnd = &pPostOp->z[pPostOp->n];
105643   }
105644 
105645   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
105646   ** unary TK_ISNULL or TK_NOTNULL expression. */
105647   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
105648     sqlite3 *db = pParse->db;
105649     if( db->mallocFailed==0 && pY->op==TK_NULL ){
105650       pA->op = (u8)op;
105651       sqlite3ExprDelete(db, pA->pRight);
105652       pA->pRight = 0;
105653     }
105654   }
105655 
105656   /* Construct an expression node for a unary prefix operator
105657   */
105658   static void spanUnaryPrefix(
105659     ExprSpan *pOut,        /* Write the new expression node here */
105660     Parse *pParse,         /* Parsing context to record errors */
105661     int op,                /* The operator */
105662     ExprSpan *pOperand,    /* The operand */
105663     Token *pPreOp         /* The operand token for setting the span */
105664   ){
105665     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
105666     pOut->zStart = pPreOp->z;
105667     pOut->zEnd = pOperand->zEnd;
105668   }
105669 /* Next is all token values, in a form suitable for use by makeheaders.
105670 ** This section will be null unless lemon is run with the -m switch.
105671 */
105672 /*
105673 ** These constants (all generated automatically by the parser generator)
105674 ** specify the various kinds of tokens (terminals) that the parser
105675 ** understands.
105676 **
105677 ** Each symbol here is a terminal symbol in the grammar.
105678 */
105679 /* Make sure the INTERFACE macro is defined.
105680 */
105681 #ifndef INTERFACE
105682 # define INTERFACE 1
105683 #endif
105684 /* The next thing included is series of defines which control
105685 ** various aspects of the generated parser.
105686 **    YYCODETYPE         is the data type used for storing terminal
105687 **                       and nonterminal numbers.  "unsigned char" is
105688 **                       used if there are fewer than 250 terminals
105689 **                       and nonterminals.  "int" is used otherwise.
105690 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
105691 **                       to no legal terminal or nonterminal number.  This
105692 **                       number is used to fill in empty slots of the hash
105693 **                       table.
105694 **    YYFALLBACK         If defined, this indicates that one or more tokens
105695 **                       have fall-back values which should be used if the
105696 **                       original value of the token will not parse.
105697 **    YYACTIONTYPE       is the data type used for storing terminal
105698 **                       and nonterminal numbers.  "unsigned char" is
105699 **                       used if there are fewer than 250 rules and
105700 **                       states combined.  "int" is used otherwise.
105701 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
105702 **                       directly to the parser from the tokenizer.
105703 **    YYMINORTYPE        is the data type used for all minor tokens.
105704 **                       This is typically a union of many types, one of
105705 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
105706 **                       for base tokens is called "yy0".
105707 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
105708 **                       zero the stack is dynamically sized using realloc()
105709 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
105710 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
105711 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
105712 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
105713 **    YYNSTATE           the combined number of states.
105714 **    YYNRULE            the number of rules in the grammar
105715 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
105716 **                       defined, then do no error processing.
105717 */
105718 #define YYCODETYPE unsigned char
105719 #define YYNOCODE 253
105720 #define YYACTIONTYPE unsigned short int
105721 #define YYWILDCARD 67
105722 #define sqlite3ParserTOKENTYPE Token
105723 typedef union {
105724   int yyinit;
105725   sqlite3ParserTOKENTYPE yy0;
105726   int yy4;
105727   struct TrigEvent yy90;
105728   ExprSpan yy118;
105729   TriggerStep* yy203;
105730   u8 yy210;
105731   struct {int value; int mask;} yy215;
105732   SrcList* yy259;
105733   struct LimitVal yy292;
105734   Expr* yy314;
105735   ExprList* yy322;
105736   struct LikeOp yy342;
105737   IdList* yy384;
105738   Select* yy387;
105739 } YYMINORTYPE;
105740 #ifndef YYSTACKDEPTH
105741 #define YYSTACKDEPTH 100
105742 #endif
105743 #define sqlite3ParserARG_SDECL Parse *pParse;
105744 #define sqlite3ParserARG_PDECL ,Parse *pParse
105745 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
105746 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
105747 #define YYNSTATE 630
105748 #define YYNRULE 329
105749 #define YYFALLBACK 1
105750 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
105751 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
105752 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
105753 
105754 /* The yyzerominor constant is used to initialize instances of
105755 ** YYMINORTYPE objects to zero. */
105756 static const YYMINORTYPE yyzerominor = { 0 };
105757 
105758 /* Define the yytestcase() macro to be a no-op if is not already defined
105759 ** otherwise.
105760 **
105761 ** Applications can choose to define yytestcase() in the %include section
105762 ** to a macro that can assist in verifying code coverage.  For production
105763 ** code the yytestcase() macro should be turned off.  But it is useful
105764 ** for testing.
105765 */
105766 #ifndef yytestcase
105767 # define yytestcase(X)
105768 #endif
105769 
105770 
105771 /* Next are the tables used to determine what action to take based on the
105772 ** current state and lookahead token.  These tables are used to implement
105773 ** functions that take a state number and lookahead value and return an
105774 ** action integer.
105775 **
105776 ** Suppose the action integer is N.  Then the action is determined as
105777 ** follows
105778 **
105779 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
105780 **                                      token onto the stack and goto state N.
105781 **
105782 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
105783 **
105784 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
105785 **
105786 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
105787 **
105788 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
105789 **                                      slots in the yy_action[] table.
105790 **
105791 ** The action table is constructed as a single large table named yy_action[].
105792 ** Given state S and lookahead X, the action is computed as
105793 **
105794 **      yy_action[ yy_shift_ofst[S] + X ]
105795 **
105796 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
105797 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
105798 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
105799 ** and that yy_default[S] should be used instead.
105800 **
105801 ** The formula above is for computing the action when the lookahead is
105802 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
105803 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
105804 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
105805 ** YY_SHIFT_USE_DFLT.
105806 **
105807 ** The following are the tables generated in this section:
105808 **
105809 **  yy_action[]        A single table containing all actions.
105810 **  yy_lookahead[]     A table containing the lookahead for each entry in
105811 **                     yy_action.  Used to detect hash collisions.
105812 **  yy_shift_ofst[]    For each state, the offset into yy_action for
105813 **                     shifting terminals.
105814 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
105815 **                     shifting non-terminals after a reduce.
105816 **  yy_default[]       Default action for each state.
105817 */
105818 #define YY_ACTTAB_COUNT (1557)
105819 static const YYACTIONTYPE yy_action[] = {
105820  /*     0 */   313,  960,  186,  419,    2,  172,  627,  597,   55,   55,
105821  /*    10 */    55,   55,   48,   53,   53,   53,   53,   52,   52,   51,
105822  /*    20 */    51,   51,   50,  238,  302,  283,  623,  622,  516,  515,
105823  /*    30 */   590,  584,   55,   55,   55,   55,  282,   53,   53,   53,
105824  /*    40 */    53,   52,   52,   51,   51,   51,   50,  238,    6,   56,
105825  /*    50 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
105826  /*    60 */    55,   55,  608,   53,   53,   53,   53,   52,   52,   51,
105827  /*    70 */    51,   51,   50,  238,  313,  597,  409,  330,  579,  579,
105828  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
105829  /*    90 */    50,  238,  330,  217,  620,  619,  166,  411,  624,  382,
105830  /*   100 */   379,  378,    7,  491,  590,  584,  200,  199,  198,   58,
105831  /*   110 */   377,  300,  414,  621,  481,   66,  623,  622,  621,  580,
105832  /*   120 */   254,  601,   94,   56,   57,   47,  582,  581,  583,  583,
105833  /*   130 */    54,   54,   55,   55,   55,   55,  671,   53,   53,   53,
105834  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  532,
105835  /*   150 */   226,  506,  507,  133,  177,  139,  284,  385,  279,  384,
105836  /*   160 */   169,  197,  342,  398,  251,  226,  253,  275,  388,  167,
105837  /*   170 */   139,  284,  385,  279,  384,  169,  570,  236,  590,  584,
105838  /*   180 */   672,  240,  275,  157,  620,  619,  554,  437,   51,   51,
105839  /*   190 */    51,   50,  238,  343,  439,  553,  438,   56,   57,   47,
105840  /*   200 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
105841  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
105842  /*   220 */    50,  238,  313,  390,   52,   52,   51,   51,   51,   50,
105843  /*   230 */   238,  391,  166,  491,  566,  382,  379,  378,  409,  440,
105844  /*   240 */   579,  579,  252,  440,  607,   66,  377,  513,  621,   49,
105845  /*   250 */    46,  147,  590,  584,  621,   16,  466,  189,  621,  441,
105846  /*   260 */   442,  673,  526,  441,  340,  577,  595,   64,  194,  482,
105847  /*   270 */   434,   56,   57,   47,  582,  581,  583,  583,   54,   54,
105848  /*   280 */    55,   55,   55,   55,   30,   53,   53,   53,   53,   52,
105849  /*   290 */    52,   51,   51,   51,   50,  238,  313,  593,  593,  593,
105850  /*   300 */   387,  578,  606,  493,  259,  351,  258,  411,    1,  623,
105851  /*   310 */   622,  496,  623,  622,   65,  240,  623,  622,  597,  443,
105852  /*   320 */   237,  239,  414,  341,  237,  602,  590,  584,   18,  603,
105853  /*   330 */   166,  601,   87,  382,  379,  378,   67,  623,  622,   38,
105854  /*   340 */   623,  622,  176,  270,  377,   56,   57,   47,  582,  581,
105855  /*   350 */   583,  583,   54,   54,   55,   55,   55,   55,  175,   53,
105856  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
105857  /*   370 */   313,  396,  233,  411,  531,  565,  317,  620,  619,   44,
105858  /*   380 */   620,  619,  240,  206,  620,  619,  597,  266,  414,  268,
105859  /*   390 */   409,  597,  579,  579,  352,  184,  505,  601,   73,  533,
105860  /*   400 */   590,  584,  466,  548,  190,  620,  619,  576,  620,  619,
105861  /*   410 */   547,  383,  551,   35,  332,  575,  574,  600,  504,   56,
105862  /*   420 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
105863  /*   430 */    55,   55,  567,   53,   53,   53,   53,   52,   52,   51,
105864  /*   440 */    51,   51,   50,  238,  313,  411,  561,  561,  528,  364,
105865  /*   450 */   259,  351,  258,  183,  361,  549,  524,  374,  411,  597,
105866  /*   460 */   414,  240,  560,  560,  409,  604,  579,  579,  328,  601,
105867  /*   470 */    93,  623,  622,  414,  590,  584,  237,  564,  559,  559,
105868  /*   480 */   520,  402,  601,   87,  409,  210,  579,  579,  168,  421,
105869  /*   490 */   950,  519,  950,   56,   57,   47,  582,  581,  583,  583,
105870  /*   500 */    54,   54,   55,   55,   55,   55,  192,   53,   53,   53,
105871  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  600,
105872  /*   520 */   293,  563,  511,  234,  357,  146,  475,  475,  367,  411,
105873  /*   530 */   562,  411,  358,  542,  425,  171,  411,  215,  144,  620,
105874  /*   540 */   619,  544,  318,  353,  414,  203,  414,  275,  590,  584,
105875  /*   550 */   549,  414,  174,  601,   94,  601,   79,  558,  471,   61,
105876  /*   560 */   601,   79,  421,  949,  350,  949,   34,   56,   57,   47,
105877  /*   570 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
105878  /*   580 */   535,   53,   53,   53,   53,   52,   52,   51,   51,   51,
105879  /*   590 */    50,  238,  313,  307,  424,  394,  272,   49,   46,  147,
105880  /*   600 */   349,  322,    4,  411,  491,  312,  321,  425,  568,  492,
105881  /*   610 */   216,  264,  407,  575,  574,  429,   66,  549,  414,  621,
105882  /*   620 */   540,  602,  590,  584,   13,  603,  621,  601,   72,   12,
105883  /*   630 */   618,  617,  616,  202,  210,  621,  546,  469,  422,  319,
105884  /*   640 */   148,   56,   57,   47,  582,  581,  583,  583,   54,   54,
105885  /*   650 */    55,   55,   55,   55,  338,   53,   53,   53,   53,   52,
105886  /*   660 */    52,   51,   51,   51,   50,  238,  313,  600,  600,  411,
105887  /*   670 */    39,   21,   37,  170,  237,  875,  411,  572,  572,  201,
105888  /*   680 */   144,  473,  538,  331,  414,  474,  143,  146,  630,  628,
105889  /*   690 */   334,  414,  353,  601,   68,  168,  590,  584,  132,  365,
105890  /*   700 */   601,   96,  307,  423,  530,  336,   49,   46,  147,  568,
105891  /*   710 */   406,  216,  549,  360,  529,   56,   57,   47,  582,  581,
105892  /*   720 */   583,  583,   54,   54,   55,   55,   55,   55,  411,   53,
105893  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
105894  /*   740 */   313,  411,  605,  414,  484,  510,  172,  422,  597,  318,
105895  /*   750 */   496,  485,  601,   99,  411,  142,  414,  411,  231,  411,
105896  /*   760 */   540,  411,  359,  629,    2,  601,   97,  426,  308,  414,
105897  /*   770 */   590,  584,  414,   20,  414,  621,  414,  621,  601,  106,
105898  /*   780 */   503,  601,  105,  601,  108,  601,  109,  204,   28,   56,
105899  /*   790 */    57,   47,  582,  581,  583,  583,   54,   54,   55,   55,
105900  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
105901  /*   810 */    51,   51,   50,  238,  313,  411,  597,  414,  411,  276,
105902  /*   820 */   214,  600,  411,  366,  213,  381,  601,  134,  274,  500,
105903  /*   830 */   414,  167,  130,  414,  621,  411,  354,  414,  376,  601,
105904  /*   840 */   135,  129,  601,  100,  590,  584,  601,  104,  522,  521,
105905  /*   850 */   414,  621,  224,  273,  600,  167,  327,  282,  600,  601,
105906  /*   860 */   103,  468,  521,   56,   57,   47,  582,  581,  583,  583,
105907  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
105908  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
105909  /*   890 */    27,  414,  411,  375,  276,  167,  359,  544,   50,  238,
105910  /*   900 */   601,   95,  128,  223,  414,  411,  165,  414,  411,  621,
105911  /*   910 */   411,  621,  612,  601,  102,  372,  601,   76,  590,  584,
105912  /*   920 */   414,  570,  236,  414,  470,  414,  167,  621,  188,  601,
105913  /*   930 */    98,  225,  601,  138,  601,  137,  232,   56,   45,   47,
105914  /*   940 */   582,  581,  583,  583,   54,   54,   55,   55,   55,   55,
105915  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
105916  /*   960 */    50,  238,  313,  276,  276,  414,  411,  276,  544,  459,
105917  /*   970 */   359,  171,  209,  479,  601,  136,  628,  334,  621,  621,
105918  /*   980 */   125,  414,  621,  368,  411,  621,  257,  540,  589,  588,
105919  /*   990 */   601,   75,  590,  584,  458,  446,   23,   23,  124,  414,
105920  /*  1000 */   326,  325,  621,  427,  324,  309,  600,  288,  601,   92,
105921  /*  1010 */   586,  585,   57,   47,  582,  581,  583,  583,   54,   54,
105922  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
105923  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  587,  411,  414,
105924  /*  1040 */   411,  207,  611,  476,  171,  472,  160,  123,  601,   91,
105925  /*  1050 */   323,  261,   15,  414,  464,  414,  411,  621,  411,  354,
105926  /*  1060 */   222,  411,  601,   74,  601,   90,  590,  584,  159,  264,
105927  /*  1070 */   158,  414,  461,  414,  621,  600,  414,  121,  120,   25,
105928  /*  1080 */   601,   89,  601,  101,  621,  601,   88,   47,  582,  581,
105929  /*  1090 */   583,  583,   54,   54,   55,   55,   55,   55,  544,   53,
105930  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
105931  /*  1110 */    43,  405,  263,    3,  610,  264,  140,  415,  622,   24,
105932  /*  1120 */   410,   11,  456,  594,  118,  155,  219,  452,  408,  621,
105933  /*  1130 */   621,  621,  156,   43,  405,  621,    3,  286,  621,  113,
105934  /*  1140 */   415,  622,  111,  445,  411,  400,  557,  403,  545,   10,
105935  /*  1150 */   411,  408,  264,  110,  205,  436,  541,  566,  453,  414,
105936  /*  1160 */   621,  621,   63,  621,  435,  414,  411,  621,  601,   94,
105937  /*  1170 */   403,  621,  411,  337,  601,   86,  150,   40,   41,  534,
105938  /*  1180 */   566,  414,  242,  264,   42,  413,  412,  414,  600,  595,
105939  /*  1190 */   601,   85,  191,  333,  107,  451,  601,   84,  621,  539,
105940  /*  1200 */    40,   41,  420,  230,  411,  149,  316,   42,  413,  412,
105941  /*  1210 */   398,  127,  595,  315,  621,  399,  278,  625,  181,  414,
105942  /*  1220 */   593,  593,  593,  592,  591,   14,  450,  411,  601,   71,
105943  /*  1230 */   240,  621,   43,  405,  264,    3,  615,  180,  264,  415,
105944  /*  1240 */   622,  614,  414,  593,  593,  593,  592,  591,   14,  621,
105945  /*  1250 */   408,  601,   70,  621,  417,   33,  405,  613,    3,  411,
105946  /*  1260 */   264,  411,  415,  622,  418,  626,  178,  509,    8,  403,
105947  /*  1270 */   241,  416,  126,  408,  414,  621,  414,  449,  208,  566,
105948  /*  1280 */   240,  221,  621,  601,   83,  601,   82,  599,  297,  277,
105949  /*  1290 */   296,   30,  403,   31,  395,  264,  295,  397,  489,   40,
105950  /*  1300 */    41,  411,  566,  220,  621,  294,   42,  413,  412,  271,
105951  /*  1310 */   621,  595,  600,  621,   59,   60,  414,  269,  267,  623,
105952  /*  1320 */   622,   36,   40,   41,  621,  601,   81,  598,  235,   42,
105953  /*  1330 */   413,  412,  621,  621,  595,  265,  344,  411,  248,  556,
105954  /*  1340 */   173,  185,  593,  593,  593,  592,  591,   14,  218,   29,
105955  /*  1350 */   621,  543,  414,  305,  304,  303,  179,  301,  411,  566,
105956  /*  1360 */   454,  601,   80,  289,  335,  593,  593,  593,  592,  591,
105957  /*  1370 */    14,  411,  287,  414,  151,  392,  246,  260,  411,  196,
105958  /*  1380 */   195,  523,  601,   69,  411,  245,  414,  526,  537,  285,
105959  /*  1390 */   389,  595,  621,  414,  536,  601,   17,  362,  153,  414,
105960  /*  1400 */   466,  463,  601,   78,  154,  414,  462,  152,  601,   77,
105961  /*  1410 */   355,  255,  621,  455,  601,    9,  621,  386,  444,  517,
105962  /*  1420 */   247,  621,  593,  593,  593,  621,  621,  244,  621,  243,
105963  /*  1430 */   430,  518,  292,  621,  329,  621,  145,  393,  280,  513,
105964  /*  1440 */   291,  131,  621,  514,  621,  621,  311,  621,  259,  346,
105965  /*  1450 */   249,  621,  621,  229,  314,  621,  228,  512,  227,  240,
105966  /*  1460 */   494,  488,  310,  164,  487,  486,  373,  480,  163,  262,
105967  /*  1470 */   369,  371,  162,   26,  212,  478,  477,  161,  141,  363,
105968  /*  1480 */   467,  122,  339,  187,  119,  348,  347,  117,  116,  115,
105969  /*  1490 */   114,  112,  182,  457,  320,   22,  433,  432,  448,   19,
105970  /*  1500 */   609,  431,  428,   62,  193,  596,  573,  298,  555,  552,
105971  /*  1510 */   571,  404,  290,  380,  498,  510,  495,  306,  281,  499,
105972  /*  1520 */   250,    5,  497,  460,  345,  447,  569,  550,  238,  299,
105973  /*  1530 */   527,  525,  508,  961,  502,  501,  961,  401,  961,  211,
105974  /*  1540 */   490,  356,  256,  961,  483,  961,  961,  961,  961,  961,
105975  /*  1550 */   961,  961,  961,  961,  961,  961,  370,
105976 };
105977 static const YYCODETYPE yy_lookahead[] = {
105978  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
105979  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
105980  /*    20 */    89,   90,   91,   92,   15,   98,   26,   27,    7,    8,
105981  /*    30 */    49,   50,   77,   78,   79,   80,  109,   82,   83,   84,
105982  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   22,   68,
105983  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
105984  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
105985  /*    70 */    89,   90,   91,   92,   19,   94,  112,   19,  114,  115,
105986  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
105987  /*    90 */    91,   92,   19,   22,   94,   95,   96,  150,  150,   99,
105988  /*   100 */   100,  101,   76,  150,   49,   50,  105,  106,  107,   54,
105989  /*   110 */   110,  158,  165,  165,  161,  162,   26,   27,  165,  113,
105990  /*   120 */    16,  174,  175,   68,   69,   70,   71,   72,   73,   74,
105991  /*   130 */    75,   76,   77,   78,   79,   80,  118,   82,   83,   84,
105992  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   23,
105993  /*   150 */    92,   97,   98,   24,   96,   97,   98,   99,  100,  101,
105994  /*   160 */   102,   25,   97,  216,   60,   92,   62,  109,  221,   25,
105995  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
105996  /*   180 */   118,  116,  109,   25,   94,   95,   32,   97,   88,   89,
105997  /*   190 */    90,   91,   92,  128,  104,   41,  106,   68,   69,   70,
105998  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
105999  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
106000  /*   220 */    91,   92,   19,   19,   86,   87,   88,   89,   90,   91,
106001  /*   230 */    92,   27,   96,  150,   66,   99,  100,  101,  112,  150,
106002  /*   240 */   114,  115,  138,  150,  161,  162,  110,  103,  165,  222,
106003  /*   250 */   223,  224,   49,   50,  165,   22,   57,   24,  165,  170,
106004  /*   260 */   171,  118,   94,  170,  171,   23,   98,   25,  185,  186,
106005  /*   270 */   243,   68,   69,   70,   71,   72,   73,   74,   75,   76,
106006  /*   280 */    77,   78,   79,   80,  126,   82,   83,   84,   85,   86,
106007  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
106008  /*   300 */    88,   23,  172,  173,  105,  106,  107,  150,   22,   26,
106009  /*   310 */    27,  181,   26,   27,   22,  116,   26,   27,   26,  230,
106010  /*   320 */   231,  197,  165,  230,  231,  113,   49,   50,  204,  117,
106011  /*   330 */    96,  174,  175,   99,  100,  101,   22,   26,   27,  136,
106012  /*   340 */    26,   27,  118,   16,  110,   68,   69,   70,   71,   72,
106013  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,  118,   82,
106014  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
106015  /*   370 */    19,  214,  215,  150,   23,   23,  155,   94,   95,   22,
106016  /*   380 */    94,   95,  116,  160,   94,   95,   94,   60,  165,   62,
106017  /*   390 */   112,   26,  114,  115,  128,   23,   36,  174,  175,   88,
106018  /*   400 */    49,   50,   57,  120,   22,   94,   95,   23,   94,   95,
106019  /*   410 */   120,   51,   25,  136,  169,  170,  171,  194,   58,   68,
106020  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
106021  /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
106022  /*   440 */    89,   90,   91,   92,   19,  150,   12,   12,   23,  228,
106023  /*   450 */   105,  106,  107,   23,  233,   25,  165,   19,  150,   94,
106024  /*   460 */   165,  116,   28,   28,  112,  174,  114,  115,  108,  174,
106025  /*   470 */   175,   26,   27,  165,   49,   50,  231,   11,   44,   44,
106026  /*   480 */    46,   46,  174,  175,  112,  160,  114,  115,   50,   22,
106027  /*   490 */    23,   57,   25,   68,   69,   70,   71,   72,   73,   74,
106028  /*   500 */    75,   76,   77,   78,   79,   80,  119,   82,   83,   84,
106029  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
106030  /*   520 */   225,   23,   23,  215,   19,   95,  105,  106,  107,  150,
106031  /*   530 */    23,  150,   27,   23,   67,   25,  150,  206,  207,   94,
106032  /*   540 */    95,  166,  104,  218,  165,   22,  165,  109,   49,   50,
106033  /*   550 */   120,  165,   25,  174,  175,  174,  175,   23,   21,  234,
106034  /*   560 */   174,  175,   22,   23,  239,   25,   25,   68,   69,   70,
106035  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
106036  /*   580 */   205,   82,   83,   84,   85,   86,   87,   88,   89,   90,
106037  /*   590 */    91,   92,   19,   22,   23,  216,   23,  222,  223,  224,
106038  /*   600 */    63,  220,   35,  150,  150,  163,  220,   67,  166,  167,
106039  /*   610 */   168,  150,  169,  170,  171,  161,  162,   25,  165,  165,
106040  /*   620 */   150,  113,   49,   50,   25,  117,  165,  174,  175,   35,
106041  /*   630 */     7,    8,    9,  160,  160,  165,  120,  100,   67,  247,
106042  /*   640 */   248,   68,   69,   70,   71,   72,   73,   74,   75,   76,
106043  /*   650 */    77,   78,   79,   80,  193,   82,   83,   84,   85,   86,
106044  /*   660 */    87,   88,   89,   90,   91,   92,   19,  194,  194,  150,
106045  /*   670 */   135,   24,  137,   35,  231,  138,  150,  129,  130,  206,
106046  /*   680 */   207,   30,   27,  213,  165,   34,  118,   95,    0,    1,
106047  /*   690 */     2,  165,  218,  174,  175,   50,   49,   50,   22,   48,
106048  /*   700 */   174,  175,   22,   23,   23,  244,  222,  223,  224,  166,
106049  /*   710 */   167,  168,  120,  239,   23,   68,   69,   70,   71,   72,
106050  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
106051  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
106052  /*   740 */    19,  150,  173,  165,  181,  182,   24,   67,   26,  104,
106053  /*   750 */   181,  188,  174,  175,  150,   39,  165,  150,   52,  150,
106054  /*   760 */   150,  150,  150,  144,  145,  174,  175,  249,  250,  165,
106055  /*   770 */    49,   50,  165,   52,  165,  165,  165,  165,  174,  175,
106056  /*   780 */    29,  174,  175,  174,  175,  174,  175,  160,   22,   68,
106057  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
106058  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
106059  /*   810 */    89,   90,   91,   92,   19,  150,   94,  165,  150,  150,
106060  /*   820 */   160,  194,  150,  213,  160,   52,  174,  175,   23,   23,
106061  /*   830 */   165,   25,   22,  165,  165,  150,  150,  165,   52,  174,
106062  /*   840 */   175,   22,  174,  175,   49,   50,  174,  175,  190,  191,
106063  /*   850 */   165,  165,  240,   23,  194,   25,  187,  109,  194,  174,
106064  /*   860 */   175,  190,  191,   68,   69,   70,   71,   72,   73,   74,
106065  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
106066  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
106067  /*   890 */    22,  165,  150,   23,  150,   25,  150,  166,   91,   92,
106068  /*   900 */   174,  175,   22,  217,  165,  150,  102,  165,  150,  165,
106069  /*   910 */   150,  165,  150,  174,  175,   19,  174,  175,   49,   50,
106070  /*   920 */   165,   86,   87,  165,   23,  165,   25,  165,   24,  174,
106071  /*   930 */   175,  187,  174,  175,  174,  175,  205,   68,   69,   70,
106072  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
106073  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
106074  /*   960 */    91,   92,   19,  150,  150,  165,  150,  150,  166,   23,
106075  /*   970 */   150,   25,  160,   20,  174,  175,    1,    2,  165,  165,
106076  /*   980 */   104,  165,  165,   43,  150,  165,  240,  150,   49,   50,
106077  /*   990 */   174,  175,   49,   50,   23,   23,   25,   25,   53,  165,
106078  /*  1000 */   187,  187,  165,   23,  187,   25,  194,  205,  174,  175,
106079  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
106080  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
106081  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
106082  /*  1040 */   150,  160,  150,   59,   25,   53,  104,   22,  174,  175,
106083  /*  1050 */   213,  138,    5,  165,    1,  165,  150,  165,  150,  150,
106084  /*  1060 */   240,  150,  174,  175,  174,  175,   49,   50,  118,  150,
106085  /*  1070 */    35,  165,   27,  165,  165,  194,  165,  108,  127,   76,
106086  /*  1080 */   174,  175,  174,  175,  165,  174,  175,   70,   71,   72,
106087  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  166,   82,
106088  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
106089  /*  1110 */    19,   20,  193,   22,  150,  150,  150,   26,   27,   76,
106090  /*  1120 */   150,   22,    1,  150,  119,  121,  217,   20,   37,  165,
106091  /*  1130 */   165,  165,   16,   19,   20,  165,   22,  205,  165,  119,
106092  /*  1140 */    26,   27,  108,  128,  150,  150,  150,   56,  150,   22,
106093  /*  1150 */   150,   37,  150,  127,  160,   23,  150,   66,  193,  165,
106094  /*  1160 */   165,  165,   16,  165,   23,  165,  150,  165,  174,  175,
106095  /*  1170 */    56,  165,  150,   65,  174,  175,   15,   86,   87,   88,
106096  /*  1180 */    66,  165,  140,  150,   93,   94,   95,  165,  194,   98,
106097  /*  1190 */   174,  175,   22,    3,  164,  193,  174,  175,  165,  150,
106098  /*  1200 */    86,   87,    4,  180,  150,  248,  251,   93,   94,   95,
106099  /*  1210 */   216,  180,   98,  251,  165,  221,  150,  149,    6,  165,
106100  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
106101  /*  1230 */   116,  165,   19,   20,  150,   22,  149,  151,  150,   26,
106102  /*  1240 */    27,  149,  165,  129,  130,  131,  132,  133,  134,  165,
106103  /*  1250 */    37,  174,  175,  165,  149,   19,   20,   13,   22,  150,
106104  /*  1260 */   150,  150,   26,   27,  146,  147,  151,  150,   25,   56,
106105  /*  1270 */   152,  159,  154,   37,  165,  165,  165,  193,  160,   66,
106106  /*  1280 */   116,  193,  165,  174,  175,  174,  175,  194,  199,  150,
106107  /*  1290 */   200,  126,   56,  124,  123,  150,  201,  122,  150,   86,
106108  /*  1300 */    87,  150,   66,  193,  165,  202,   93,   94,   95,  150,
106109  /*  1310 */   165,   98,  194,  165,  125,   22,  165,  150,  150,   26,
106110  /*  1320 */    27,  135,   86,   87,  165,  174,  175,  203,  226,   93,
106111  /*  1330 */    94,   95,  165,  165,   98,  150,  218,  150,  193,  157,
106112  /*  1340 */   118,  157,  129,  130,  131,  132,  133,  134,    5,  104,
106113  /*  1350 */   165,  211,  165,   10,   11,   12,   13,   14,  150,   66,
106114  /*  1360 */    17,  174,  175,  210,  246,  129,  130,  131,  132,  133,
106115  /*  1370 */   134,  150,  210,  165,   31,  121,   33,  150,  150,   86,
106116  /*  1380 */    87,  176,  174,  175,  150,   42,  165,   94,  211,  210,
106117  /*  1390 */   150,   98,  165,  165,  211,  174,  175,  150,   55,  165,
106118  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
106119  /*  1410 */   150,  150,  165,  150,  174,  175,  165,  104,  150,  184,
106120  /*  1420 */   150,  165,  129,  130,  131,  165,  165,  150,  165,  150,
106121  /*  1430 */   150,  176,  150,  165,   47,  165,  150,  150,  176,  103,
106122  /*  1440 */   150,   22,  165,  178,  165,  165,  179,  165,  105,  106,
106123  /*  1450 */   107,  165,  165,  229,  111,  165,   92,  176,  229,  116,
106124  /*  1460 */   184,  176,  179,  156,  176,  176,   18,  157,  156,  237,
106125  /*  1470 */    45,  157,  156,  135,  157,  157,  238,  156,   68,  157,
106126  /*  1480 */   189,  189,  139,  219,   22,  157,   18,  192,  192,  192,
106127  /*  1490 */   192,  189,  219,  199,  157,  242,   40,  157,  199,  242,
106128  /*  1500 */   153,  157,   38,  245,  196,  166,  232,  198,  177,  177,
106129  /*  1510 */   232,  227,  209,  178,  166,  182,  166,  148,  177,  177,
106130  /*  1520 */   209,  196,  177,  199,  209,  199,  166,  208,   92,  195,
106131  /*  1530 */   174,  174,  183,  252,  183,  183,  252,  191,  252,  235,
106132  /*  1540 */   186,  241,  241,  252,  186,  252,  252,  252,  252,  252,
106133  /*  1550 */   252,  252,  252,  252,  252,  252,  236,
106134 };
106135 #define YY_SHIFT_USE_DFLT (-74)
106136 #define YY_SHIFT_COUNT (418)
106137 #define YY_SHIFT_MIN   (-73)
106138 #define YY_SHIFT_MAX   (1468)
106139 static const short yy_shift_ofst[] = {
106140  /*     0 */   975, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
106141  /*    10 */  1213, 1213, 1213, 1213, 1213,  345,  445,  721, 1091, 1213,
106142  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106143  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106144  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
106145  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
106146  /*    60 */  1213,  199,  445,  445,  835,  835,  365, 1164,   55,  647,
106147  /*    70 */   573,  499,  425,  351,  277,  203,  129,  795,  795,  795,
106148  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
106149  /*    90 */   795,  795,  795,  795,  795,  869,  795,  943, 1017, 1017,
106150  /*   100 */   -69,  -45,  -45,  -45,  -45,  -45,   -1,   58,  138,  100,
106151  /*   110 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
106152  /*   120 */   445,  445,  445,  445,  445,  445,  537,  438,  445,  445,
106153  /*   130 */   445,  445,  445,  365,  807, 1436,  -74,  -74,  -74, 1293,
106154  /*   140 */    73,  434,  434,  311,  314,  290,  283,  286,  540,  467,
106155  /*   150 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
106156  /*   160 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
106157  /*   170 */   445,  445,  445,  445,  445,  445,  445,  445,  445,  445,
106158  /*   180 */   445,  445,   65,  722,  722,  722,  688,  266, 1164, 1164,
106159  /*   190 */  1164,  -74,  -74,  -74,  136,  168,  168,  234,  360,  360,
106160  /*   200 */   360,  430,  372,  435,  352,  278,  126,  -36,  -36,  -36,
106161  /*   210 */   -36,  421,  651,  -36,  -36,  592,  292,  212,  623,  158,
106162  /*   220 */   204,  204,  505,  158,  505,  144,  365,  154,  365,  154,
106163  /*   230 */   645,  154,  204,  154,  154,  535,  548,  548,  365,  387,
106164  /*   240 */   508,  233, 1464, 1222, 1222, 1456, 1456, 1222, 1462, 1410,
106165  /*   250 */  1165, 1468, 1468, 1468, 1468, 1222, 1165, 1462, 1410, 1410,
106166  /*   260 */  1222, 1448, 1338, 1425, 1222, 1222, 1448, 1222, 1448, 1222,
106167  /*   270 */  1448, 1419, 1313, 1313, 1313, 1387, 1364, 1364, 1419, 1313,
106168  /*   280 */  1336, 1313, 1387, 1313, 1313, 1254, 1245, 1254, 1245, 1254,
106169  /*   290 */  1245, 1222, 1222, 1186, 1189, 1175, 1169, 1171, 1165, 1164,
106170  /*   300 */  1243, 1244, 1244, 1212, 1212, 1212, 1212,  -74,  -74,  -74,
106171  /*   310 */   -74,  -74,  -74,  939,  104,  680,  571,  327,    1,  980,
106172  /*   320 */    26,  972,  971,  946,  901,  870,  830,  806,   54,   21,
106173  /*   330 */   -73,  510,  242, 1198, 1190, 1170, 1042, 1161, 1108, 1146,
106174  /*   340 */  1141, 1132, 1015, 1127, 1026, 1034, 1020, 1107, 1004, 1116,
106175  /*   350 */  1121, 1005, 1099,  951, 1043, 1003,  969, 1045, 1035,  950,
106176  /*   360 */  1053, 1047, 1025,  942,  913,  992, 1019,  945,  984,  940,
106177  /*   370 */   876,  904,  953,  896,  748,  804,  880,  786,  868,  819,
106178  /*   380 */   805,  810,  773,  751,  766,  706,  716,  691,  681,  568,
106179  /*   390 */   655,  638,  676,  516,  541,  594,  599,  567,  541,  534,
106180  /*   400 */   507,  527,  498,  523,  466,  382,  409,  384,  357,    6,
106181  /*   410 */   240,  224,  143,   62,   18,   71,   39,    9,    5,
106182 };
106183 #define YY_REDUCE_USE_DFLT (-142)
106184 #define YY_REDUCE_COUNT (312)
106185 #define YY_REDUCE_MIN   (-141)
106186 #define YY_REDUCE_MAX   (1369)
106187 static const short yy_reduce_ofst[] = {
106188  /*     0 */  -141,  994, 1118,  223,  157,  -53,   93,   89,   83,  375,
106189  /*    10 */   386,  381,  379,  308,  295,  325,  -47,   27, 1240, 1234,
106190  /*    20 */  1228, 1221, 1208, 1187, 1151, 1111, 1109, 1077, 1054, 1022,
106191  /*    30 */  1016, 1000,  911,  908,  906,  890,  888,  874,  834,  816,
106192  /*    40 */   800,  760,  758,  755,  742,  739,  726,  685,  672,  668,
106193  /*    50 */   665,  652,  611,  609,  607,  604,  591,  578,  526,  519,
106194  /*    60 */   453,  474,  454,  461,  443,  245,  442,  473,  484,  484,
106195  /*    70 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
106196  /*    80 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
106197  /*    90 */   484,  484,  484,  484,  484,  484,  484,  484,  484,  484,
106198  /*   100 */   484,  484,  484,  484,  484,  484,  484,  130,  484,  484,
106199  /*   110 */  1145,  909, 1110, 1088, 1084, 1033, 1002,  965,  820,  837,
106200  /*   120 */   746,  686,  612,  817,  610,  919,  221,  563,  814,  813,
106201  /*   130 */   744,  669,  470,  543,  484,  484,  484,  484,  484,  291,
106202  /*   140 */   569,  671,  658,  970, 1290, 1287, 1286, 1282,  518,  518,
106203  /*   150 */  1280, 1279, 1277, 1270, 1268, 1263, 1261, 1260, 1256, 1251,
106204  /*   160 */  1247, 1227, 1185, 1168, 1167, 1159, 1148, 1139, 1117, 1066,
106205  /*   170 */  1049, 1006,  998,  996,  995,  973,  970,  966,  964,  892,
106206  /*   180 */   762,  -52,  881,  932,  802,  731,  619,  812,  664,  660,
106207  /*   190 */   627,  392,  331,  124, 1358, 1357, 1356, 1354, 1352, 1351,
106208  /*   200 */  1349, 1319, 1334, 1346, 1334, 1334, 1334, 1334, 1334, 1334,
106209  /*   210 */  1334, 1320, 1304, 1334, 1334, 1319, 1360, 1325, 1369, 1326,
106210  /*   220 */  1315, 1311, 1301, 1324, 1300, 1335, 1350, 1345, 1348, 1342,
106211  /*   230 */  1333, 1341, 1303, 1332, 1331, 1284, 1278, 1274, 1339, 1309,
106212  /*   240 */  1308, 1347, 1258, 1344, 1340, 1257, 1253, 1337, 1273, 1302,
106213  /*   250 */  1299, 1298, 1297, 1296, 1295, 1328, 1294, 1264, 1292, 1291,
106214  /*   260 */  1322, 1321, 1238, 1232, 1318, 1317, 1316, 1314, 1312, 1310,
106215  /*   270 */  1307, 1283, 1289, 1288, 1285, 1276, 1229, 1224, 1267, 1281,
106216  /*   280 */  1265, 1262, 1235, 1255, 1205, 1183, 1179, 1177, 1162, 1140,
106217  /*   290 */  1153, 1184, 1182, 1102, 1124, 1103, 1095, 1090, 1089, 1093,
106218  /*   300 */  1112, 1115, 1086, 1105, 1092, 1087, 1068,  962,  955,  957,
106219  /*   310 */  1031, 1023, 1030,
106220 };
106221 static const YYACTIONTYPE yy_default[] = {
106222  /*     0 */   635,  870,  959,  959,  959,  870,  899,  899,  959,  759,
106223  /*    10 */   959,  959,  959,  959,  868,  959,  959,  933,  959,  959,
106224  /*    20 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106225  /*    30 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106226  /*    40 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106227  /*    50 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106228  /*    60 */   959,  959,  959,  959,  899,  899,  674,  763,  794,  959,
106229  /*    70 */   959,  959,  959,  959,  959,  959,  959,  932,  934,  809,
106230  /*    80 */   808,  802,  801,  912,  774,  799,  792,  785,  796,  871,
106231  /*    90 */   864,  865,  863,  867,  872,  959,  795,  831,  848,  830,
106232  /*   100 */   842,  847,  854,  846,  843,  833,  832,  666,  834,  835,
106233  /*   110 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106234  /*   120 */   959,  959,  959,  959,  959,  959,  661,  728,  959,  959,
106235  /*   130 */   959,  959,  959,  959,  836,  837,  851,  850,  849,  959,
106236  /*   140 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106237  /*   150 */   959,  939,  937,  959,  883,  959,  959,  959,  959,  959,
106238  /*   160 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106239  /*   170 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106240  /*   180 */   959,  641,  959,  759,  759,  759,  635,  959,  959,  959,
106241  /*   190 */   959,  951,  763,  753,  719,  959,  959,  959,  959,  959,
106242  /*   200 */   959,  959,  959,  959,  959,  959,  959,  804,  742,  922,
106243  /*   210 */   924,  959,  905,  740,  663,  761,  676,  751,  643,  798,
106244  /*   220 */   776,  776,  917,  798,  917,  700,  959,  788,  959,  788,
106245  /*   230 */   697,  788,  776,  788,  788,  866,  959,  959,  959,  760,
106246  /*   240 */   751,  959,  944,  767,  767,  936,  936,  767,  810,  732,
106247  /*   250 */   798,  739,  739,  739,  739,  767,  798,  810,  732,  732,
106248  /*   260 */   767,  658,  911,  909,  767,  767,  658,  767,  658,  767,
106249  /*   270 */   658,  876,  730,  730,  730,  715,  880,  880,  876,  730,
106250  /*   280 */   700,  730,  715,  730,  730,  780,  775,  780,  775,  780,
106251  /*   290 */   775,  767,  767,  959,  793,  781,  791,  789,  798,  959,
106252  /*   300 */   718,  651,  651,  640,  640,  640,  640,  956,  956,  951,
106253  /*   310 */   702,  702,  684,  959,  959,  959,  959,  959,  959,  959,
106254  /*   320 */   885,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106255  /*   330 */   959,  959,  959,  959,  636,  946,  959,  959,  943,  959,
106256  /*   340 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106257  /*   350 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  915,
106258  /*   360 */   959,  959,  959,  959,  959,  959,  908,  907,  959,  959,
106259  /*   370 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106260  /*   380 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  959,
106261  /*   390 */   959,  959,  959,  959,  790,  959,  782,  959,  869,  959,
106262  /*   400 */   959,  959,  959,  959,  959,  959,  959,  959,  959,  745,
106263  /*   410 */   819,  959,  818,  822,  817,  668,  959,  649,  959,  632,
106264  /*   420 */   637,  955,  958,  957,  954,  953,  952,  947,  945,  942,
106265  /*   430 */   941,  940,  938,  935,  931,  889,  887,  894,  893,  892,
106266  /*   440 */   891,  890,  888,  886,  884,  805,  803,  800,  797,  930,
106267  /*   450 */   882,  741,  738,  737,  657,  948,  914,  923,  921,  811,
106268  /*   460 */   920,  919,  918,  916,  913,  900,  807,  806,  733,  874,
106269  /*   470 */   873,  660,  904,  903,  902,  906,  910,  901,  769,  659,
106270  /*   480 */   656,  665,  722,  721,  729,  727,  726,  725,  724,  723,
106271  /*   490 */   720,  667,  675,  686,  714,  699,  698,  879,  881,  878,
106272  /*   500 */   877,  707,  706,  712,  711,  710,  709,  708,  705,  704,
106273  /*   510 */   703,  696,  695,  701,  694,  717,  716,  713,  693,  736,
106274  /*   520 */   735,  734,  731,  692,  691,  690,  822,  689,  688,  828,
106275  /*   530 */   827,  815,  858,  756,  755,  754,  766,  765,  778,  777,
106276  /*   540 */   813,  812,  779,  764,  758,  757,  773,  772,  771,  770,
106277  /*   550 */   762,  752,  784,  787,  786,  783,  860,  768,  857,  929,
106278  /*   560 */   928,  927,  926,  925,  862,  861,  829,  826,  679,  680,
106279  /*   570 */   898,  896,  897,  895,  682,  681,  678,  677,  859,  747,
106280  /*   580 */   746,  855,  852,  844,  840,  856,  853,  845,  841,  839,
106281  /*   590 */   838,  824,  823,  821,  820,  816,  825,  670,  748,  744,
106282  /*   600 */   743,  814,  750,  749,  687,  685,  683,  664,  662,  655,
106283  /*   610 */   653,  652,  654,  650,  648,  647,  646,  645,  644,  673,
106284  /*   620 */   672,  671,  669,  668,  642,  639,  638,  634,  633,  631,
106285 };
106286 
106287 /* The next table maps tokens into fallback tokens.  If a construct
106288 ** like the following:
106289 **
106290 **      %fallback ID X Y Z.
106291 **
106292 ** appears in the grammar, then ID becomes a fallback token for X, Y,
106293 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
106294 ** but it does not parse, the type of the token is changed to ID and
106295 ** the parse is retried before an error is thrown.
106296 */
106297 #ifdef YYFALLBACK
106298 static const YYCODETYPE yyFallback[] = {
106299     0,  /*          $ => nothing */
106300     0,  /*       SEMI => nothing */
106301    26,  /*    EXPLAIN => ID */
106302    26,  /*      QUERY => ID */
106303    26,  /*       PLAN => ID */
106304    26,  /*      BEGIN => ID */
106305     0,  /* TRANSACTION => nothing */
106306    26,  /*   DEFERRED => ID */
106307    26,  /*  IMMEDIATE => ID */
106308    26,  /*  EXCLUSIVE => ID */
106309     0,  /*     COMMIT => nothing */
106310    26,  /*        END => ID */
106311    26,  /*   ROLLBACK => ID */
106312    26,  /*  SAVEPOINT => ID */
106313    26,  /*    RELEASE => ID */
106314     0,  /*         TO => nothing */
106315     0,  /*      TABLE => nothing */
106316     0,  /*     CREATE => nothing */
106317    26,  /*         IF => ID */
106318     0,  /*        NOT => nothing */
106319     0,  /*     EXISTS => nothing */
106320    26,  /*       TEMP => ID */
106321     0,  /*         LP => nothing */
106322     0,  /*         RP => nothing */
106323     0,  /*         AS => nothing */
106324     0,  /*      COMMA => nothing */
106325     0,  /*         ID => nothing */
106326     0,  /*    INDEXED => nothing */
106327    26,  /*      ABORT => ID */
106328    26,  /*     ACTION => ID */
106329    26,  /*      AFTER => ID */
106330    26,  /*    ANALYZE => ID */
106331    26,  /*        ASC => ID */
106332    26,  /*     ATTACH => ID */
106333    26,  /*     BEFORE => ID */
106334    26,  /*         BY => ID */
106335    26,  /*    CASCADE => ID */
106336    26,  /*       CAST => ID */
106337    26,  /*   COLUMNKW => ID */
106338    26,  /*   CONFLICT => ID */
106339    26,  /*   DATABASE => ID */
106340    26,  /*       DESC => ID */
106341    26,  /*     DETACH => ID */
106342    26,  /*       EACH => ID */
106343    26,  /*       FAIL => ID */
106344    26,  /*        FOR => ID */
106345    26,  /*     IGNORE => ID */
106346    26,  /*  INITIALLY => ID */
106347    26,  /*    INSTEAD => ID */
106348    26,  /*    LIKE_KW => ID */
106349    26,  /*      MATCH => ID */
106350    26,  /*         NO => ID */
106351    26,  /*        KEY => ID */
106352    26,  /*         OF => ID */
106353    26,  /*     OFFSET => ID */
106354    26,  /*     PRAGMA => ID */
106355    26,  /*      RAISE => ID */
106356    26,  /*    REPLACE => ID */
106357    26,  /*   RESTRICT => ID */
106358    26,  /*        ROW => ID */
106359    26,  /*    TRIGGER => ID */
106360    26,  /*     VACUUM => ID */
106361    26,  /*       VIEW => ID */
106362    26,  /*    VIRTUAL => ID */
106363    26,  /*    REINDEX => ID */
106364    26,  /*     RENAME => ID */
106365    26,  /*   CTIME_KW => ID */
106366 };
106367 #endif /* YYFALLBACK */
106368 
106369 /* The following structure represents a single element of the
106370 ** parser's stack.  Information stored includes:
106371 **
106372 **   +  The state number for the parser at this level of the stack.
106373 **
106374 **   +  The value of the token stored at this level of the stack.
106375 **      (In other words, the "major" token.)
106376 **
106377 **   +  The semantic value stored at this level of the stack.  This is
106378 **      the information used by the action routines in the grammar.
106379 **      It is sometimes called the "minor" token.
106380 */
106381 struct yyStackEntry {
106382   YYACTIONTYPE stateno;  /* The state-number */
106383   YYCODETYPE major;      /* The major token value.  This is the code
106384                          ** number for the token at this stack level */
106385   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
106386                          ** is the value of the token  */
106387 };
106388 typedef struct yyStackEntry yyStackEntry;
106389 
106390 /* The state of the parser is completely contained in an instance of
106391 ** the following structure */
106392 struct yyParser {
106393   int yyidx;                    /* Index of top element in stack */
106394 #ifdef YYTRACKMAXSTACKDEPTH
106395   int yyidxMax;                 /* Maximum value of yyidx */
106396 #endif
106397   int yyerrcnt;                 /* Shifts left before out of the error */
106398   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
106399 #if YYSTACKDEPTH<=0
106400   int yystksz;                  /* Current side of the stack */
106401   yyStackEntry *yystack;        /* The parser's stack */
106402 #else
106403   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
106404 #endif
106405 };
106406 typedef struct yyParser yyParser;
106407 
106408 #ifndef NDEBUG
106409 /* #include <stdio.h> */
106410 static FILE *yyTraceFILE = 0;
106411 static char *yyTracePrompt = 0;
106412 #endif /* NDEBUG */
106413 
106414 #ifndef NDEBUG
106415 /*
106416 ** Turn parser tracing on by giving a stream to which to write the trace
106417 ** and a prompt to preface each trace message.  Tracing is turned off
106418 ** by making either argument NULL
106419 **
106420 ** Inputs:
106421 ** <ul>
106422 ** <li> A FILE* to which trace output should be written.
106423 **      If NULL, then tracing is turned off.
106424 ** <li> A prefix string written at the beginning of every
106425 **      line of trace output.  If NULL, then tracing is
106426 **      turned off.
106427 ** </ul>
106428 **
106429 ** Outputs:
106430 ** None.
106431 */
106432 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
106433   yyTraceFILE = TraceFILE;
106434   yyTracePrompt = zTracePrompt;
106435   if( yyTraceFILE==0 ) yyTracePrompt = 0;
106436   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
106437 }
106438 #endif /* NDEBUG */
106439 
106440 #ifndef NDEBUG
106441 /* For tracing shifts, the names of all terminals and nonterminals
106442 ** are required.  The following table supplies these names */
106443 static const char *const yyTokenName[] = {
106444   "$",             "SEMI",          "EXPLAIN",       "QUERY",
106445   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
106446   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
106447   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
106448   "TABLE",         "CREATE",        "IF",            "NOT",
106449   "EXISTS",        "TEMP",          "LP",            "RP",
106450   "AS",            "COMMA",         "ID",            "INDEXED",
106451   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
106452   "ASC",           "ATTACH",        "BEFORE",        "BY",
106453   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
106454   "DATABASE",      "DESC",          "DETACH",        "EACH",
106455   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
106456   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
106457   "KEY",           "OF",            "OFFSET",        "PRAGMA",
106458   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
106459   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
106460   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
106461   "OR",            "AND",           "IS",            "BETWEEN",
106462   "IN",            "ISNULL",        "NOTNULL",       "NE",
106463   "EQ",            "GT",            "LE",            "LT",
106464   "GE",            "ESCAPE",        "BITAND",        "BITOR",
106465   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
106466   "STAR",          "SLASH",         "REM",           "CONCAT",
106467   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
106468   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
106469   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
106470   "ON",            "INSERT",        "DELETE",        "UPDATE",
106471   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
106472   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
106473   "SELECT",        "DISTINCT",      "DOT",           "FROM",
106474   "JOIN",          "USING",         "ORDER",         "GROUP",
106475   "HAVING",        "LIMIT",         "WHERE",         "INTO",
106476   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
106477   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
106478   "THEN",          "ELSE",          "INDEX",         "ALTER",
106479   "ADD",           "error",         "input",         "cmdlist",
106480   "ecmd",          "explain",       "cmdx",          "cmd",
106481   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
106482   "create_table",  "create_table_args",  "createkw",      "temp",
106483   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
106484   "select",        "column",        "columnid",      "type",
106485   "carglist",      "id",            "ids",           "typetoken",
106486   "typename",      "signed",        "plus_num",      "minus_num",
106487   "carg",          "ccons",         "term",          "expr",
106488   "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
106489   "refargs",       "defer_subclause",  "refarg",        "refact",
106490   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
106491   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
106492   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
106493   "distinct",      "selcollist",    "from",          "where_opt",
106494   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
106495   "sclp",          "as",            "seltablist",    "stl_prefix",
106496   "joinop",        "indexed_opt",   "on_opt",        "using_opt",
106497   "joinop2",       "inscollist",    "sortlist",      "sortitem",
106498   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
106499   "itemlist",      "exprlist",      "likeop",        "between_op",
106500   "in_op",         "case_operand",  "case_exprlist",  "case_else",
106501   "uniqueflag",    "collate",       "nmnum",         "plus_opt",
106502   "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
106503   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd",
106504   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",
106505   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist",
106506   "vtabarg",       "vtabargtoken",  "lp",            "anylist",
106507 };
106508 #endif /* NDEBUG */
106509 
106510 #ifndef NDEBUG
106511 /* For tracing reduce actions, the names of all rules are required.
106512 */
106513 static const char *const yyRuleName[] = {
106514  /*   0 */ "input ::= cmdlist",
106515  /*   1 */ "cmdlist ::= cmdlist ecmd",
106516  /*   2 */ "cmdlist ::= ecmd",
106517  /*   3 */ "ecmd ::= SEMI",
106518  /*   4 */ "ecmd ::= explain cmdx SEMI",
106519  /*   5 */ "explain ::=",
106520  /*   6 */ "explain ::= EXPLAIN",
106521  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
106522  /*   8 */ "cmdx ::= cmd",
106523  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
106524  /*  10 */ "trans_opt ::=",
106525  /*  11 */ "trans_opt ::= TRANSACTION",
106526  /*  12 */ "trans_opt ::= TRANSACTION nm",
106527  /*  13 */ "transtype ::=",
106528  /*  14 */ "transtype ::= DEFERRED",
106529  /*  15 */ "transtype ::= IMMEDIATE",
106530  /*  16 */ "transtype ::= EXCLUSIVE",
106531  /*  17 */ "cmd ::= COMMIT trans_opt",
106532  /*  18 */ "cmd ::= END trans_opt",
106533  /*  19 */ "cmd ::= ROLLBACK trans_opt",
106534  /*  20 */ "savepoint_opt ::= SAVEPOINT",
106535  /*  21 */ "savepoint_opt ::=",
106536  /*  22 */ "cmd ::= SAVEPOINT nm",
106537  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
106538  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
106539  /*  25 */ "cmd ::= create_table create_table_args",
106540  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
106541  /*  27 */ "createkw ::= CREATE",
106542  /*  28 */ "ifnotexists ::=",
106543  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
106544  /*  30 */ "temp ::= TEMP",
106545  /*  31 */ "temp ::=",
106546  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
106547  /*  33 */ "create_table_args ::= AS select",
106548  /*  34 */ "columnlist ::= columnlist COMMA column",
106549  /*  35 */ "columnlist ::= column",
106550  /*  36 */ "column ::= columnid type carglist",
106551  /*  37 */ "columnid ::= nm",
106552  /*  38 */ "id ::= ID",
106553  /*  39 */ "id ::= INDEXED",
106554  /*  40 */ "ids ::= ID|STRING",
106555  /*  41 */ "nm ::= id",
106556  /*  42 */ "nm ::= STRING",
106557  /*  43 */ "nm ::= JOIN_KW",
106558  /*  44 */ "type ::=",
106559  /*  45 */ "type ::= typetoken",
106560  /*  46 */ "typetoken ::= typename",
106561  /*  47 */ "typetoken ::= typename LP signed RP",
106562  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
106563  /*  49 */ "typename ::= ids",
106564  /*  50 */ "typename ::= typename ids",
106565  /*  51 */ "signed ::= plus_num",
106566  /*  52 */ "signed ::= minus_num",
106567  /*  53 */ "carglist ::= carglist carg",
106568  /*  54 */ "carglist ::=",
106569  /*  55 */ "carg ::= CONSTRAINT nm ccons",
106570  /*  56 */ "carg ::= ccons",
106571  /*  57 */ "ccons ::= DEFAULT term",
106572  /*  58 */ "ccons ::= DEFAULT LP expr RP",
106573  /*  59 */ "ccons ::= DEFAULT PLUS term",
106574  /*  60 */ "ccons ::= DEFAULT MINUS term",
106575  /*  61 */ "ccons ::= DEFAULT id",
106576  /*  62 */ "ccons ::= NULL onconf",
106577  /*  63 */ "ccons ::= NOT NULL onconf",
106578  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
106579  /*  65 */ "ccons ::= UNIQUE onconf",
106580  /*  66 */ "ccons ::= CHECK LP expr RP",
106581  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
106582  /*  68 */ "ccons ::= defer_subclause",
106583  /*  69 */ "ccons ::= COLLATE ids",
106584  /*  70 */ "autoinc ::=",
106585  /*  71 */ "autoinc ::= AUTOINCR",
106586  /*  72 */ "refargs ::=",
106587  /*  73 */ "refargs ::= refargs refarg",
106588  /*  74 */ "refarg ::= MATCH nm",
106589  /*  75 */ "refarg ::= ON INSERT refact",
106590  /*  76 */ "refarg ::= ON DELETE refact",
106591  /*  77 */ "refarg ::= ON UPDATE refact",
106592  /*  78 */ "refact ::= SET NULL",
106593  /*  79 */ "refact ::= SET DEFAULT",
106594  /*  80 */ "refact ::= CASCADE",
106595  /*  81 */ "refact ::= RESTRICT",
106596  /*  82 */ "refact ::= NO ACTION",
106597  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
106598  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
106599  /*  85 */ "init_deferred_pred_opt ::=",
106600  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
106601  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
106602  /*  88 */ "conslist_opt ::=",
106603  /*  89 */ "conslist_opt ::= COMMA conslist",
106604  /*  90 */ "conslist ::= conslist COMMA tcons",
106605  /*  91 */ "conslist ::= conslist tcons",
106606  /*  92 */ "conslist ::= tcons",
106607  /*  93 */ "tcons ::= CONSTRAINT nm",
106608  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
106609  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
106610  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
106611  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
106612  /*  98 */ "defer_subclause_opt ::=",
106613  /*  99 */ "defer_subclause_opt ::= defer_subclause",
106614  /* 100 */ "onconf ::=",
106615  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
106616  /* 102 */ "orconf ::=",
106617  /* 103 */ "orconf ::= OR resolvetype",
106618  /* 104 */ "resolvetype ::= raisetype",
106619  /* 105 */ "resolvetype ::= IGNORE",
106620  /* 106 */ "resolvetype ::= REPLACE",
106621  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
106622  /* 108 */ "ifexists ::= IF EXISTS",
106623  /* 109 */ "ifexists ::=",
106624  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
106625  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
106626  /* 112 */ "cmd ::= select",
106627  /* 113 */ "select ::= oneselect",
106628  /* 114 */ "select ::= select multiselect_op oneselect",
106629  /* 115 */ "multiselect_op ::= UNION",
106630  /* 116 */ "multiselect_op ::= UNION ALL",
106631  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
106632  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
106633  /* 119 */ "distinct ::= DISTINCT",
106634  /* 120 */ "distinct ::= ALL",
106635  /* 121 */ "distinct ::=",
106636  /* 122 */ "sclp ::= selcollist COMMA",
106637  /* 123 */ "sclp ::=",
106638  /* 124 */ "selcollist ::= sclp expr as",
106639  /* 125 */ "selcollist ::= sclp STAR",
106640  /* 126 */ "selcollist ::= sclp nm DOT STAR",
106641  /* 127 */ "as ::= AS nm",
106642  /* 128 */ "as ::= ids",
106643  /* 129 */ "as ::=",
106644  /* 130 */ "from ::=",
106645  /* 131 */ "from ::= FROM seltablist",
106646  /* 132 */ "stl_prefix ::= seltablist joinop",
106647  /* 133 */ "stl_prefix ::=",
106648  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
106649  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
106650  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
106651  /* 137 */ "dbnm ::=",
106652  /* 138 */ "dbnm ::= DOT nm",
106653  /* 139 */ "fullname ::= nm dbnm",
106654  /* 140 */ "joinop ::= COMMA|JOIN",
106655  /* 141 */ "joinop ::= JOIN_KW JOIN",
106656  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
106657  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
106658  /* 144 */ "on_opt ::= ON expr",
106659  /* 145 */ "on_opt ::=",
106660  /* 146 */ "indexed_opt ::=",
106661  /* 147 */ "indexed_opt ::= INDEXED BY nm",
106662  /* 148 */ "indexed_opt ::= NOT INDEXED",
106663  /* 149 */ "using_opt ::= USING LP inscollist RP",
106664  /* 150 */ "using_opt ::=",
106665  /* 151 */ "orderby_opt ::=",
106666  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
106667  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
106668  /* 154 */ "sortlist ::= sortitem sortorder",
106669  /* 155 */ "sortitem ::= expr",
106670  /* 156 */ "sortorder ::= ASC",
106671  /* 157 */ "sortorder ::= DESC",
106672  /* 158 */ "sortorder ::=",
106673  /* 159 */ "groupby_opt ::=",
106674  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
106675  /* 161 */ "having_opt ::=",
106676  /* 162 */ "having_opt ::= HAVING expr",
106677  /* 163 */ "limit_opt ::=",
106678  /* 164 */ "limit_opt ::= LIMIT expr",
106679  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
106680  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
106681  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
106682  /* 168 */ "where_opt ::=",
106683  /* 169 */ "where_opt ::= WHERE expr",
106684  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
106685  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
106686  /* 172 */ "setlist ::= nm EQ expr",
106687  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
106688  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
106689  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
106690  /* 176 */ "insert_cmd ::= INSERT orconf",
106691  /* 177 */ "insert_cmd ::= REPLACE",
106692  /* 178 */ "itemlist ::= itemlist COMMA expr",
106693  /* 179 */ "itemlist ::= expr",
106694  /* 180 */ "inscollist_opt ::=",
106695  /* 181 */ "inscollist_opt ::= LP inscollist RP",
106696  /* 182 */ "inscollist ::= inscollist COMMA nm",
106697  /* 183 */ "inscollist ::= nm",
106698  /* 184 */ "expr ::= term",
106699  /* 185 */ "expr ::= LP expr RP",
106700  /* 186 */ "term ::= NULL",
106701  /* 187 */ "expr ::= id",
106702  /* 188 */ "expr ::= JOIN_KW",
106703  /* 189 */ "expr ::= nm DOT nm",
106704  /* 190 */ "expr ::= nm DOT nm DOT nm",
106705  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
106706  /* 192 */ "term ::= STRING",
106707  /* 193 */ "expr ::= REGISTER",
106708  /* 194 */ "expr ::= VARIABLE",
106709  /* 195 */ "expr ::= expr COLLATE ids",
106710  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
106711  /* 197 */ "expr ::= ID LP distinct exprlist RP",
106712  /* 198 */ "expr ::= ID LP STAR RP",
106713  /* 199 */ "term ::= CTIME_KW",
106714  /* 200 */ "expr ::= expr AND expr",
106715  /* 201 */ "expr ::= expr OR expr",
106716  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
106717  /* 203 */ "expr ::= expr EQ|NE expr",
106718  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
106719  /* 205 */ "expr ::= expr PLUS|MINUS expr",
106720  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
106721  /* 207 */ "expr ::= expr CONCAT expr",
106722  /* 208 */ "likeop ::= LIKE_KW",
106723  /* 209 */ "likeop ::= NOT LIKE_KW",
106724  /* 210 */ "likeop ::= MATCH",
106725  /* 211 */ "likeop ::= NOT MATCH",
106726  /* 212 */ "expr ::= expr likeop expr",
106727  /* 213 */ "expr ::= expr likeop expr ESCAPE expr",
106728  /* 214 */ "expr ::= expr ISNULL|NOTNULL",
106729  /* 215 */ "expr ::= expr NOT NULL",
106730  /* 216 */ "expr ::= expr IS expr",
106731  /* 217 */ "expr ::= expr IS NOT expr",
106732  /* 218 */ "expr ::= NOT expr",
106733  /* 219 */ "expr ::= BITNOT expr",
106734  /* 220 */ "expr ::= MINUS expr",
106735  /* 221 */ "expr ::= PLUS expr",
106736  /* 222 */ "between_op ::= BETWEEN",
106737  /* 223 */ "between_op ::= NOT BETWEEN",
106738  /* 224 */ "expr ::= expr between_op expr AND expr",
106739  /* 225 */ "in_op ::= IN",
106740  /* 226 */ "in_op ::= NOT IN",
106741  /* 227 */ "expr ::= expr in_op LP exprlist RP",
106742  /* 228 */ "expr ::= LP select RP",
106743  /* 229 */ "expr ::= expr in_op LP select RP",
106744  /* 230 */ "expr ::= expr in_op nm dbnm",
106745  /* 231 */ "expr ::= EXISTS LP select RP",
106746  /* 232 */ "expr ::= CASE case_operand case_exprlist case_else END",
106747  /* 233 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
106748  /* 234 */ "case_exprlist ::= WHEN expr THEN expr",
106749  /* 235 */ "case_else ::= ELSE expr",
106750  /* 236 */ "case_else ::=",
106751  /* 237 */ "case_operand ::= expr",
106752  /* 238 */ "case_operand ::=",
106753  /* 239 */ "exprlist ::= nexprlist",
106754  /* 240 */ "exprlist ::=",
106755  /* 241 */ "nexprlist ::= nexprlist COMMA expr",
106756  /* 242 */ "nexprlist ::= expr",
106757  /* 243 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
106758  /* 244 */ "uniqueflag ::= UNIQUE",
106759  /* 245 */ "uniqueflag ::=",
106760  /* 246 */ "idxlist_opt ::=",
106761  /* 247 */ "idxlist_opt ::= LP idxlist RP",
106762  /* 248 */ "idxlist ::= idxlist COMMA nm collate sortorder",
106763  /* 249 */ "idxlist ::= nm collate sortorder",
106764  /* 250 */ "collate ::=",
106765  /* 251 */ "collate ::= COLLATE ids",
106766  /* 252 */ "cmd ::= DROP INDEX ifexists fullname",
106767  /* 253 */ "cmd ::= VACUUM",
106768  /* 254 */ "cmd ::= VACUUM nm",
106769  /* 255 */ "cmd ::= PRAGMA nm dbnm",
106770  /* 256 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
106771  /* 257 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
106772  /* 258 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
106773  /* 259 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
106774  /* 260 */ "nmnum ::= plus_num",
106775  /* 261 */ "nmnum ::= nm",
106776  /* 262 */ "nmnum ::= ON",
106777  /* 263 */ "nmnum ::= DELETE",
106778  /* 264 */ "nmnum ::= DEFAULT",
106779  /* 265 */ "plus_num ::= plus_opt number",
106780  /* 266 */ "minus_num ::= MINUS number",
106781  /* 267 */ "number ::= INTEGER|FLOAT",
106782  /* 268 */ "plus_opt ::= PLUS",
106783  /* 269 */ "plus_opt ::=",
106784  /* 270 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
106785  /* 271 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
106786  /* 272 */ "trigger_time ::= BEFORE",
106787  /* 273 */ "trigger_time ::= AFTER",
106788  /* 274 */ "trigger_time ::= INSTEAD OF",
106789  /* 275 */ "trigger_time ::=",
106790  /* 276 */ "trigger_event ::= DELETE|INSERT",
106791  /* 277 */ "trigger_event ::= UPDATE",
106792  /* 278 */ "trigger_event ::= UPDATE OF inscollist",
106793  /* 279 */ "foreach_clause ::=",
106794  /* 280 */ "foreach_clause ::= FOR EACH ROW",
106795  /* 281 */ "when_clause ::=",
106796  /* 282 */ "when_clause ::= WHEN expr",
106797  /* 283 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
106798  /* 284 */ "trigger_cmd_list ::= trigger_cmd SEMI",
106799  /* 285 */ "trnm ::= nm",
106800  /* 286 */ "trnm ::= nm DOT nm",
106801  /* 287 */ "tridxby ::=",
106802  /* 288 */ "tridxby ::= INDEXED BY nm",
106803  /* 289 */ "tridxby ::= NOT INDEXED",
106804  /* 290 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
106805  /* 291 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
106806  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
106807  /* 293 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
106808  /* 294 */ "trigger_cmd ::= select",
106809  /* 295 */ "expr ::= RAISE LP IGNORE RP",
106810  /* 296 */ "expr ::= RAISE LP raisetype COMMA nm RP",
106811  /* 297 */ "raisetype ::= ROLLBACK",
106812  /* 298 */ "raisetype ::= ABORT",
106813  /* 299 */ "raisetype ::= FAIL",
106814  /* 300 */ "cmd ::= DROP TRIGGER ifexists fullname",
106815  /* 301 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
106816  /* 302 */ "cmd ::= DETACH database_kw_opt expr",
106817  /* 303 */ "key_opt ::=",
106818  /* 304 */ "key_opt ::= KEY expr",
106819  /* 305 */ "database_kw_opt ::= DATABASE",
106820  /* 306 */ "database_kw_opt ::=",
106821  /* 307 */ "cmd ::= REINDEX",
106822  /* 308 */ "cmd ::= REINDEX nm dbnm",
106823  /* 309 */ "cmd ::= ANALYZE",
106824  /* 310 */ "cmd ::= ANALYZE nm dbnm",
106825  /* 311 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
106826  /* 312 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
106827  /* 313 */ "add_column_fullname ::= fullname",
106828  /* 314 */ "kwcolumn_opt ::=",
106829  /* 315 */ "kwcolumn_opt ::= COLUMNKW",
106830  /* 316 */ "cmd ::= create_vtab",
106831  /* 317 */ "cmd ::= create_vtab LP vtabarglist RP",
106832  /* 318 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
106833  /* 319 */ "vtabarglist ::= vtabarg",
106834  /* 320 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
106835  /* 321 */ "vtabarg ::=",
106836  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
106837  /* 323 */ "vtabargtoken ::= ANY",
106838  /* 324 */ "vtabargtoken ::= lp anylist RP",
106839  /* 325 */ "lp ::= LP",
106840  /* 326 */ "anylist ::=",
106841  /* 327 */ "anylist ::= anylist LP anylist RP",
106842  /* 328 */ "anylist ::= anylist ANY",
106843 };
106844 #endif /* NDEBUG */
106845 
106846 
106847 #if YYSTACKDEPTH<=0
106848 /*
106849 ** Try to increase the size of the parser stack.
106850 */
106851 static void yyGrowStack(yyParser *p){
106852   int newSize;
106853   yyStackEntry *pNew;
106854 
106855   newSize = p->yystksz*2 + 100;
106856   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
106857   if( pNew ){
106858     p->yystack = pNew;
106859     p->yystksz = newSize;
106860 #ifndef NDEBUG
106861     if( yyTraceFILE ){
106862       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
106863               yyTracePrompt, p->yystksz);
106864     }
106865 #endif
106866   }
106867 }
106868 #endif
106869 
106870 /*
106871 ** This function allocates a new parser.
106872 ** The only argument is a pointer to a function which works like
106873 ** malloc.
106874 **
106875 ** Inputs:
106876 ** A pointer to the function used to allocate memory.
106877 **
106878 ** Outputs:
106879 ** A pointer to a parser.  This pointer is used in subsequent calls
106880 ** to sqlite3Parser and sqlite3ParserFree.
106881 */
106882 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
106883   yyParser *pParser;
106884   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
106885   if( pParser ){
106886     pParser->yyidx = -1;
106887 #ifdef YYTRACKMAXSTACKDEPTH
106888     pParser->yyidxMax = 0;
106889 #endif
106890 #if YYSTACKDEPTH<=0
106891     pParser->yystack = NULL;
106892     pParser->yystksz = 0;
106893     yyGrowStack(pParser);
106894 #endif
106895   }
106896   return pParser;
106897 }
106898 
106899 /* The following function deletes the value associated with a
106900 ** symbol.  The symbol can be either a terminal or nonterminal.
106901 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
106902 ** the value.
106903 */
106904 static void yy_destructor(
106905   yyParser *yypParser,    /* The parser */
106906   YYCODETYPE yymajor,     /* Type code for object to destroy */
106907   YYMINORTYPE *yypminor   /* The object to be destroyed */
106908 ){
106909   sqlite3ParserARG_FETCH;
106910   switch( yymajor ){
106911     /* Here is inserted the actions which take place when a
106912     ** terminal or non-terminal is destroyed.  This can happen
106913     ** when the symbol is popped from the stack during a
106914     ** reduce or during error processing or when a parser is
106915     ** being destroyed before it is finished parsing.
106916     **
106917     ** Note: during a reduce, the only symbols destroyed are those
106918     ** which appear on the RHS of the rule, but which are not used
106919     ** inside the C code.
106920     */
106921     case 160: /* select */
106922     case 194: /* oneselect */
106923 {
106924 sqlite3SelectDelete(pParse->db, (yypminor->yy387));
106925 }
106926       break;
106927     case 174: /* term */
106928     case 175: /* expr */
106929 {
106930 sqlite3ExprDelete(pParse->db, (yypminor->yy118).pExpr);
106931 }
106932       break;
106933     case 179: /* idxlist_opt */
106934     case 187: /* idxlist */
106935     case 197: /* selcollist */
106936     case 200: /* groupby_opt */
106937     case 202: /* orderby_opt */
106938     case 204: /* sclp */
106939     case 214: /* sortlist */
106940     case 216: /* nexprlist */
106941     case 217: /* setlist */
106942     case 220: /* itemlist */
106943     case 221: /* exprlist */
106944     case 226: /* case_exprlist */
106945 {
106946 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
106947 }
106948       break;
106949     case 193: /* fullname */
106950     case 198: /* from */
106951     case 206: /* seltablist */
106952     case 207: /* stl_prefix */
106953 {
106954 sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
106955 }
106956       break;
106957     case 199: /* where_opt */
106958     case 201: /* having_opt */
106959     case 210: /* on_opt */
106960     case 215: /* sortitem */
106961     case 225: /* case_operand */
106962     case 227: /* case_else */
106963     case 238: /* when_clause */
106964     case 243: /* key_opt */
106965 {
106966 sqlite3ExprDelete(pParse->db, (yypminor->yy314));
106967 }
106968       break;
106969     case 211: /* using_opt */
106970     case 213: /* inscollist */
106971     case 219: /* inscollist_opt */
106972 {
106973 sqlite3IdListDelete(pParse->db, (yypminor->yy384));
106974 }
106975       break;
106976     case 234: /* trigger_cmd_list */
106977     case 239: /* trigger_cmd */
106978 {
106979 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
106980 }
106981       break;
106982     case 236: /* trigger_event */
106983 {
106984 sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
106985 }
106986       break;
106987     default:  break;   /* If no destructor action specified: do nothing */
106988   }
106989 }
106990 
106991 /*
106992 ** Pop the parser's stack once.
106993 **
106994 ** If there is a destructor routine associated with the token which
106995 ** is popped from the stack, then call it.
106996 **
106997 ** Return the major token number for the symbol popped.
106998 */
106999 static int yy_pop_parser_stack(yyParser *pParser){
107000   YYCODETYPE yymajor;
107001   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
107002 
107003   /* There is no mechanism by which the parser stack can be popped below
107004   ** empty in SQLite.  */
107005   if( NEVER(pParser->yyidx<0) ) return 0;
107006 #ifndef NDEBUG
107007   if( yyTraceFILE && pParser->yyidx>=0 ){
107008     fprintf(yyTraceFILE,"%sPopping %s\n",
107009       yyTracePrompt,
107010       yyTokenName[yytos->major]);
107011   }
107012 #endif
107013   yymajor = yytos->major;
107014   yy_destructor(pParser, yymajor, &yytos->minor);
107015   pParser->yyidx--;
107016   return yymajor;
107017 }
107018 
107019 /*
107020 ** Deallocate and destroy a parser.  Destructors are all called for
107021 ** all stack elements before shutting the parser down.
107022 **
107023 ** Inputs:
107024 ** <ul>
107025 ** <li>  A pointer to the parser.  This should be a pointer
107026 **       obtained from sqlite3ParserAlloc.
107027 ** <li>  A pointer to a function used to reclaim memory obtained
107028 **       from malloc.
107029 ** </ul>
107030 */
107031 SQLITE_PRIVATE void sqlite3ParserFree(
107032   void *p,                    /* The parser to be deleted */
107033   void (*freeProc)(void*)     /* Function used to reclaim memory */
107034 ){
107035   yyParser *pParser = (yyParser*)p;
107036   /* In SQLite, we never try to destroy a parser that was not successfully
107037   ** created in the first place. */
107038   if( NEVER(pParser==0) ) return;
107039   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
107040 #if YYSTACKDEPTH<=0
107041   free(pParser->yystack);
107042 #endif
107043   (*freeProc)((void*)pParser);
107044 }
107045 
107046 /*
107047 ** Return the peak depth of the stack for a parser.
107048 */
107049 #ifdef YYTRACKMAXSTACKDEPTH
107050 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
107051   yyParser *pParser = (yyParser*)p;
107052   return pParser->yyidxMax;
107053 }
107054 #endif
107055 
107056 /*
107057 ** Find the appropriate action for a parser given the terminal
107058 ** look-ahead token iLookAhead.
107059 **
107060 ** If the look-ahead token is YYNOCODE, then check to see if the action is
107061 ** independent of the look-ahead.  If it is, return the action, otherwise
107062 ** return YY_NO_ACTION.
107063 */
107064 static int yy_find_shift_action(
107065   yyParser *pParser,        /* The parser */
107066   YYCODETYPE iLookAhead     /* The look-ahead token */
107067 ){
107068   int i;
107069   int stateno = pParser->yystack[pParser->yyidx].stateno;
107070 
107071   if( stateno>YY_SHIFT_COUNT
107072    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
107073     return yy_default[stateno];
107074   }
107075   assert( iLookAhead!=YYNOCODE );
107076   i += iLookAhead;
107077   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
107078     if( iLookAhead>0 ){
107079 #ifdef YYFALLBACK
107080       YYCODETYPE iFallback;            /* Fallback token */
107081       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
107082              && (iFallback = yyFallback[iLookAhead])!=0 ){
107083 #ifndef NDEBUG
107084         if( yyTraceFILE ){
107085           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
107086              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
107087         }
107088 #endif
107089         return yy_find_shift_action(pParser, iFallback);
107090       }
107091 #endif
107092 #ifdef YYWILDCARD
107093       {
107094         int j = i - iLookAhead + YYWILDCARD;
107095         if(
107096 #if YY_SHIFT_MIN+YYWILDCARD<0
107097           j>=0 &&
107098 #endif
107099 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
107100           j<YY_ACTTAB_COUNT &&
107101 #endif
107102           yy_lookahead[j]==YYWILDCARD
107103         ){
107104 #ifndef NDEBUG
107105           if( yyTraceFILE ){
107106             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
107107                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
107108           }
107109 #endif /* NDEBUG */
107110           return yy_action[j];
107111         }
107112       }
107113 #endif /* YYWILDCARD */
107114     }
107115     return yy_default[stateno];
107116   }else{
107117     return yy_action[i];
107118   }
107119 }
107120 
107121 /*
107122 ** Find the appropriate action for a parser given the non-terminal
107123 ** look-ahead token iLookAhead.
107124 **
107125 ** If the look-ahead token is YYNOCODE, then check to see if the action is
107126 ** independent of the look-ahead.  If it is, return the action, otherwise
107127 ** return YY_NO_ACTION.
107128 */
107129 static int yy_find_reduce_action(
107130   int stateno,              /* Current state number */
107131   YYCODETYPE iLookAhead     /* The look-ahead token */
107132 ){
107133   int i;
107134 #ifdef YYERRORSYMBOL
107135   if( stateno>YY_REDUCE_COUNT ){
107136     return yy_default[stateno];
107137   }
107138 #else
107139   assert( stateno<=YY_REDUCE_COUNT );
107140 #endif
107141   i = yy_reduce_ofst[stateno];
107142   assert( i!=YY_REDUCE_USE_DFLT );
107143   assert( iLookAhead!=YYNOCODE );
107144   i += iLookAhead;
107145 #ifdef YYERRORSYMBOL
107146   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
107147     return yy_default[stateno];
107148   }
107149 #else
107150   assert( i>=0 && i<YY_ACTTAB_COUNT );
107151   assert( yy_lookahead[i]==iLookAhead );
107152 #endif
107153   return yy_action[i];
107154 }
107155 
107156 /*
107157 ** The following routine is called if the stack overflows.
107158 */
107159 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
107160    sqlite3ParserARG_FETCH;
107161    yypParser->yyidx--;
107162 #ifndef NDEBUG
107163    if( yyTraceFILE ){
107164      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
107165    }
107166 #endif
107167    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
107168    /* Here code is inserted which will execute if the parser
107169    ** stack every overflows */
107170 
107171   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
107172   sqlite3ErrorMsg(pParse, "parser stack overflow");
107173   pParse->parseError = 1;
107174    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
107175 }
107176 
107177 /*
107178 ** Perform a shift action.
107179 */
107180 static void yy_shift(
107181   yyParser *yypParser,          /* The parser to be shifted */
107182   int yyNewState,               /* The new state to shift in */
107183   int yyMajor,                  /* The major token to shift in */
107184   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
107185 ){
107186   yyStackEntry *yytos;
107187   yypParser->yyidx++;
107188 #ifdef YYTRACKMAXSTACKDEPTH
107189   if( yypParser->yyidx>yypParser->yyidxMax ){
107190     yypParser->yyidxMax = yypParser->yyidx;
107191   }
107192 #endif
107193 #if YYSTACKDEPTH>0
107194   if( yypParser->yyidx>=YYSTACKDEPTH ){
107195     yyStackOverflow(yypParser, yypMinor);
107196     return;
107197   }
107198 #else
107199   if( yypParser->yyidx>=yypParser->yystksz ){
107200     yyGrowStack(yypParser);
107201     if( yypParser->yyidx>=yypParser->yystksz ){
107202       yyStackOverflow(yypParser, yypMinor);
107203       return;
107204     }
107205   }
107206 #endif
107207   yytos = &yypParser->yystack[yypParser->yyidx];
107208   yytos->stateno = (YYACTIONTYPE)yyNewState;
107209   yytos->major = (YYCODETYPE)yyMajor;
107210   yytos->minor = *yypMinor;
107211 #ifndef NDEBUG
107212   if( yyTraceFILE && yypParser->yyidx>0 ){
107213     int i;
107214     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
107215     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
107216     for(i=1; i<=yypParser->yyidx; i++)
107217       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
107218     fprintf(yyTraceFILE,"\n");
107219   }
107220 #endif
107221 }
107222 
107223 /* The following table contains information about every rule that
107224 ** is used during the reduce.
107225 */
107226 static const struct {
107227   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
107228   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
107229 } yyRuleInfo[] = {
107230   { 142, 1 },
107231   { 143, 2 },
107232   { 143, 1 },
107233   { 144, 1 },
107234   { 144, 3 },
107235   { 145, 0 },
107236   { 145, 1 },
107237   { 145, 3 },
107238   { 146, 1 },
107239   { 147, 3 },
107240   { 149, 0 },
107241   { 149, 1 },
107242   { 149, 2 },
107243   { 148, 0 },
107244   { 148, 1 },
107245   { 148, 1 },
107246   { 148, 1 },
107247   { 147, 2 },
107248   { 147, 2 },
107249   { 147, 2 },
107250   { 151, 1 },
107251   { 151, 0 },
107252   { 147, 2 },
107253   { 147, 3 },
107254   { 147, 5 },
107255   { 147, 2 },
107256   { 152, 6 },
107257   { 154, 1 },
107258   { 156, 0 },
107259   { 156, 3 },
107260   { 155, 1 },
107261   { 155, 0 },
107262   { 153, 4 },
107263   { 153, 2 },
107264   { 158, 3 },
107265   { 158, 1 },
107266   { 161, 3 },
107267   { 162, 1 },
107268   { 165, 1 },
107269   { 165, 1 },
107270   { 166, 1 },
107271   { 150, 1 },
107272   { 150, 1 },
107273   { 150, 1 },
107274   { 163, 0 },
107275   { 163, 1 },
107276   { 167, 1 },
107277   { 167, 4 },
107278   { 167, 6 },
107279   { 168, 1 },
107280   { 168, 2 },
107281   { 169, 1 },
107282   { 169, 1 },
107283   { 164, 2 },
107284   { 164, 0 },
107285   { 172, 3 },
107286   { 172, 1 },
107287   { 173, 2 },
107288   { 173, 4 },
107289   { 173, 3 },
107290   { 173, 3 },
107291   { 173, 2 },
107292   { 173, 2 },
107293   { 173, 3 },
107294   { 173, 5 },
107295   { 173, 2 },
107296   { 173, 4 },
107297   { 173, 4 },
107298   { 173, 1 },
107299   { 173, 2 },
107300   { 178, 0 },
107301   { 178, 1 },
107302   { 180, 0 },
107303   { 180, 2 },
107304   { 182, 2 },
107305   { 182, 3 },
107306   { 182, 3 },
107307   { 182, 3 },
107308   { 183, 2 },
107309   { 183, 2 },
107310   { 183, 1 },
107311   { 183, 1 },
107312   { 183, 2 },
107313   { 181, 3 },
107314   { 181, 2 },
107315   { 184, 0 },
107316   { 184, 2 },
107317   { 184, 2 },
107318   { 159, 0 },
107319   { 159, 2 },
107320   { 185, 3 },
107321   { 185, 2 },
107322   { 185, 1 },
107323   { 186, 2 },
107324   { 186, 7 },
107325   { 186, 5 },
107326   { 186, 5 },
107327   { 186, 10 },
107328   { 188, 0 },
107329   { 188, 1 },
107330   { 176, 0 },
107331   { 176, 3 },
107332   { 189, 0 },
107333   { 189, 2 },
107334   { 190, 1 },
107335   { 190, 1 },
107336   { 190, 1 },
107337   { 147, 4 },
107338   { 192, 2 },
107339   { 192, 0 },
107340   { 147, 8 },
107341   { 147, 4 },
107342   { 147, 1 },
107343   { 160, 1 },
107344   { 160, 3 },
107345   { 195, 1 },
107346   { 195, 2 },
107347   { 195, 1 },
107348   { 194, 9 },
107349   { 196, 1 },
107350   { 196, 1 },
107351   { 196, 0 },
107352   { 204, 2 },
107353   { 204, 0 },
107354   { 197, 3 },
107355   { 197, 2 },
107356   { 197, 4 },
107357   { 205, 2 },
107358   { 205, 1 },
107359   { 205, 0 },
107360   { 198, 0 },
107361   { 198, 2 },
107362   { 207, 2 },
107363   { 207, 0 },
107364   { 206, 7 },
107365   { 206, 7 },
107366   { 206, 7 },
107367   { 157, 0 },
107368   { 157, 2 },
107369   { 193, 2 },
107370   { 208, 1 },
107371   { 208, 2 },
107372   { 208, 3 },
107373   { 208, 4 },
107374   { 210, 2 },
107375   { 210, 0 },
107376   { 209, 0 },
107377   { 209, 3 },
107378   { 209, 2 },
107379   { 211, 4 },
107380   { 211, 0 },
107381   { 202, 0 },
107382   { 202, 3 },
107383   { 214, 4 },
107384   { 214, 2 },
107385   { 215, 1 },
107386   { 177, 1 },
107387   { 177, 1 },
107388   { 177, 0 },
107389   { 200, 0 },
107390   { 200, 3 },
107391   { 201, 0 },
107392   { 201, 2 },
107393   { 203, 0 },
107394   { 203, 2 },
107395   { 203, 4 },
107396   { 203, 4 },
107397   { 147, 5 },
107398   { 199, 0 },
107399   { 199, 2 },
107400   { 147, 7 },
107401   { 217, 5 },
107402   { 217, 3 },
107403   { 147, 8 },
107404   { 147, 5 },
107405   { 147, 6 },
107406   { 218, 2 },
107407   { 218, 1 },
107408   { 220, 3 },
107409   { 220, 1 },
107410   { 219, 0 },
107411   { 219, 3 },
107412   { 213, 3 },
107413   { 213, 1 },
107414   { 175, 1 },
107415   { 175, 3 },
107416   { 174, 1 },
107417   { 175, 1 },
107418   { 175, 1 },
107419   { 175, 3 },
107420   { 175, 5 },
107421   { 174, 1 },
107422   { 174, 1 },
107423   { 175, 1 },
107424   { 175, 1 },
107425   { 175, 3 },
107426   { 175, 6 },
107427   { 175, 5 },
107428   { 175, 4 },
107429   { 174, 1 },
107430   { 175, 3 },
107431   { 175, 3 },
107432   { 175, 3 },
107433   { 175, 3 },
107434   { 175, 3 },
107435   { 175, 3 },
107436   { 175, 3 },
107437   { 175, 3 },
107438   { 222, 1 },
107439   { 222, 2 },
107440   { 222, 1 },
107441   { 222, 2 },
107442   { 175, 3 },
107443   { 175, 5 },
107444   { 175, 2 },
107445   { 175, 3 },
107446   { 175, 3 },
107447   { 175, 4 },
107448   { 175, 2 },
107449   { 175, 2 },
107450   { 175, 2 },
107451   { 175, 2 },
107452   { 223, 1 },
107453   { 223, 2 },
107454   { 175, 5 },
107455   { 224, 1 },
107456   { 224, 2 },
107457   { 175, 5 },
107458   { 175, 3 },
107459   { 175, 5 },
107460   { 175, 4 },
107461   { 175, 4 },
107462   { 175, 5 },
107463   { 226, 5 },
107464   { 226, 4 },
107465   { 227, 2 },
107466   { 227, 0 },
107467   { 225, 1 },
107468   { 225, 0 },
107469   { 221, 1 },
107470   { 221, 0 },
107471   { 216, 3 },
107472   { 216, 1 },
107473   { 147, 11 },
107474   { 228, 1 },
107475   { 228, 0 },
107476   { 179, 0 },
107477   { 179, 3 },
107478   { 187, 5 },
107479   { 187, 3 },
107480   { 229, 0 },
107481   { 229, 2 },
107482   { 147, 4 },
107483   { 147, 1 },
107484   { 147, 2 },
107485   { 147, 3 },
107486   { 147, 5 },
107487   { 147, 6 },
107488   { 147, 5 },
107489   { 147, 6 },
107490   { 230, 1 },
107491   { 230, 1 },
107492   { 230, 1 },
107493   { 230, 1 },
107494   { 230, 1 },
107495   { 170, 2 },
107496   { 171, 2 },
107497   { 232, 1 },
107498   { 231, 1 },
107499   { 231, 0 },
107500   { 147, 5 },
107501   { 233, 11 },
107502   { 235, 1 },
107503   { 235, 1 },
107504   { 235, 2 },
107505   { 235, 0 },
107506   { 236, 1 },
107507   { 236, 1 },
107508   { 236, 3 },
107509   { 237, 0 },
107510   { 237, 3 },
107511   { 238, 0 },
107512   { 238, 2 },
107513   { 234, 3 },
107514   { 234, 2 },
107515   { 240, 1 },
107516   { 240, 3 },
107517   { 241, 0 },
107518   { 241, 3 },
107519   { 241, 2 },
107520   { 239, 7 },
107521   { 239, 8 },
107522   { 239, 5 },
107523   { 239, 5 },
107524   { 239, 1 },
107525   { 175, 4 },
107526   { 175, 6 },
107527   { 191, 1 },
107528   { 191, 1 },
107529   { 191, 1 },
107530   { 147, 4 },
107531   { 147, 6 },
107532   { 147, 3 },
107533   { 243, 0 },
107534   { 243, 2 },
107535   { 242, 1 },
107536   { 242, 0 },
107537   { 147, 1 },
107538   { 147, 3 },
107539   { 147, 1 },
107540   { 147, 3 },
107541   { 147, 6 },
107542   { 147, 6 },
107543   { 244, 1 },
107544   { 245, 0 },
107545   { 245, 1 },
107546   { 147, 1 },
107547   { 147, 4 },
107548   { 246, 7 },
107549   { 247, 1 },
107550   { 247, 3 },
107551   { 248, 0 },
107552   { 248, 2 },
107553   { 249, 1 },
107554   { 249, 3 },
107555   { 250, 1 },
107556   { 251, 0 },
107557   { 251, 4 },
107558   { 251, 2 },
107559 };
107560 
107561 static void yy_accept(yyParser*);  /* Forward Declaration */
107562 
107563 /*
107564 ** Perform a reduce action and the shift that must immediately
107565 ** follow the reduce.
107566 */
107567 static void yy_reduce(
107568   yyParser *yypParser,         /* The parser */
107569   int yyruleno                 /* Number of the rule by which to reduce */
107570 ){
107571   int yygoto;                     /* The next state */
107572   int yyact;                      /* The next action */
107573   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
107574   yyStackEntry *yymsp;            /* The top of the parser's stack */
107575   int yysize;                     /* Amount to pop the stack */
107576   sqlite3ParserARG_FETCH;
107577   yymsp = &yypParser->yystack[yypParser->yyidx];
107578 #ifndef NDEBUG
107579   if( yyTraceFILE && yyruleno>=0
107580         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
107581     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
107582       yyRuleName[yyruleno]);
107583   }
107584 #endif /* NDEBUG */
107585 
107586   /* Silence complaints from purify about yygotominor being uninitialized
107587   ** in some cases when it is copied into the stack after the following
107588   ** switch.  yygotominor is uninitialized when a rule reduces that does
107589   ** not set the value of its left-hand side nonterminal.  Leaving the
107590   ** value of the nonterminal uninitialized is utterly harmless as long
107591   ** as the value is never used.  So really the only thing this code
107592   ** accomplishes is to quieten purify.
107593   **
107594   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
107595   ** without this code, their parser segfaults.  I'm not sure what there
107596   ** parser is doing to make this happen.  This is the second bug report
107597   ** from wireshark this week.  Clearly they are stressing Lemon in ways
107598   ** that it has not been previously stressed...  (SQLite ticket #2172)
107599   */
107600   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
107601   yygotominor = yyzerominor;
107602 
107603 
107604   switch( yyruleno ){
107605   /* Beginning here are the reduction cases.  A typical example
107606   ** follows:
107607   **   case 0:
107608   **  #line <lineno> <grammarfile>
107609   **     { ... }           // User supplied code
107610   **  #line <lineno> <thisfile>
107611   **     break;
107612   */
107613       case 5: /* explain ::= */
107614 { sqlite3BeginParse(pParse, 0); }
107615         break;
107616       case 6: /* explain ::= EXPLAIN */
107617 { sqlite3BeginParse(pParse, 1); }
107618         break;
107619       case 7: /* explain ::= EXPLAIN QUERY PLAN */
107620 { sqlite3BeginParse(pParse, 2); }
107621         break;
107622       case 8: /* cmdx ::= cmd */
107623 { sqlite3FinishCoding(pParse); }
107624         break;
107625       case 9: /* cmd ::= BEGIN transtype trans_opt */
107626 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
107627         break;
107628       case 13: /* transtype ::= */
107629 {yygotominor.yy4 = TK_DEFERRED;}
107630         break;
107631       case 14: /* transtype ::= DEFERRED */
107632       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
107633       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
107634       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
107635       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
107636 {yygotominor.yy4 = yymsp[0].major;}
107637         break;
107638       case 17: /* cmd ::= COMMIT trans_opt */
107639       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
107640 {sqlite3CommitTransaction(pParse);}
107641         break;
107642       case 19: /* cmd ::= ROLLBACK trans_opt */
107643 {sqlite3RollbackTransaction(pParse);}
107644         break;
107645       case 22: /* cmd ::= SAVEPOINT nm */
107646 {
107647   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
107648 }
107649         break;
107650       case 23: /* cmd ::= RELEASE savepoint_opt nm */
107651 {
107652   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
107653 }
107654         break;
107655       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
107656 {
107657   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
107658 }
107659         break;
107660       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
107661 {
107662    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
107663 }
107664         break;
107665       case 27: /* createkw ::= CREATE */
107666 {
107667   pParse->db->lookaside.bEnabled = 0;
107668   yygotominor.yy0 = yymsp[0].minor.yy0;
107669 }
107670         break;
107671       case 28: /* ifnotexists ::= */
107672       case 31: /* temp ::= */ yytestcase(yyruleno==31);
107673       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
107674       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
107675       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
107676       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
107677       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
107678       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
107679       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
107680       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
107681       case 222: /* between_op ::= BETWEEN */ yytestcase(yyruleno==222);
107682       case 225: /* in_op ::= IN */ yytestcase(yyruleno==225);
107683 {yygotominor.yy4 = 0;}
107684         break;
107685       case 29: /* ifnotexists ::= IF NOT EXISTS */
107686       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
107687       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
107688       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
107689       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
107690       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
107691       case 223: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==223);
107692       case 226: /* in_op ::= NOT IN */ yytestcase(yyruleno==226);
107693 {yygotominor.yy4 = 1;}
107694         break;
107695       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
107696 {
107697   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
107698 }
107699         break;
107700       case 33: /* create_table_args ::= AS select */
107701 {
107702   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
107703   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
107704 }
107705         break;
107706       case 36: /* column ::= columnid type carglist */
107707 {
107708   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
107709   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
107710 }
107711         break;
107712       case 37: /* columnid ::= nm */
107713 {
107714   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
107715   yygotominor.yy0 = yymsp[0].minor.yy0;
107716 }
107717         break;
107718       case 38: /* id ::= ID */
107719       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
107720       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
107721       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
107722       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
107723       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
107724       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
107725       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
107726       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
107727       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
107728       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
107729       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
107730       case 251: /* collate ::= COLLATE ids */ yytestcase(yyruleno==251);
107731       case 260: /* nmnum ::= plus_num */ yytestcase(yyruleno==260);
107732       case 261: /* nmnum ::= nm */ yytestcase(yyruleno==261);
107733       case 262: /* nmnum ::= ON */ yytestcase(yyruleno==262);
107734       case 263: /* nmnum ::= DELETE */ yytestcase(yyruleno==263);
107735       case 264: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==264);
107736       case 265: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==265);
107737       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
107738       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
107739       case 285: /* trnm ::= nm */ yytestcase(yyruleno==285);
107740 {yygotominor.yy0 = yymsp[0].minor.yy0;}
107741         break;
107742       case 45: /* type ::= typetoken */
107743 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
107744         break;
107745       case 47: /* typetoken ::= typename LP signed RP */
107746 {
107747   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
107748   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
107749 }
107750         break;
107751       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
107752 {
107753   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
107754   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
107755 }
107756         break;
107757       case 50: /* typename ::= typename ids */
107758 {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);}
107759         break;
107760       case 57: /* ccons ::= DEFAULT term */
107761       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
107762 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy118);}
107763         break;
107764       case 58: /* ccons ::= DEFAULT LP expr RP */
107765 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy118);}
107766         break;
107767       case 60: /* ccons ::= DEFAULT MINUS term */
107768 {
107769   ExprSpan v;
107770   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy118.pExpr, 0, 0);
107771   v.zStart = yymsp[-1].minor.yy0.z;
107772   v.zEnd = yymsp[0].minor.yy118.zEnd;
107773   sqlite3AddDefaultValue(pParse,&v);
107774 }
107775         break;
107776       case 61: /* ccons ::= DEFAULT id */
107777 {
107778   ExprSpan v;
107779   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
107780   sqlite3AddDefaultValue(pParse,&v);
107781 }
107782         break;
107783       case 63: /* ccons ::= NOT NULL onconf */
107784 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
107785         break;
107786       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
107787 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
107788         break;
107789       case 65: /* ccons ::= UNIQUE onconf */
107790 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0);}
107791         break;
107792       case 66: /* ccons ::= CHECK LP expr RP */
107793 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy118.pExpr);}
107794         break;
107795       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
107796 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
107797         break;
107798       case 68: /* ccons ::= defer_subclause */
107799 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
107800         break;
107801       case 69: /* ccons ::= COLLATE ids */
107802 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
107803         break;
107804       case 72: /* refargs ::= */
107805 { yygotominor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
107806         break;
107807       case 73: /* refargs ::= refargs refarg */
107808 { yygotominor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
107809         break;
107810       case 74: /* refarg ::= MATCH nm */
107811       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
107812 { yygotominor.yy215.value = 0;     yygotominor.yy215.mask = 0x000000; }
107813         break;
107814       case 76: /* refarg ::= ON DELETE refact */
107815 { yygotominor.yy215.value = yymsp[0].minor.yy4;     yygotominor.yy215.mask = 0x0000ff; }
107816         break;
107817       case 77: /* refarg ::= ON UPDATE refact */
107818 { yygotominor.yy215.value = yymsp[0].minor.yy4<<8;  yygotominor.yy215.mask = 0x00ff00; }
107819         break;
107820       case 78: /* refact ::= SET NULL */
107821 { yygotominor.yy4 = OE_SetNull;  /* EV: R-33326-45252 */}
107822         break;
107823       case 79: /* refact ::= SET DEFAULT */
107824 { yygotominor.yy4 = OE_SetDflt;  /* EV: R-33326-45252 */}
107825         break;
107826       case 80: /* refact ::= CASCADE */
107827 { yygotominor.yy4 = OE_Cascade;  /* EV: R-33326-45252 */}
107828         break;
107829       case 81: /* refact ::= RESTRICT */
107830 { yygotominor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
107831         break;
107832       case 82: /* refact ::= NO ACTION */
107833 { yygotominor.yy4 = OE_None;     /* EV: R-33326-45252 */}
107834         break;
107835       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
107836       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
107837       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
107838       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
107839 {yygotominor.yy4 = yymsp[0].minor.yy4;}
107840         break;
107841       case 88: /* conslist_opt ::= */
107842 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
107843         break;
107844       case 89: /* conslist_opt ::= COMMA conslist */
107845 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
107846         break;
107847       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
107848 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
107849         break;
107850       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
107851 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0);}
107852         break;
107853       case 96: /* tcons ::= CHECK LP expr RP onconf */
107854 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy118.pExpr);}
107855         break;
107856       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
107857 {
107858     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
107859     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
107860 }
107861         break;
107862       case 100: /* onconf ::= */
107863 {yygotominor.yy4 = OE_Default;}
107864         break;
107865       case 102: /* orconf ::= */
107866 {yygotominor.yy210 = OE_Default;}
107867         break;
107868       case 103: /* orconf ::= OR resolvetype */
107869 {yygotominor.yy210 = (u8)yymsp[0].minor.yy4;}
107870         break;
107871       case 105: /* resolvetype ::= IGNORE */
107872 {yygotominor.yy4 = OE_Ignore;}
107873         break;
107874       case 106: /* resolvetype ::= REPLACE */
107875 {yygotominor.yy4 = OE_Replace;}
107876         break;
107877       case 107: /* cmd ::= DROP TABLE ifexists fullname */
107878 {
107879   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
107880 }
107881         break;
107882       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
107883 {
107884   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy4, yymsp[-4].minor.yy4);
107885 }
107886         break;
107887       case 111: /* cmd ::= DROP VIEW ifexists fullname */
107888 {
107889   sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
107890 }
107891         break;
107892       case 112: /* cmd ::= select */
107893 {
107894   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
107895   sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
107896   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
107897 }
107898         break;
107899       case 113: /* select ::= oneselect */
107900 {yygotominor.yy387 = yymsp[0].minor.yy387;}
107901         break;
107902       case 114: /* select ::= select multiselect_op oneselect */
107903 {
107904   if( yymsp[0].minor.yy387 ){
107905     yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy4;
107906     yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
107907   }else{
107908     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
107909   }
107910   yygotominor.yy387 = yymsp[0].minor.yy387;
107911 }
107912         break;
107913       case 116: /* multiselect_op ::= UNION ALL */
107914 {yygotominor.yy4 = TK_ALL;}
107915         break;
107916       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
107917 {
107918   yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy292.pLimit,yymsp[0].minor.yy292.pOffset);
107919 }
107920         break;
107921       case 122: /* sclp ::= selcollist COMMA */
107922       case 247: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==247);
107923 {yygotominor.yy322 = yymsp[-1].minor.yy322;}
107924         break;
107925       case 123: /* sclp ::= */
107926       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
107927       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
107928       case 240: /* exprlist ::= */ yytestcase(yyruleno==240);
107929       case 246: /* idxlist_opt ::= */ yytestcase(yyruleno==246);
107930 {yygotominor.yy322 = 0;}
107931         break;
107932       case 124: /* selcollist ::= sclp expr as */
107933 {
107934    yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, yymsp[-1].minor.yy118.pExpr);
107935    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[0].minor.yy0, 1);
107936    sqlite3ExprListSetSpan(pParse,yygotominor.yy322,&yymsp[-1].minor.yy118);
107937 }
107938         break;
107939       case 125: /* selcollist ::= sclp STAR */
107940 {
107941   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
107942   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy322, p);
107943 }
107944         break;
107945       case 126: /* selcollist ::= sclp nm DOT STAR */
107946 {
107947   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
107948   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
107949   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
107950   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, pDot);
107951 }
107952         break;
107953       case 129: /* as ::= */
107954 {yygotominor.yy0.n = 0;}
107955         break;
107956       case 130: /* from ::= */
107957 {yygotominor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy259));}
107958         break;
107959       case 131: /* from ::= FROM seltablist */
107960 {
107961   yygotominor.yy259 = yymsp[0].minor.yy259;
107962   sqlite3SrcListShiftJoinType(yygotominor.yy259);
107963 }
107964         break;
107965       case 132: /* stl_prefix ::= seltablist joinop */
107966 {
107967    yygotominor.yy259 = yymsp[-1].minor.yy259;
107968    if( ALWAYS(yygotominor.yy259 && yygotominor.yy259->nSrc>0) ) yygotominor.yy259->a[yygotominor.yy259->nSrc-1].jointype = (u8)yymsp[0].minor.yy4;
107969 }
107970         break;
107971       case 133: /* stl_prefix ::= */
107972 {yygotominor.yy259 = 0;}
107973         break;
107974       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
107975 {
107976   yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
107977   sqlite3SrcListIndexedBy(pParse, yygotominor.yy259, &yymsp[-2].minor.yy0);
107978 }
107979         break;
107980       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
107981 {
107982     yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
107983   }
107984         break;
107985       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
107986 {
107987     if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
107988       yygotominor.yy259 = yymsp[-4].minor.yy259;
107989     }else{
107990       Select *pSubquery;
107991       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
107992       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,0,0,0);
107993       yygotominor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
107994     }
107995   }
107996         break;
107997       case 137: /* dbnm ::= */
107998       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
107999 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
108000         break;
108001       case 139: /* fullname ::= nm dbnm */
108002 {yygotominor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
108003         break;
108004       case 140: /* joinop ::= COMMA|JOIN */
108005 { yygotominor.yy4 = JT_INNER; }
108006         break;
108007       case 141: /* joinop ::= JOIN_KW JOIN */
108008 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
108009         break;
108010       case 142: /* joinop ::= JOIN_KW nm JOIN */
108011 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
108012         break;
108013       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
108014 { yygotominor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
108015         break;
108016       case 144: /* on_opt ::= ON expr */
108017       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
108018       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
108019       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
108020       case 235: /* case_else ::= ELSE expr */ yytestcase(yyruleno==235);
108021       case 237: /* case_operand ::= expr */ yytestcase(yyruleno==237);
108022 {yygotominor.yy314 = yymsp[0].minor.yy118.pExpr;}
108023         break;
108024       case 145: /* on_opt ::= */
108025       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
108026       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
108027       case 236: /* case_else ::= */ yytestcase(yyruleno==236);
108028       case 238: /* case_operand ::= */ yytestcase(yyruleno==238);
108029 {yygotominor.yy314 = 0;}
108030         break;
108031       case 148: /* indexed_opt ::= NOT INDEXED */
108032 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
108033         break;
108034       case 149: /* using_opt ::= USING LP inscollist RP */
108035       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
108036 {yygotominor.yy384 = yymsp[-1].minor.yy384;}
108037         break;
108038       case 150: /* using_opt ::= */
108039       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
108040 {yygotominor.yy384 = 0;}
108041         break;
108042       case 152: /* orderby_opt ::= ORDER BY sortlist */
108043       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
108044       case 239: /* exprlist ::= nexprlist */ yytestcase(yyruleno==239);
108045 {yygotominor.yy322 = yymsp[0].minor.yy322;}
108046         break;
108047       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
108048 {
108049   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
108050   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108051 }
108052         break;
108053       case 154: /* sortlist ::= sortitem sortorder */
108054 {
108055   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314);
108056   if( yygotominor.yy322 && ALWAYS(yygotominor.yy322->a) ) yygotominor.yy322->a[0].sortOrder = (u8)yymsp[0].minor.yy4;
108057 }
108058         break;
108059       case 156: /* sortorder ::= ASC */
108060       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
108061 {yygotominor.yy4 = SQLITE_SO_ASC;}
108062         break;
108063       case 157: /* sortorder ::= DESC */
108064 {yygotominor.yy4 = SQLITE_SO_DESC;}
108065         break;
108066       case 163: /* limit_opt ::= */
108067 {yygotominor.yy292.pLimit = 0; yygotominor.yy292.pOffset = 0;}
108068         break;
108069       case 164: /* limit_opt ::= LIMIT expr */
108070 {yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr; yygotominor.yy292.pOffset = 0;}
108071         break;
108072       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
108073 {yygotominor.yy292.pLimit = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pOffset = yymsp[0].minor.yy118.pExpr;}
108074         break;
108075       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
108076 {yygotominor.yy292.pOffset = yymsp[-2].minor.yy118.pExpr; yygotominor.yy292.pLimit = yymsp[0].minor.yy118.pExpr;}
108077         break;
108078       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
108079 {
108080   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
108081   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314);
108082 }
108083         break;
108084       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
108085 {
108086   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
108087   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
108088   sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy210);
108089 }
108090         break;
108091       case 171: /* setlist ::= setlist COMMA nm EQ expr */
108092 {
108093   yygotominor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy118.pExpr);
108094   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108095 }
108096         break;
108097       case 172: /* setlist ::= nm EQ expr */
108098 {
108099   yygotominor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy118.pExpr);
108100   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108101 }
108102         break;
108103       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
108104 {sqlite3Insert(pParse, yymsp[-5].minor.yy259, yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy384, yymsp[-7].minor.yy210);}
108105         break;
108106       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
108107 {sqlite3Insert(pParse, yymsp[-2].minor.yy259, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy210);}
108108         break;
108109       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
108110 {sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy210);}
108111         break;
108112       case 176: /* insert_cmd ::= INSERT orconf */
108113 {yygotominor.yy210 = yymsp[0].minor.yy210;}
108114         break;
108115       case 177: /* insert_cmd ::= REPLACE */
108116 {yygotominor.yy210 = OE_Replace;}
108117         break;
108118       case 178: /* itemlist ::= itemlist COMMA expr */
108119       case 241: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==241);
108120 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy118.pExpr);}
108121         break;
108122       case 179: /* itemlist ::= expr */
108123       case 242: /* nexprlist ::= expr */ yytestcase(yyruleno==242);
108124 {yygotominor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy118.pExpr);}
108125         break;
108126       case 182: /* inscollist ::= inscollist COMMA nm */
108127 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
108128         break;
108129       case 183: /* inscollist ::= nm */
108130 {yygotominor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
108131         break;
108132       case 184: /* expr ::= term */
108133 {yygotominor.yy118 = yymsp[0].minor.yy118;}
108134         break;
108135       case 185: /* expr ::= LP expr RP */
108136 {yygotominor.yy118.pExpr = yymsp[-1].minor.yy118.pExpr; spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
108137         break;
108138       case 186: /* term ::= NULL */
108139       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
108140       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
108141 {spanExpr(&yygotominor.yy118, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
108142         break;
108143       case 187: /* expr ::= id */
108144       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
108145 {spanExpr(&yygotominor.yy118, pParse, TK_ID, &yymsp[0].minor.yy0);}
108146         break;
108147       case 189: /* expr ::= nm DOT nm */
108148 {
108149   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
108150   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
108151   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
108152   spanSet(&yygotominor.yy118,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
108153 }
108154         break;
108155       case 190: /* expr ::= nm DOT nm DOT nm */
108156 {
108157   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
108158   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
108159   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
108160   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
108161   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
108162   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
108163 }
108164         break;
108165       case 193: /* expr ::= REGISTER */
108166 {
108167   /* When doing a nested parse, one can include terms in an expression
108168   ** that look like this:   #1 #2 ...  These terms refer to registers
108169   ** in the virtual machine.  #N is the N-th register. */
108170   if( pParse->nested==0 ){
108171     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
108172     yygotominor.yy118.pExpr = 0;
108173   }else{
108174     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
108175     if( yygotominor.yy118.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy118.pExpr->iTable);
108176   }
108177   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108178 }
108179         break;
108180       case 194: /* expr ::= VARIABLE */
108181 {
108182   spanExpr(&yygotominor.yy118, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
108183   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy118.pExpr);
108184   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108185 }
108186         break;
108187       case 195: /* expr ::= expr COLLATE ids */
108188 {
108189   yygotominor.yy118.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy118.pExpr, &yymsp[0].minor.yy0);
108190   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
108191   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108192 }
108193         break;
108194       case 196: /* expr ::= CAST LP expr AS typetoken RP */
108195 {
108196   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy118.pExpr, 0, &yymsp[-1].minor.yy0);
108197   spanSet(&yygotominor.yy118,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
108198 }
108199         break;
108200       case 197: /* expr ::= ID LP distinct exprlist RP */
108201 {
108202   if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
108203     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
108204   }
108205   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
108206   spanSet(&yygotominor.yy118,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
108207   if( yymsp[-2].minor.yy4 && yygotominor.yy118.pExpr ){
108208     yygotominor.yy118.pExpr->flags |= EP_Distinct;
108209   }
108210 }
108211         break;
108212       case 198: /* expr ::= ID LP STAR RP */
108213 {
108214   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
108215   spanSet(&yygotominor.yy118,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
108216 }
108217         break;
108218       case 199: /* term ::= CTIME_KW */
108219 {
108220   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
108221   ** treated as functions that return constants */
108222   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
108223   if( yygotominor.yy118.pExpr ){
108224     yygotominor.yy118.pExpr->op = TK_CONST_FUNC;
108225   }
108226   spanSet(&yygotominor.yy118, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
108227 }
108228         break;
108229       case 200: /* expr ::= expr AND expr */
108230       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
108231       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
108232       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
108233       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
108234       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
108235       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
108236       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
108237 {spanBinaryExpr(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);}
108238         break;
108239       case 208: /* likeop ::= LIKE_KW */
108240       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
108241 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 0;}
108242         break;
108243       case 209: /* likeop ::= NOT LIKE_KW */
108244       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
108245 {yygotominor.yy342.eOperator = yymsp[0].minor.yy0; yygotominor.yy342.not = 1;}
108246         break;
108247       case 212: /* expr ::= expr likeop expr */
108248 {
108249   ExprList *pList;
108250   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy118.pExpr);
108251   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy118.pExpr);
108252   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy342.eOperator);
108253   if( yymsp[-1].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108254   yygotominor.yy118.zStart = yymsp[-2].minor.yy118.zStart;
108255   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108256   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
108257 }
108258         break;
108259       case 213: /* expr ::= expr likeop expr ESCAPE expr */
108260 {
108261   ExprList *pList;
108262   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108263   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy118.pExpr);
108264   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
108265   yygotominor.yy118.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy342.eOperator);
108266   if( yymsp[-3].minor.yy342.not ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108267   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108268   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108269   if( yygotominor.yy118.pExpr ) yygotominor.yy118.pExpr->flags |= EP_InfixFunc;
108270 }
108271         break;
108272       case 214: /* expr ::= expr ISNULL|NOTNULL */
108273 {spanUnaryPostfix(&yygotominor.yy118,pParse,yymsp[0].major,&yymsp[-1].minor.yy118,&yymsp[0].minor.yy0);}
108274         break;
108275       case 215: /* expr ::= expr NOT NULL */
108276 {spanUnaryPostfix(&yygotominor.yy118,pParse,TK_NOTNULL,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy0);}
108277         break;
108278       case 216: /* expr ::= expr IS expr */
108279 {
108280   spanBinaryExpr(&yygotominor.yy118,pParse,TK_IS,&yymsp[-2].minor.yy118,&yymsp[0].minor.yy118);
108281   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_ISNULL);
108282 }
108283         break;
108284       case 217: /* expr ::= expr IS NOT expr */
108285 {
108286   spanBinaryExpr(&yygotominor.yy118,pParse,TK_ISNOT,&yymsp[-3].minor.yy118,&yymsp[0].minor.yy118);
108287   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy118.pExpr, yygotominor.yy118.pExpr, TK_NOTNULL);
108288 }
108289         break;
108290       case 218: /* expr ::= NOT expr */
108291       case 219: /* expr ::= BITNOT expr */ yytestcase(yyruleno==219);
108292 {spanUnaryPrefix(&yygotominor.yy118,pParse,yymsp[-1].major,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108293         break;
108294       case 220: /* expr ::= MINUS expr */
108295 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UMINUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108296         break;
108297       case 221: /* expr ::= PLUS expr */
108298 {spanUnaryPrefix(&yygotominor.yy118,pParse,TK_UPLUS,&yymsp[0].minor.yy118,&yymsp[-1].minor.yy0);}
108299         break;
108300       case 224: /* expr ::= expr between_op expr AND expr */
108301 {
108302   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108303   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy118.pExpr);
108304   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108305   if( yygotominor.yy118.pExpr ){
108306     yygotominor.yy118.pExpr->x.pList = pList;
108307   }else{
108308     sqlite3ExprListDelete(pParse->db, pList);
108309   }
108310   if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108311   yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108312   yygotominor.yy118.zEnd = yymsp[0].minor.yy118.zEnd;
108313 }
108314         break;
108315       case 227: /* expr ::= expr in_op LP exprlist RP */
108316 {
108317     if( yymsp[-1].minor.yy322==0 ){
108318       /* Expressions of the form
108319       **
108320       **      expr1 IN ()
108321       **      expr1 NOT IN ()
108322       **
108323       ** simplify to constants 0 (false) and 1 (true), respectively,
108324       ** regardless of the value of expr1.
108325       */
108326       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy4]);
108327       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy118.pExpr);
108328     }else{
108329       yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108330       if( yygotominor.yy118.pExpr ){
108331         yygotominor.yy118.pExpr->x.pList = yymsp[-1].minor.yy322;
108332         sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108333       }else{
108334         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
108335       }
108336       if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108337     }
108338     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108339     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108340   }
108341         break;
108342       case 228: /* expr ::= LP select RP */
108343 {
108344     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
108345     if( yygotominor.yy118.pExpr ){
108346       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
108347       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108348       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108349     }else{
108350       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108351     }
108352     yygotominor.yy118.zStart = yymsp[-2].minor.yy0.z;
108353     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108354   }
108355         break;
108356       case 229: /* expr ::= expr in_op LP select RP */
108357 {
108358     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy118.pExpr, 0, 0);
108359     if( yygotominor.yy118.pExpr ){
108360       yygotominor.yy118.pExpr->x.pSelect = yymsp[-1].minor.yy387;
108361       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108362       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108363     }else{
108364       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108365     }
108366     if( yymsp[-3].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108367     yygotominor.yy118.zStart = yymsp[-4].minor.yy118.zStart;
108368     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108369   }
108370         break;
108371       case 230: /* expr ::= expr in_op nm dbnm */
108372 {
108373     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
108374     yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy118.pExpr, 0, 0);
108375     if( yygotominor.yy118.pExpr ){
108376       yygotominor.yy118.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
108377       ExprSetProperty(yygotominor.yy118.pExpr, EP_xIsSelect);
108378       sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108379     }else{
108380       sqlite3SrcListDelete(pParse->db, pSrc);
108381     }
108382     if( yymsp[-2].minor.yy4 ) yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy118.pExpr, 0, 0);
108383     yygotominor.yy118.zStart = yymsp[-3].minor.yy118.zStart;
108384     yygotominor.yy118.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
108385   }
108386         break;
108387       case 231: /* expr ::= EXISTS LP select RP */
108388 {
108389     Expr *p = yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
108390     if( p ){
108391       p->x.pSelect = yymsp[-1].minor.yy387;
108392       ExprSetProperty(p, EP_xIsSelect);
108393       sqlite3ExprSetHeight(pParse, p);
108394     }else{
108395       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
108396     }
108397     yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
108398     yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108399   }
108400         break;
108401       case 232: /* expr ::= CASE case_operand case_exprlist case_else END */
108402 {
108403   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, 0);
108404   if( yygotominor.yy118.pExpr ){
108405     yygotominor.yy118.pExpr->x.pList = yymsp[-2].minor.yy322;
108406     sqlite3ExprSetHeight(pParse, yygotominor.yy118.pExpr);
108407   }else{
108408     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
108409   }
108410   yygotominor.yy118.zStart = yymsp[-4].minor.yy0.z;
108411   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108412 }
108413         break;
108414       case 233: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
108415 {
108416   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy118.pExpr);
108417   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
108418 }
108419         break;
108420       case 234: /* case_exprlist ::= WHEN expr THEN expr */
108421 {
108422   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy118.pExpr);
108423   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yygotominor.yy322, yymsp[0].minor.yy118.pExpr);
108424 }
108425         break;
108426       case 243: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
108427 {
108428   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
108429                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy322, yymsp[-9].minor.yy4,
108430                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy4);
108431 }
108432         break;
108433       case 244: /* uniqueflag ::= UNIQUE */
108434       case 298: /* raisetype ::= ABORT */ yytestcase(yyruleno==298);
108435 {yygotominor.yy4 = OE_Abort;}
108436         break;
108437       case 245: /* uniqueflag ::= */
108438 {yygotominor.yy4 = OE_None;}
108439         break;
108440       case 248: /* idxlist ::= idxlist COMMA nm collate sortorder */
108441 {
108442   Expr *p = 0;
108443   if( yymsp[-1].minor.yy0.n>0 ){
108444     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
108445     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
108446   }
108447   yygotominor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, p);
108448   sqlite3ExprListSetName(pParse,yygotominor.yy322,&yymsp[-2].minor.yy0,1);
108449   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
108450   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108451 }
108452         break;
108453       case 249: /* idxlist ::= nm collate sortorder */
108454 {
108455   Expr *p = 0;
108456   if( yymsp[-1].minor.yy0.n>0 ){
108457     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
108458     sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
108459   }
108460   yygotominor.yy322 = sqlite3ExprListAppend(pParse,0, p);
108461   sqlite3ExprListSetName(pParse, yygotominor.yy322, &yymsp[-2].minor.yy0, 1);
108462   sqlite3ExprListCheckLength(pParse, yygotominor.yy322, "index");
108463   if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy4;
108464 }
108465         break;
108466       case 250: /* collate ::= */
108467 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
108468         break;
108469       case 252: /* cmd ::= DROP INDEX ifexists fullname */
108470 {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
108471         break;
108472       case 253: /* cmd ::= VACUUM */
108473       case 254: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==254);
108474 {sqlite3Vacuum(pParse);}
108475         break;
108476       case 255: /* cmd ::= PRAGMA nm dbnm */
108477 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
108478         break;
108479       case 256: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
108480 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
108481         break;
108482       case 257: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
108483 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
108484         break;
108485       case 258: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
108486 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
108487         break;
108488       case 259: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
108489 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
108490         break;
108491       case 270: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
108492 {
108493   Token all;
108494   all.z = yymsp[-3].minor.yy0.z;
108495   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
108496   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
108497 }
108498         break;
108499       case 271: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
108500 {
108501   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
108502   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
108503 }
108504         break;
108505       case 272: /* trigger_time ::= BEFORE */
108506       case 275: /* trigger_time ::= */ yytestcase(yyruleno==275);
108507 { yygotominor.yy4 = TK_BEFORE; }
108508         break;
108509       case 273: /* trigger_time ::= AFTER */
108510 { yygotominor.yy4 = TK_AFTER;  }
108511         break;
108512       case 274: /* trigger_time ::= INSTEAD OF */
108513 { yygotominor.yy4 = TK_INSTEAD;}
108514         break;
108515       case 276: /* trigger_event ::= DELETE|INSERT */
108516       case 277: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==277);
108517 {yygotominor.yy90.a = yymsp[0].major; yygotominor.yy90.b = 0;}
108518         break;
108519       case 278: /* trigger_event ::= UPDATE OF inscollist */
108520 {yygotominor.yy90.a = TK_UPDATE; yygotominor.yy90.b = yymsp[0].minor.yy384;}
108521         break;
108522       case 281: /* when_clause ::= */
108523       case 303: /* key_opt ::= */ yytestcase(yyruleno==303);
108524 { yygotominor.yy314 = 0; }
108525         break;
108526       case 282: /* when_clause ::= WHEN expr */
108527       case 304: /* key_opt ::= KEY expr */ yytestcase(yyruleno==304);
108528 { yygotominor.yy314 = yymsp[0].minor.yy118.pExpr; }
108529         break;
108530       case 283: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
108531 {
108532   assert( yymsp[-2].minor.yy203!=0 );
108533   yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
108534   yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
108535   yygotominor.yy203 = yymsp[-2].minor.yy203;
108536 }
108537         break;
108538       case 284: /* trigger_cmd_list ::= trigger_cmd SEMI */
108539 {
108540   assert( yymsp[-1].minor.yy203!=0 );
108541   yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
108542   yygotominor.yy203 = yymsp[-1].minor.yy203;
108543 }
108544         break;
108545       case 286: /* trnm ::= nm DOT nm */
108546 {
108547   yygotominor.yy0 = yymsp[0].minor.yy0;
108548   sqlite3ErrorMsg(pParse,
108549         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
108550         "statements within triggers");
108551 }
108552         break;
108553       case 288: /* tridxby ::= INDEXED BY nm */
108554 {
108555   sqlite3ErrorMsg(pParse,
108556         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
108557         "within triggers");
108558 }
108559         break;
108560       case 289: /* tridxby ::= NOT INDEXED */
108561 {
108562   sqlite3ErrorMsg(pParse,
108563         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
108564         "within triggers");
108565 }
108566         break;
108567       case 290: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
108568 { yygotominor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy314, yymsp[-5].minor.yy210); }
108569         break;
108570       case 291: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
108571 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy384, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy210);}
108572         break;
108573       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
108574 {yygotominor.yy203 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy384, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy210);}
108575         break;
108576       case 293: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
108577 {yygotominor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy314);}
108578         break;
108579       case 294: /* trigger_cmd ::= select */
108580 {yygotominor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
108581         break;
108582       case 295: /* expr ::= RAISE LP IGNORE RP */
108583 {
108584   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
108585   if( yygotominor.yy118.pExpr ){
108586     yygotominor.yy118.pExpr->affinity = OE_Ignore;
108587   }
108588   yygotominor.yy118.zStart = yymsp[-3].minor.yy0.z;
108589   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108590 }
108591         break;
108592       case 296: /* expr ::= RAISE LP raisetype COMMA nm RP */
108593 {
108594   yygotominor.yy118.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
108595   if( yygotominor.yy118.pExpr ) {
108596     yygotominor.yy118.pExpr->affinity = (char)yymsp[-3].minor.yy4;
108597   }
108598   yygotominor.yy118.zStart = yymsp[-5].minor.yy0.z;
108599   yygotominor.yy118.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
108600 }
108601         break;
108602       case 297: /* raisetype ::= ROLLBACK */
108603 {yygotominor.yy4 = OE_Rollback;}
108604         break;
108605       case 299: /* raisetype ::= FAIL */
108606 {yygotominor.yy4 = OE_Fail;}
108607         break;
108608       case 300: /* cmd ::= DROP TRIGGER ifexists fullname */
108609 {
108610   sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
108611 }
108612         break;
108613       case 301: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
108614 {
108615   sqlite3Attach(pParse, yymsp[-3].minor.yy118.pExpr, yymsp[-1].minor.yy118.pExpr, yymsp[0].minor.yy314);
108616 }
108617         break;
108618       case 302: /* cmd ::= DETACH database_kw_opt expr */
108619 {
108620   sqlite3Detach(pParse, yymsp[0].minor.yy118.pExpr);
108621 }
108622         break;
108623       case 307: /* cmd ::= REINDEX */
108624 {sqlite3Reindex(pParse, 0, 0);}
108625         break;
108626       case 308: /* cmd ::= REINDEX nm dbnm */
108627 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
108628         break;
108629       case 309: /* cmd ::= ANALYZE */
108630 {sqlite3Analyze(pParse, 0, 0);}
108631         break;
108632       case 310: /* cmd ::= ANALYZE nm dbnm */
108633 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
108634         break;
108635       case 311: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
108636 {
108637   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
108638 }
108639         break;
108640       case 312: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
108641 {
108642   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
108643 }
108644         break;
108645       case 313: /* add_column_fullname ::= fullname */
108646 {
108647   pParse->db->lookaside.bEnabled = 0;
108648   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
108649 }
108650         break;
108651       case 316: /* cmd ::= create_vtab */
108652 {sqlite3VtabFinishParse(pParse,0);}
108653         break;
108654       case 317: /* cmd ::= create_vtab LP vtabarglist RP */
108655 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
108656         break;
108657       case 318: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
108658 {
108659     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
108660 }
108661         break;
108662       case 321: /* vtabarg ::= */
108663 {sqlite3VtabArgInit(pParse);}
108664         break;
108665       case 323: /* vtabargtoken ::= ANY */
108666       case 324: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==324);
108667       case 325: /* lp ::= LP */ yytestcase(yyruleno==325);
108668 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
108669         break;
108670       default:
108671       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
108672       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
108673       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
108674       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
108675       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
108676       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
108677       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
108678       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
108679       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
108680       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
108681       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
108682       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
108683       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
108684       /* (44) type ::= */ yytestcase(yyruleno==44);
108685       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
108686       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
108687       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
108688       /* (54) carglist ::= */ yytestcase(yyruleno==54);
108689       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
108690       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
108691       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
108692       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
108693       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
108694       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
108695       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
108696       /* (268) plus_opt ::= PLUS */ yytestcase(yyruleno==268);
108697       /* (269) plus_opt ::= */ yytestcase(yyruleno==269);
108698       /* (279) foreach_clause ::= */ yytestcase(yyruleno==279);
108699       /* (280) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==280);
108700       /* (287) tridxby ::= */ yytestcase(yyruleno==287);
108701       /* (305) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==305);
108702       /* (306) database_kw_opt ::= */ yytestcase(yyruleno==306);
108703       /* (314) kwcolumn_opt ::= */ yytestcase(yyruleno==314);
108704       /* (315) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==315);
108705       /* (319) vtabarglist ::= vtabarg */ yytestcase(yyruleno==319);
108706       /* (320) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==320);
108707       /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
108708       /* (326) anylist ::= */ yytestcase(yyruleno==326);
108709       /* (327) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==327);
108710       /* (328) anylist ::= anylist ANY */ yytestcase(yyruleno==328);
108711         break;
108712   };
108713   yygoto = yyRuleInfo[yyruleno].lhs;
108714   yysize = yyRuleInfo[yyruleno].nrhs;
108715   yypParser->yyidx -= yysize;
108716   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
108717   if( yyact < YYNSTATE ){
108718 #ifdef NDEBUG
108719     /* If we are not debugging and the reduce action popped at least
108720     ** one element off the stack, then we can push the new element back
108721     ** onto the stack here, and skip the stack overflow test in yy_shift().
108722     ** That gives a significant speed improvement. */
108723     if( yysize ){
108724       yypParser->yyidx++;
108725       yymsp -= yysize-1;
108726       yymsp->stateno = (YYACTIONTYPE)yyact;
108727       yymsp->major = (YYCODETYPE)yygoto;
108728       yymsp->minor = yygotominor;
108729     }else
108730 #endif
108731     {
108732       yy_shift(yypParser,yyact,yygoto,&yygotominor);
108733     }
108734   }else{
108735     assert( yyact == YYNSTATE + YYNRULE + 1 );
108736     yy_accept(yypParser);
108737   }
108738 }
108739 
108740 /*
108741 ** The following code executes when the parse fails
108742 */
108743 #ifndef YYNOERRORRECOVERY
108744 static void yy_parse_failed(
108745   yyParser *yypParser           /* The parser */
108746 ){
108747   sqlite3ParserARG_FETCH;
108748 #ifndef NDEBUG
108749   if( yyTraceFILE ){
108750     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
108751   }
108752 #endif
108753   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
108754   /* Here code is inserted which will be executed whenever the
108755   ** parser fails */
108756   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
108757 }
108758 #endif /* YYNOERRORRECOVERY */
108759 
108760 /*
108761 ** The following code executes when a syntax error first occurs.
108762 */
108763 static void yy_syntax_error(
108764   yyParser *yypParser,           /* The parser */
108765   int yymajor,                   /* The major type of the error token */
108766   YYMINORTYPE yyminor            /* The minor type of the error token */
108767 ){
108768   sqlite3ParserARG_FETCH;
108769 #define TOKEN (yyminor.yy0)
108770 
108771   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
108772   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
108773   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
108774   pParse->parseError = 1;
108775   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
108776 }
108777 
108778 /*
108779 ** The following is executed when the parser accepts
108780 */
108781 static void yy_accept(
108782   yyParser *yypParser           /* The parser */
108783 ){
108784   sqlite3ParserARG_FETCH;
108785 #ifndef NDEBUG
108786   if( yyTraceFILE ){
108787     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
108788   }
108789 #endif
108790   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
108791   /* Here code is inserted which will be executed whenever the
108792   ** parser accepts */
108793   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
108794 }
108795 
108796 /* The main parser program.
108797 ** The first argument is a pointer to a structure obtained from
108798 ** "sqlite3ParserAlloc" which describes the current state of the parser.
108799 ** The second argument is the major token number.  The third is
108800 ** the minor token.  The fourth optional argument is whatever the
108801 ** user wants (and specified in the grammar) and is available for
108802 ** use by the action routines.
108803 **
108804 ** Inputs:
108805 ** <ul>
108806 ** <li> A pointer to the parser (an opaque structure.)
108807 ** <li> The major token number.
108808 ** <li> The minor token number.
108809 ** <li> An option argument of a grammar-specified type.
108810 ** </ul>
108811 **
108812 ** Outputs:
108813 ** None.
108814 */
108815 SQLITE_PRIVATE void sqlite3Parser(
108816   void *yyp,                   /* The parser */
108817   int yymajor,                 /* The major token code number */
108818   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
108819   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
108820 ){
108821   YYMINORTYPE yyminorunion;
108822   int yyact;            /* The parser action. */
108823   int yyendofinput;     /* True if we are at the end of input */
108824 #ifdef YYERRORSYMBOL
108825   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
108826 #endif
108827   yyParser *yypParser;  /* The parser */
108828 
108829   /* (re)initialize the parser, if necessary */
108830   yypParser = (yyParser*)yyp;
108831   if( yypParser->yyidx<0 ){
108832 #if YYSTACKDEPTH<=0
108833     if( yypParser->yystksz <=0 ){
108834       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
108835       yyminorunion = yyzerominor;
108836       yyStackOverflow(yypParser, &yyminorunion);
108837       return;
108838     }
108839 #endif
108840     yypParser->yyidx = 0;
108841     yypParser->yyerrcnt = -1;
108842     yypParser->yystack[0].stateno = 0;
108843     yypParser->yystack[0].major = 0;
108844   }
108845   yyminorunion.yy0 = yyminor;
108846   yyendofinput = (yymajor==0);
108847   sqlite3ParserARG_STORE;
108848 
108849 #ifndef NDEBUG
108850   if( yyTraceFILE ){
108851     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
108852   }
108853 #endif
108854 
108855   do{
108856     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
108857     if( yyact<YYNSTATE ){
108858       assert( !yyendofinput );  /* Impossible to shift the $ token */
108859       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
108860       yypParser->yyerrcnt--;
108861       yymajor = YYNOCODE;
108862     }else if( yyact < YYNSTATE + YYNRULE ){
108863       yy_reduce(yypParser,yyact-YYNSTATE);
108864     }else{
108865       assert( yyact == YY_ERROR_ACTION );
108866 #ifdef YYERRORSYMBOL
108867       int yymx;
108868 #endif
108869 #ifndef NDEBUG
108870       if( yyTraceFILE ){
108871         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
108872       }
108873 #endif
108874 #ifdef YYERRORSYMBOL
108875       /* A syntax error has occurred.
108876       ** The response to an error depends upon whether or not the
108877       ** grammar defines an error token "ERROR".
108878       **
108879       ** This is what we do if the grammar does define ERROR:
108880       **
108881       **  * Call the %syntax_error function.
108882       **
108883       **  * Begin popping the stack until we enter a state where
108884       **    it is legal to shift the error symbol, then shift
108885       **    the error symbol.
108886       **
108887       **  * Set the error count to three.
108888       **
108889       **  * Begin accepting and shifting new tokens.  No new error
108890       **    processing will occur until three tokens have been
108891       **    shifted successfully.
108892       **
108893       */
108894       if( yypParser->yyerrcnt<0 ){
108895         yy_syntax_error(yypParser,yymajor,yyminorunion);
108896       }
108897       yymx = yypParser->yystack[yypParser->yyidx].major;
108898       if( yymx==YYERRORSYMBOL || yyerrorhit ){
108899 #ifndef NDEBUG
108900         if( yyTraceFILE ){
108901           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
108902              yyTracePrompt,yyTokenName[yymajor]);
108903         }
108904 #endif
108905         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
108906         yymajor = YYNOCODE;
108907       }else{
108908          while(
108909           yypParser->yyidx >= 0 &&
108910           yymx != YYERRORSYMBOL &&
108911           (yyact = yy_find_reduce_action(
108912                         yypParser->yystack[yypParser->yyidx].stateno,
108913                         YYERRORSYMBOL)) >= YYNSTATE
108914         ){
108915           yy_pop_parser_stack(yypParser);
108916         }
108917         if( yypParser->yyidx < 0 || yymajor==0 ){
108918           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
108919           yy_parse_failed(yypParser);
108920           yymajor = YYNOCODE;
108921         }else if( yymx!=YYERRORSYMBOL ){
108922           YYMINORTYPE u2;
108923           u2.YYERRSYMDT = 0;
108924           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
108925         }
108926       }
108927       yypParser->yyerrcnt = 3;
108928       yyerrorhit = 1;
108929 #elif defined(YYNOERRORRECOVERY)
108930       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
108931       ** do any kind of error recovery.  Instead, simply invoke the syntax
108932       ** error routine and continue going as if nothing had happened.
108933       **
108934       ** Applications can set this macro (for example inside %include) if
108935       ** they intend to abandon the parse upon the first syntax error seen.
108936       */
108937       yy_syntax_error(yypParser,yymajor,yyminorunion);
108938       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
108939       yymajor = YYNOCODE;
108940 
108941 #else  /* YYERRORSYMBOL is not defined */
108942       /* This is what we do if the grammar does not define ERROR:
108943       **
108944       **  * Report an error message, and throw away the input token.
108945       **
108946       **  * If the input token is $, then fail the parse.
108947       **
108948       ** As before, subsequent error messages are suppressed until
108949       ** three input tokens have been successfully shifted.
108950       */
108951       if( yypParser->yyerrcnt<=0 ){
108952         yy_syntax_error(yypParser,yymajor,yyminorunion);
108953       }
108954       yypParser->yyerrcnt = 3;
108955       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
108956       if( yyendofinput ){
108957         yy_parse_failed(yypParser);
108958       }
108959       yymajor = YYNOCODE;
108960 #endif
108961     }
108962   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
108963   return;
108964 }
108965 
108966 /************** End of parse.c ***********************************************/
108967 /************** Begin file tokenize.c ****************************************/
108968 /*
108969 ** 2001 September 15
108970 **
108971 ** The author disclaims copyright to this source code.  In place of
108972 ** a legal notice, here is a blessing:
108973 **
108974 **    May you do good and not evil.
108975 **    May you find forgiveness for yourself and forgive others.
108976 **    May you share freely, never taking more than you give.
108977 **
108978 *************************************************************************
108979 ** An tokenizer for SQL
108980 **
108981 ** This file contains C code that splits an SQL input string up into
108982 ** individual tokens and sends those tokens one-by-one over to the
108983 ** parser for analysis.
108984 */
108985 /* #include <stdlib.h> */
108986 
108987 /*
108988 ** The charMap() macro maps alphabetic characters into their
108989 ** lower-case ASCII equivalent.  On ASCII machines, this is just
108990 ** an upper-to-lower case map.  On EBCDIC machines we also need
108991 ** to adjust the encoding.  Only alphabetic characters and underscores
108992 ** need to be translated.
108993 */
108994 #ifdef SQLITE_ASCII
108995 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
108996 #endif
108997 #ifdef SQLITE_EBCDIC
108998 # define charMap(X) ebcdicToAscii[(unsigned char)X]
108999 const unsigned char ebcdicToAscii[] = {
109000 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
109001    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
109002    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
109003    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
109004    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
109005    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
109006    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
109007    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
109008    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
109009    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
109010    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
109011    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
109012    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
109013    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
109014    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
109015    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
109016    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
109017 };
109018 #endif
109019 
109020 /*
109021 ** The sqlite3KeywordCode function looks up an identifier to determine if
109022 ** it is a keyword.  If it is a keyword, the token code of that keyword is
109023 ** returned.  If the input is not a keyword, TK_ID is returned.
109024 **
109025 ** The implementation of this routine was generated by a program,
109026 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
109027 ** The output of the mkkeywordhash.c program is written into a file
109028 ** named keywordhash.h and then included into this source file by
109029 ** the #include below.
109030 */
109031 /************** Include keywordhash.h in the middle of tokenize.c ************/
109032 /************** Begin file keywordhash.h *************************************/
109033 /***** This file contains automatically generated code ******
109034 **
109035 ** The code in this file has been automatically generated by
109036 **
109037 **   sqlite/tool/mkkeywordhash.c
109038 **
109039 ** The code in this file implements a function that determines whether
109040 ** or not a given identifier is really an SQL keyword.  The same thing
109041 ** might be implemented more directly using a hand-written hash table.
109042 ** But by using this automatically generated code, the size of the code
109043 ** is substantially reduced.  This is important for embedded applications
109044 ** on platforms with limited memory.
109045 */
109046 /* Hash score: 175 */
109047 static int keywordCode(const char *z, int n){
109048   /* zText[] encodes 811 bytes of keywords in 541 bytes */
109049   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
109050   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
109051   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
109052   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
109053   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
109054   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
109055   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
109056   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
109057   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
109058   /*   INITIALLY                                                          */
109059   static const char zText[540] = {
109060     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
109061     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
109062     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
109063     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
109064     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
109065     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
109066     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
109067     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
109068     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
109069     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
109070     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
109071     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
109072     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
109073     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
109074     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
109075     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
109076     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
109077     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
109078     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
109079     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
109080     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
109081     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
109082     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
109083     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
109084     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
109085     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
109086     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
109087     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
109088     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
109089     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
109090   };
109091   static const unsigned char aHash[127] = {
109092       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
109093       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
109094      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
109095        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
109096        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
109097       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
109098       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
109099       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
109100       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
109101       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
109102   };
109103   static const unsigned char aNext[121] = {
109104        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
109105        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
109106        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
109107        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
109108        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
109109       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
109110       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
109111        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
109112      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
109113       35,  64,   0,   0,
109114   };
109115   static const unsigned char aLen[121] = {
109116        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
109117        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
109118       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
109119        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
109120        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
109121        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
109122        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
109123        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
109124        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
109125        6,   4,   9,   3,
109126   };
109127   static const unsigned short int aOffset[121] = {
109128        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
109129       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
109130       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
109131      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
109132      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
109133      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
109134      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
109135      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
109136      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
109137      521, 527, 531, 536,
109138   };
109139   static const unsigned char aCode[121] = {
109140     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
109141     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
109142     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
109143     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
109144     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
109145     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
109146     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
109147     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
109148     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
109149     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
109150     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
109151     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
109152     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
109153     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
109154     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
109155     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
109156     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
109157     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
109158     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
109159     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
109160     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
109161     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
109162     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
109163     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
109164     TK_ALL,
109165   };
109166   int h, i;
109167   if( n<2 ) return TK_ID;
109168   h = ((charMap(z[0])*4) ^
109169       (charMap(z[n-1])*3) ^
109170       n) % 127;
109171   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
109172     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
109173       testcase( i==0 ); /* REINDEX */
109174       testcase( i==1 ); /* INDEXED */
109175       testcase( i==2 ); /* INDEX */
109176       testcase( i==3 ); /* DESC */
109177       testcase( i==4 ); /* ESCAPE */
109178       testcase( i==5 ); /* EACH */
109179       testcase( i==6 ); /* CHECK */
109180       testcase( i==7 ); /* KEY */
109181       testcase( i==8 ); /* BEFORE */
109182       testcase( i==9 ); /* FOREIGN */
109183       testcase( i==10 ); /* FOR */
109184       testcase( i==11 ); /* IGNORE */
109185       testcase( i==12 ); /* REGEXP */
109186       testcase( i==13 ); /* EXPLAIN */
109187       testcase( i==14 ); /* INSTEAD */
109188       testcase( i==15 ); /* ADD */
109189       testcase( i==16 ); /* DATABASE */
109190       testcase( i==17 ); /* AS */
109191       testcase( i==18 ); /* SELECT */
109192       testcase( i==19 ); /* TABLE */
109193       testcase( i==20 ); /* LEFT */
109194       testcase( i==21 ); /* THEN */
109195       testcase( i==22 ); /* END */
109196       testcase( i==23 ); /* DEFERRABLE */
109197       testcase( i==24 ); /* ELSE */
109198       testcase( i==25 ); /* EXCEPT */
109199       testcase( i==26 ); /* TRANSACTION */
109200       testcase( i==27 ); /* ACTION */
109201       testcase( i==28 ); /* ON */
109202       testcase( i==29 ); /* NATURAL */
109203       testcase( i==30 ); /* ALTER */
109204       testcase( i==31 ); /* RAISE */
109205       testcase( i==32 ); /* EXCLUSIVE */
109206       testcase( i==33 ); /* EXISTS */
109207       testcase( i==34 ); /* SAVEPOINT */
109208       testcase( i==35 ); /* INTERSECT */
109209       testcase( i==36 ); /* TRIGGER */
109210       testcase( i==37 ); /* REFERENCES */
109211       testcase( i==38 ); /* CONSTRAINT */
109212       testcase( i==39 ); /* INTO */
109213       testcase( i==40 ); /* OFFSET */
109214       testcase( i==41 ); /* OF */
109215       testcase( i==42 ); /* SET */
109216       testcase( i==43 ); /* TEMPORARY */
109217       testcase( i==44 ); /* TEMP */
109218       testcase( i==45 ); /* OR */
109219       testcase( i==46 ); /* UNIQUE */
109220       testcase( i==47 ); /* QUERY */
109221       testcase( i==48 ); /* ATTACH */
109222       testcase( i==49 ); /* HAVING */
109223       testcase( i==50 ); /* GROUP */
109224       testcase( i==51 ); /* UPDATE */
109225       testcase( i==52 ); /* BEGIN */
109226       testcase( i==53 ); /* INNER */
109227       testcase( i==54 ); /* RELEASE */
109228       testcase( i==55 ); /* BETWEEN */
109229       testcase( i==56 ); /* NOTNULL */
109230       testcase( i==57 ); /* NOT */
109231       testcase( i==58 ); /* NO */
109232       testcase( i==59 ); /* NULL */
109233       testcase( i==60 ); /* LIKE */
109234       testcase( i==61 ); /* CASCADE */
109235       testcase( i==62 ); /* ASC */
109236       testcase( i==63 ); /* DELETE */
109237       testcase( i==64 ); /* CASE */
109238       testcase( i==65 ); /* COLLATE */
109239       testcase( i==66 ); /* CREATE */
109240       testcase( i==67 ); /* CURRENT_DATE */
109241       testcase( i==68 ); /* DETACH */
109242       testcase( i==69 ); /* IMMEDIATE */
109243       testcase( i==70 ); /* JOIN */
109244       testcase( i==71 ); /* INSERT */
109245       testcase( i==72 ); /* MATCH */
109246       testcase( i==73 ); /* PLAN */
109247       testcase( i==74 ); /* ANALYZE */
109248       testcase( i==75 ); /* PRAGMA */
109249       testcase( i==76 ); /* ABORT */
109250       testcase( i==77 ); /* VALUES */
109251       testcase( i==78 ); /* VIRTUAL */
109252       testcase( i==79 ); /* LIMIT */
109253       testcase( i==80 ); /* WHEN */
109254       testcase( i==81 ); /* WHERE */
109255       testcase( i==82 ); /* RENAME */
109256       testcase( i==83 ); /* AFTER */
109257       testcase( i==84 ); /* REPLACE */
109258       testcase( i==85 ); /* AND */
109259       testcase( i==86 ); /* DEFAULT */
109260       testcase( i==87 ); /* AUTOINCREMENT */
109261       testcase( i==88 ); /* TO */
109262       testcase( i==89 ); /* IN */
109263       testcase( i==90 ); /* CAST */
109264       testcase( i==91 ); /* COLUMN */
109265       testcase( i==92 ); /* COMMIT */
109266       testcase( i==93 ); /* CONFLICT */
109267       testcase( i==94 ); /* CROSS */
109268       testcase( i==95 ); /* CURRENT_TIMESTAMP */
109269       testcase( i==96 ); /* CURRENT_TIME */
109270       testcase( i==97 ); /* PRIMARY */
109271       testcase( i==98 ); /* DEFERRED */
109272       testcase( i==99 ); /* DISTINCT */
109273       testcase( i==100 ); /* IS */
109274       testcase( i==101 ); /* DROP */
109275       testcase( i==102 ); /* FAIL */
109276       testcase( i==103 ); /* FROM */
109277       testcase( i==104 ); /* FULL */
109278       testcase( i==105 ); /* GLOB */
109279       testcase( i==106 ); /* BY */
109280       testcase( i==107 ); /* IF */
109281       testcase( i==108 ); /* ISNULL */
109282       testcase( i==109 ); /* ORDER */
109283       testcase( i==110 ); /* RESTRICT */
109284       testcase( i==111 ); /* OUTER */
109285       testcase( i==112 ); /* RIGHT */
109286       testcase( i==113 ); /* ROLLBACK */
109287       testcase( i==114 ); /* ROW */
109288       testcase( i==115 ); /* UNION */
109289       testcase( i==116 ); /* USING */
109290       testcase( i==117 ); /* VACUUM */
109291       testcase( i==118 ); /* VIEW */
109292       testcase( i==119 ); /* INITIALLY */
109293       testcase( i==120 ); /* ALL */
109294       return aCode[i];
109295     }
109296   }
109297   return TK_ID;
109298 }
109299 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
109300   return keywordCode((char*)z, n);
109301 }
109302 #define SQLITE_N_KEYWORD 121
109303 
109304 /************** End of keywordhash.h *****************************************/
109305 /************** Continuing where we left off in tokenize.c *******************/
109306 
109307 
109308 /*
109309 ** If X is a character that can be used in an identifier then
109310 ** IdChar(X) will be true.  Otherwise it is false.
109311 **
109312 ** For ASCII, any character with the high-order bit set is
109313 ** allowed in an identifier.  For 7-bit characters,
109314 ** sqlite3IsIdChar[X] must be 1.
109315 **
109316 ** For EBCDIC, the rules are more complex but have the same
109317 ** end result.
109318 **
109319 ** Ticket #1066.  the SQL standard does not allow '$' in the
109320 ** middle of identfiers.  But many SQL implementations do.
109321 ** SQLite will allow '$' in identifiers for compatibility.
109322 ** But the feature is undocumented.
109323 */
109324 #ifdef SQLITE_ASCII
109325 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
109326 #endif
109327 #ifdef SQLITE_EBCDIC
109328 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
109329 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
109330     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
109331     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
109332     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
109333     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
109334     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
109335     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
109336     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
109337     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
109338     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
109339     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
109340     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
109341     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
109342 };
109343 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
109344 #endif
109345 
109346 
109347 /*
109348 ** Return the length of the token that begins at z[0].
109349 ** Store the token type in *tokenType before returning.
109350 */
109351 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
109352   int i, c;
109353   switch( *z ){
109354     case ' ': case '\t': case '\n': case '\f': case '\r': {
109355       testcase( z[0]==' ' );
109356       testcase( z[0]=='\t' );
109357       testcase( z[0]=='\n' );
109358       testcase( z[0]=='\f' );
109359       testcase( z[0]=='\r' );
109360       for(i=1; sqlite3Isspace(z[i]); i++){}
109361       *tokenType = TK_SPACE;
109362       return i;
109363     }
109364     case '-': {
109365       if( z[1]=='-' ){
109366         /* IMP: R-15891-05542 -- syntax diagram for comments */
109367         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
109368         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
109369         return i;
109370       }
109371       *tokenType = TK_MINUS;
109372       return 1;
109373     }
109374     case '(': {
109375       *tokenType = TK_LP;
109376       return 1;
109377     }
109378     case ')': {
109379       *tokenType = TK_RP;
109380       return 1;
109381     }
109382     case ';': {
109383       *tokenType = TK_SEMI;
109384       return 1;
109385     }
109386     case '+': {
109387       *tokenType = TK_PLUS;
109388       return 1;
109389     }
109390     case '*': {
109391       *tokenType = TK_STAR;
109392       return 1;
109393     }
109394     case '/': {
109395       if( z[1]!='*' || z[2]==0 ){
109396         *tokenType = TK_SLASH;
109397         return 1;
109398       }
109399       /* IMP: R-15891-05542 -- syntax diagram for comments */
109400       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
109401       if( c ) i++;
109402       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
109403       return i;
109404     }
109405     case '%': {
109406       *tokenType = TK_REM;
109407       return 1;
109408     }
109409     case '=': {
109410       *tokenType = TK_EQ;
109411       return 1 + (z[1]=='=');
109412     }
109413     case '<': {
109414       if( (c=z[1])=='=' ){
109415         *tokenType = TK_LE;
109416         return 2;
109417       }else if( c=='>' ){
109418         *tokenType = TK_NE;
109419         return 2;
109420       }else if( c=='<' ){
109421         *tokenType = TK_LSHIFT;
109422         return 2;
109423       }else{
109424         *tokenType = TK_LT;
109425         return 1;
109426       }
109427     }
109428     case '>': {
109429       if( (c=z[1])=='=' ){
109430         *tokenType = TK_GE;
109431         return 2;
109432       }else if( c=='>' ){
109433         *tokenType = TK_RSHIFT;
109434         return 2;
109435       }else{
109436         *tokenType = TK_GT;
109437         return 1;
109438       }
109439     }
109440     case '!': {
109441       if( z[1]!='=' ){
109442         *tokenType = TK_ILLEGAL;
109443         return 2;
109444       }else{
109445         *tokenType = TK_NE;
109446         return 2;
109447       }
109448     }
109449     case '|': {
109450       if( z[1]!='|' ){
109451         *tokenType = TK_BITOR;
109452         return 1;
109453       }else{
109454         *tokenType = TK_CONCAT;
109455         return 2;
109456       }
109457     }
109458     case ',': {
109459       *tokenType = TK_COMMA;
109460       return 1;
109461     }
109462     case '&': {
109463       *tokenType = TK_BITAND;
109464       return 1;
109465     }
109466     case '~': {
109467       *tokenType = TK_BITNOT;
109468       return 1;
109469     }
109470     case '`':
109471     case '\'':
109472     case '"': {
109473       int delim = z[0];
109474       testcase( delim=='`' );
109475       testcase( delim=='\'' );
109476       testcase( delim=='"' );
109477       for(i=1; (c=z[i])!=0; i++){
109478         if( c==delim ){
109479           if( z[i+1]==delim ){
109480             i++;
109481           }else{
109482             break;
109483           }
109484         }
109485       }
109486       if( c=='\'' ){
109487         *tokenType = TK_STRING;
109488         return i+1;
109489       }else if( c!=0 ){
109490         *tokenType = TK_ID;
109491         return i+1;
109492       }else{
109493         *tokenType = TK_ILLEGAL;
109494         return i;
109495       }
109496     }
109497     case '.': {
109498 #ifndef SQLITE_OMIT_FLOATING_POINT
109499       if( !sqlite3Isdigit(z[1]) )
109500 #endif
109501       {
109502         *tokenType = TK_DOT;
109503         return 1;
109504       }
109505       /* If the next character is a digit, this is a floating point
109506       ** number that begins with ".".  Fall thru into the next case */
109507     }
109508     case '0': case '1': case '2': case '3': case '4':
109509     case '5': case '6': case '7': case '8': case '9': {
109510       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
109511       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
109512       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
109513       testcase( z[0]=='9' );
109514       *tokenType = TK_INTEGER;
109515       for(i=0; sqlite3Isdigit(z[i]); i++){}
109516 #ifndef SQLITE_OMIT_FLOATING_POINT
109517       if( z[i]=='.' ){
109518         i++;
109519         while( sqlite3Isdigit(z[i]) ){ i++; }
109520         *tokenType = TK_FLOAT;
109521       }
109522       if( (z[i]=='e' || z[i]=='E') &&
109523            ( sqlite3Isdigit(z[i+1])
109524             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
109525            )
109526       ){
109527         i += 2;
109528         while( sqlite3Isdigit(z[i]) ){ i++; }
109529         *tokenType = TK_FLOAT;
109530       }
109531 #endif
109532       while( IdChar(z[i]) ){
109533         *tokenType = TK_ILLEGAL;
109534         i++;
109535       }
109536       return i;
109537     }
109538     case '[': {
109539       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
109540       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
109541       return i;
109542     }
109543     case '?': {
109544       *tokenType = TK_VARIABLE;
109545       for(i=1; sqlite3Isdigit(z[i]); i++){}
109546       return i;
109547     }
109548     case '#': {
109549       for(i=1; sqlite3Isdigit(z[i]); i++){}
109550       if( i>1 ){
109551         /* Parameters of the form #NNN (where NNN is a number) are used
109552         ** internally by sqlite3NestedParse.  */
109553         *tokenType = TK_REGISTER;
109554         return i;
109555       }
109556       /* Fall through into the next case if the '#' is not followed by
109557       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
109558     }
109559 #ifndef SQLITE_OMIT_TCL_VARIABLE
109560     case '$':
109561 #endif
109562     case '@':  /* For compatibility with MS SQL Server */
109563     case ':': {
109564       int n = 0;
109565       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
109566       *tokenType = TK_VARIABLE;
109567       for(i=1; (c=z[i])!=0; i++){
109568         if( IdChar(c) ){
109569           n++;
109570 #ifndef SQLITE_OMIT_TCL_VARIABLE
109571         }else if( c=='(' && n>0 ){
109572           do{
109573             i++;
109574           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
109575           if( c==')' ){
109576             i++;
109577           }else{
109578             *tokenType = TK_ILLEGAL;
109579           }
109580           break;
109581         }else if( c==':' && z[i+1]==':' ){
109582           i++;
109583 #endif
109584         }else{
109585           break;
109586         }
109587       }
109588       if( n==0 ) *tokenType = TK_ILLEGAL;
109589       return i;
109590     }
109591 #ifndef SQLITE_OMIT_BLOB_LITERAL
109592     case 'x': case 'X': {
109593       testcase( z[0]=='x' ); testcase( z[0]=='X' );
109594       if( z[1]=='\'' ){
109595         *tokenType = TK_BLOB;
109596         for(i=2; sqlite3Isxdigit(z[i]); i++){}
109597         if( z[i]!='\'' || i%2 ){
109598           *tokenType = TK_ILLEGAL;
109599           while( z[i] && z[i]!='\'' ){ i++; }
109600         }
109601         if( z[i] ) i++;
109602         return i;
109603       }
109604       /* Otherwise fall through to the next case */
109605     }
109606 #endif
109607     default: {
109608       if( !IdChar(*z) ){
109609         break;
109610       }
109611       for(i=1; IdChar(z[i]); i++){}
109612       *tokenType = keywordCode((char*)z, i);
109613       return i;
109614     }
109615   }
109616   *tokenType = TK_ILLEGAL;
109617   return 1;
109618 }
109619 
109620 /*
109621 ** Run the parser on the given SQL string.  The parser structure is
109622 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
109623 ** then an and attempt is made to write an error message into
109624 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
109625 ** error message.
109626 */
109627 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
109628   int nErr = 0;                   /* Number of errors encountered */
109629   int i;                          /* Loop counter */
109630   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
109631   int tokenType;                  /* type of the next token */
109632   int lastTokenParsed = -1;       /* type of the previous token */
109633   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
109634   sqlite3 *db = pParse->db;       /* The database connection */
109635   int mxSqlLen;                   /* Max length of an SQL string */
109636 
109637 
109638   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
109639   if( db->activeVdbeCnt==0 ){
109640     db->u1.isInterrupted = 0;
109641   }
109642   pParse->rc = SQLITE_OK;
109643   pParse->zTail = zSql;
109644   i = 0;
109645   assert( pzErrMsg!=0 );
109646   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
109647   if( pEngine==0 ){
109648     db->mallocFailed = 1;
109649     return SQLITE_NOMEM;
109650   }
109651   assert( pParse->pNewTable==0 );
109652   assert( pParse->pNewTrigger==0 );
109653   assert( pParse->nVar==0 );
109654   assert( pParse->nzVar==0 );
109655   assert( pParse->azVar==0 );
109656   enableLookaside = db->lookaside.bEnabled;
109657   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
109658   while( !db->mallocFailed && zSql[i]!=0 ){
109659     assert( i>=0 );
109660     pParse->sLastToken.z = &zSql[i];
109661     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
109662     i += pParse->sLastToken.n;
109663     if( i>mxSqlLen ){
109664       pParse->rc = SQLITE_TOOBIG;
109665       break;
109666     }
109667     switch( tokenType ){
109668       case TK_SPACE: {
109669         if( db->u1.isInterrupted ){
109670           sqlite3ErrorMsg(pParse, "interrupt");
109671           pParse->rc = SQLITE_INTERRUPT;
109672           goto abort_parse;
109673         }
109674         break;
109675       }
109676       case TK_ILLEGAL: {
109677         sqlite3DbFree(db, *pzErrMsg);
109678         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
109679                         &pParse->sLastToken);
109680         nErr++;
109681         goto abort_parse;
109682       }
109683       case TK_SEMI: {
109684         pParse->zTail = &zSql[i];
109685         /* Fall thru into the default case */
109686       }
109687       default: {
109688         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
109689         lastTokenParsed = tokenType;
109690         if( pParse->rc!=SQLITE_OK ){
109691           goto abort_parse;
109692         }
109693         break;
109694       }
109695     }
109696   }
109697 abort_parse:
109698   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
109699     if( lastTokenParsed!=TK_SEMI ){
109700       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
109701       pParse->zTail = &zSql[i];
109702     }
109703     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
109704   }
109705 #ifdef YYTRACKMAXSTACKDEPTH
109706   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
109707       sqlite3ParserStackPeak(pEngine)
109708   );
109709 #endif /* YYDEBUG */
109710   sqlite3ParserFree(pEngine, sqlite3_free);
109711   db->lookaside.bEnabled = enableLookaside;
109712   if( db->mallocFailed ){
109713     pParse->rc = SQLITE_NOMEM;
109714   }
109715   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
109716     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
109717   }
109718   assert( pzErrMsg!=0 );
109719   if( pParse->zErrMsg ){
109720     *pzErrMsg = pParse->zErrMsg;
109721     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
109722     pParse->zErrMsg = 0;
109723     nErr++;
109724   }
109725   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
109726     sqlite3VdbeDelete(pParse->pVdbe);
109727     pParse->pVdbe = 0;
109728   }
109729 #ifndef SQLITE_OMIT_SHARED_CACHE
109730   if( pParse->nested==0 ){
109731     sqlite3DbFree(db, pParse->aTableLock);
109732     pParse->aTableLock = 0;
109733     pParse->nTableLock = 0;
109734   }
109735 #endif
109736 #ifndef SQLITE_OMIT_VIRTUALTABLE
109737   sqlite3_free(pParse->apVtabLock);
109738 #endif
109739 
109740   if( !IN_DECLARE_VTAB ){
109741     /* If the pParse->declareVtab flag is set, do not delete any table
109742     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
109743     ** will take responsibility for freeing the Table structure.
109744     */
109745     sqlite3DeleteTable(db, pParse->pNewTable);
109746   }
109747 
109748   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
109749   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
109750   sqlite3DbFree(db, pParse->azVar);
109751   sqlite3DbFree(db, pParse->aAlias);
109752   while( pParse->pAinc ){
109753     AutoincInfo *p = pParse->pAinc;
109754     pParse->pAinc = p->pNext;
109755     sqlite3DbFree(db, p);
109756   }
109757   while( pParse->pZombieTab ){
109758     Table *p = pParse->pZombieTab;
109759     pParse->pZombieTab = p->pNextZombie;
109760     sqlite3DeleteTable(db, p);
109761   }
109762   if( nErr>0 && pParse->rc==SQLITE_OK ){
109763     pParse->rc = SQLITE_ERROR;
109764   }
109765   return nErr;
109766 }
109767 
109768 /************** End of tokenize.c ********************************************/
109769 /************** Begin file complete.c ****************************************/
109770 /*
109771 ** 2001 September 15
109772 **
109773 ** The author disclaims copyright to this source code.  In place of
109774 ** a legal notice, here is a blessing:
109775 **
109776 **    May you do good and not evil.
109777 **    May you find forgiveness for yourself and forgive others.
109778 **    May you share freely, never taking more than you give.
109779 **
109780 *************************************************************************
109781 ** An tokenizer for SQL
109782 **
109783 ** This file contains C code that implements the sqlite3_complete() API.
109784 ** This code used to be part of the tokenizer.c source file.  But by
109785 ** separating it out, the code will be automatically omitted from
109786 ** static links that do not use it.
109787 */
109788 #ifndef SQLITE_OMIT_COMPLETE
109789 
109790 /*
109791 ** This is defined in tokenize.c.  We just have to import the definition.
109792 */
109793 #ifndef SQLITE_AMALGAMATION
109794 #ifdef SQLITE_ASCII
109795 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
109796 #endif
109797 #ifdef SQLITE_EBCDIC
109798 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
109799 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
109800 #endif
109801 #endif /* SQLITE_AMALGAMATION */
109802 
109803 
109804 /*
109805 ** Token types used by the sqlite3_complete() routine.  See the header
109806 ** comments on that procedure for additional information.
109807 */
109808 #define tkSEMI    0
109809 #define tkWS      1
109810 #define tkOTHER   2
109811 #ifndef SQLITE_OMIT_TRIGGER
109812 #define tkEXPLAIN 3
109813 #define tkCREATE  4
109814 #define tkTEMP    5
109815 #define tkTRIGGER 6
109816 #define tkEND     7
109817 #endif
109818 
109819 /*
109820 ** Return TRUE if the given SQL string ends in a semicolon.
109821 **
109822 ** Special handling is require for CREATE TRIGGER statements.
109823 ** Whenever the CREATE TRIGGER keywords are seen, the statement
109824 ** must end with ";END;".
109825 **
109826 ** This implementation uses a state machine with 8 states:
109827 **
109828 **   (0) INVALID   We have not yet seen a non-whitespace character.
109829 **
109830 **   (1) START     At the beginning or end of an SQL statement.  This routine
109831 **                 returns 1 if it ends in the START state and 0 if it ends
109832 **                 in any other state.
109833 **
109834 **   (2) NORMAL    We are in the middle of statement which ends with a single
109835 **                 semicolon.
109836 **
109837 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
109838 **                 a statement.
109839 **
109840 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
109841 **                 statement, possibly preceeded by EXPLAIN and/or followed by
109842 **                 TEMP or TEMPORARY
109843 **
109844 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
109845 **                 ended by a semicolon, the keyword END, and another semicolon.
109846 **
109847 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
109848 **                 the end of a trigger definition.
109849 **
109850 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
109851 **                 of a trigger difinition.
109852 **
109853 ** Transitions between states above are determined by tokens extracted
109854 ** from the input.  The following tokens are significant:
109855 **
109856 **   (0) tkSEMI      A semicolon.
109857 **   (1) tkWS        Whitespace.
109858 **   (2) tkOTHER     Any other SQL token.
109859 **   (3) tkEXPLAIN   The "explain" keyword.
109860 **   (4) tkCREATE    The "create" keyword.
109861 **   (5) tkTEMP      The "temp" or "temporary" keyword.
109862 **   (6) tkTRIGGER   The "trigger" keyword.
109863 **   (7) tkEND       The "end" keyword.
109864 **
109865 ** Whitespace never causes a state transition and is always ignored.
109866 ** This means that a SQL string of all whitespace is invalid.
109867 **
109868 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
109869 ** to recognize the end of a trigger can be omitted.  All we have to do
109870 ** is look for a semicolon that is not part of an string or comment.
109871 */
109872 SQLITE_API int sqlite3_complete(const char *zSql){
109873   u8 state = 0;   /* Current state, using numbers defined in header comment */
109874   u8 token;       /* Value of the next token */
109875 
109876 #ifndef SQLITE_OMIT_TRIGGER
109877   /* A complex statement machine used to detect the end of a CREATE TRIGGER
109878   ** statement.  This is the normal case.
109879   */
109880   static const u8 trans[8][8] = {
109881                      /* Token:                                                */
109882      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
109883      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
109884      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
109885      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
109886      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
109887      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
109888      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
109889      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
109890      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
109891   };
109892 #else
109893   /* If triggers are not supported by this compile then the statement machine
109894   ** used to detect the end of a statement is much simplier
109895   */
109896   static const u8 trans[3][3] = {
109897                      /* Token:           */
109898      /* State:       **  SEMI  WS  OTHER */
109899      /* 0 INVALID: */ {    1,  0,     2, },
109900      /* 1   START: */ {    1,  1,     2, },
109901      /* 2  NORMAL: */ {    1,  2,     2, },
109902   };
109903 #endif /* SQLITE_OMIT_TRIGGER */
109904 
109905   while( *zSql ){
109906     switch( *zSql ){
109907       case ';': {  /* A semicolon */
109908         token = tkSEMI;
109909         break;
109910       }
109911       case ' ':
109912       case '\r':
109913       case '\t':
109914       case '\n':
109915       case '\f': {  /* White space is ignored */
109916         token = tkWS;
109917         break;
109918       }
109919       case '/': {   /* C-style comments */
109920         if( zSql[1]!='*' ){
109921           token = tkOTHER;
109922           break;
109923         }
109924         zSql += 2;
109925         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
109926         if( zSql[0]==0 ) return 0;
109927         zSql++;
109928         token = tkWS;
109929         break;
109930       }
109931       case '-': {   /* SQL-style comments from "--" to end of line */
109932         if( zSql[1]!='-' ){
109933           token = tkOTHER;
109934           break;
109935         }
109936         while( *zSql && *zSql!='\n' ){ zSql++; }
109937         if( *zSql==0 ) return state==1;
109938         token = tkWS;
109939         break;
109940       }
109941       case '[': {   /* Microsoft-style identifiers in [...] */
109942         zSql++;
109943         while( *zSql && *zSql!=']' ){ zSql++; }
109944         if( *zSql==0 ) return 0;
109945         token = tkOTHER;
109946         break;
109947       }
109948       case '`':     /* Grave-accent quoted symbols used by MySQL */
109949       case '"':     /* single- and double-quoted strings */
109950       case '\'': {
109951         int c = *zSql;
109952         zSql++;
109953         while( *zSql && *zSql!=c ){ zSql++; }
109954         if( *zSql==0 ) return 0;
109955         token = tkOTHER;
109956         break;
109957       }
109958       default: {
109959 #ifdef SQLITE_EBCDIC
109960         unsigned char c;
109961 #endif
109962         if( IdChar((u8)*zSql) ){
109963           /* Keywords and unquoted identifiers */
109964           int nId;
109965           for(nId=1; IdChar(zSql[nId]); nId++){}
109966 #ifdef SQLITE_OMIT_TRIGGER
109967           token = tkOTHER;
109968 #else
109969           switch( *zSql ){
109970             case 'c': case 'C': {
109971               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
109972                 token = tkCREATE;
109973               }else{
109974                 token = tkOTHER;
109975               }
109976               break;
109977             }
109978             case 't': case 'T': {
109979               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
109980                 token = tkTRIGGER;
109981               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
109982                 token = tkTEMP;
109983               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
109984                 token = tkTEMP;
109985               }else{
109986                 token = tkOTHER;
109987               }
109988               break;
109989             }
109990             case 'e':  case 'E': {
109991               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
109992                 token = tkEND;
109993               }else
109994 #ifndef SQLITE_OMIT_EXPLAIN
109995               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
109996                 token = tkEXPLAIN;
109997               }else
109998 #endif
109999               {
110000                 token = tkOTHER;
110001               }
110002               break;
110003             }
110004             default: {
110005               token = tkOTHER;
110006               break;
110007             }
110008           }
110009 #endif /* SQLITE_OMIT_TRIGGER */
110010           zSql += nId-1;
110011         }else{
110012           /* Operators and special symbols */
110013           token = tkOTHER;
110014         }
110015         break;
110016       }
110017     }
110018     state = trans[state][token];
110019     zSql++;
110020   }
110021   return state==1;
110022 }
110023 
110024 #ifndef SQLITE_OMIT_UTF16
110025 /*
110026 ** This routine is the same as the sqlite3_complete() routine described
110027 ** above, except that the parameter is required to be UTF-16 encoded, not
110028 ** UTF-8.
110029 */
110030 SQLITE_API int sqlite3_complete16(const void *zSql){
110031   sqlite3_value *pVal;
110032   char const *zSql8;
110033   int rc = SQLITE_NOMEM;
110034 
110035 #ifndef SQLITE_OMIT_AUTOINIT
110036   rc = sqlite3_initialize();
110037   if( rc ) return rc;
110038 #endif
110039   pVal = sqlite3ValueNew(0);
110040   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
110041   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
110042   if( zSql8 ){
110043     rc = sqlite3_complete(zSql8);
110044   }else{
110045     rc = SQLITE_NOMEM;
110046   }
110047   sqlite3ValueFree(pVal);
110048   return sqlite3ApiExit(0, rc);
110049 }
110050 #endif /* SQLITE_OMIT_UTF16 */
110051 #endif /* SQLITE_OMIT_COMPLETE */
110052 
110053 /************** End of complete.c ********************************************/
110054 /************** Begin file main.c ********************************************/
110055 /*
110056 ** 2001 September 15
110057 **
110058 ** The author disclaims copyright to this source code.  In place of
110059 ** a legal notice, here is a blessing:
110060 **
110061 **    May you do good and not evil.
110062 **    May you find forgiveness for yourself and forgive others.
110063 **    May you share freely, never taking more than you give.
110064 **
110065 *************************************************************************
110066 ** Main file for the SQLite library.  The routines in this file
110067 ** implement the programmer interface to the library.  Routines in
110068 ** other files are for internal use by SQLite and should not be
110069 ** accessed by users of the library.
110070 */
110071 
110072 #ifdef SQLITE_ENABLE_FTS3
110073 /************** Include fts3.h in the middle of main.c ***********************/
110074 /************** Begin file fts3.h ********************************************/
110075 /*
110076 ** 2006 Oct 10
110077 **
110078 ** The author disclaims copyright to this source code.  In place of
110079 ** a legal notice, here is a blessing:
110080 **
110081 **    May you do good and not evil.
110082 **    May you find forgiveness for yourself and forgive others.
110083 **    May you share freely, never taking more than you give.
110084 **
110085 ******************************************************************************
110086 **
110087 ** This header file is used by programs that want to link against the
110088 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
110089 */
110090 
110091 #if 0
110092 extern "C" {
110093 #endif  /* __cplusplus */
110094 
110095 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
110096 
110097 #if 0
110098 }  /* extern "C" */
110099 #endif  /* __cplusplus */
110100 
110101 /************** End of fts3.h ************************************************/
110102 /************** Continuing where we left off in main.c ***********************/
110103 #endif
110104 #ifdef SQLITE_ENABLE_RTREE
110105 /************** Include rtree.h in the middle of main.c **********************/
110106 /************** Begin file rtree.h *******************************************/
110107 /*
110108 ** 2008 May 26
110109 **
110110 ** The author disclaims copyright to this source code.  In place of
110111 ** a legal notice, here is a blessing:
110112 **
110113 **    May you do good and not evil.
110114 **    May you find forgiveness for yourself and forgive others.
110115 **    May you share freely, never taking more than you give.
110116 **
110117 ******************************************************************************
110118 **
110119 ** This header file is used by programs that want to link against the
110120 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
110121 */
110122 
110123 #if 0
110124 extern "C" {
110125 #endif  /* __cplusplus */
110126 
110127 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
110128 
110129 #if 0
110130 }  /* extern "C" */
110131 #endif  /* __cplusplus */
110132 
110133 /************** End of rtree.h ***********************************************/
110134 /************** Continuing where we left off in main.c ***********************/
110135 #endif
110136 #ifdef SQLITE_ENABLE_ICU
110137 /************** Include sqliteicu.h in the middle of main.c ******************/
110138 /************** Begin file sqliteicu.h ***************************************/
110139 /*
110140 ** 2008 May 26
110141 **
110142 ** The author disclaims copyright to this source code.  In place of
110143 ** a legal notice, here is a blessing:
110144 **
110145 **    May you do good and not evil.
110146 **    May you find forgiveness for yourself and forgive others.
110147 **    May you share freely, never taking more than you give.
110148 **
110149 ******************************************************************************
110150 **
110151 ** This header file is used by programs that want to link against the
110152 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
110153 */
110154 
110155 #if 0
110156 extern "C" {
110157 #endif  /* __cplusplus */
110158 
110159 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
110160 
110161 #if 0
110162 }  /* extern "C" */
110163 #endif  /* __cplusplus */
110164 
110165 
110166 /************** End of sqliteicu.h *******************************************/
110167 /************** Continuing where we left off in main.c ***********************/
110168 #endif
110169 
110170 #ifndef SQLITE_AMALGAMATION
110171 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
110172 ** contains the text of SQLITE_VERSION macro.
110173 */
110174 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
110175 #endif
110176 
110177 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
110178 ** a pointer to the to the sqlite3_version[] string constant.
110179 */
110180 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
110181 
110182 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
110183 ** pointer to a string constant whose value is the same as the
110184 ** SQLITE_SOURCE_ID C preprocessor macro.
110185 */
110186 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
110187 
110188 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
110189 ** returns an integer equal to SQLITE_VERSION_NUMBER.
110190 */
110191 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
110192 
110193 /* IMPLEMENTATION-OF: R-54823-41343 The sqlite3_threadsafe() function returns
110194 ** zero if and only if SQLite was compiled mutexing code omitted due to
110195 ** the SQLITE_THREADSAFE compile-time option being set to 0.
110196 */
110197 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
110198 
110199 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
110200 /*
110201 ** If the following function pointer is not NULL and if
110202 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
110203 ** I/O active are written using this function.  These messages
110204 ** are intended for debugging activity only.
110205 */
110206 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
110207 #endif
110208 
110209 /*
110210 ** If the following global variable points to a string which is the
110211 ** name of a directory, then that directory will be used to store
110212 ** temporary files.
110213 **
110214 ** See also the "PRAGMA temp_store_directory" SQL command.
110215 */
110216 SQLITE_API char *sqlite3_temp_directory = 0;
110217 
110218 /*
110219 ** Initialize SQLite.
110220 **
110221 ** This routine must be called to initialize the memory allocation,
110222 ** VFS, and mutex subsystems prior to doing any serious work with
110223 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
110224 ** this routine will be called automatically by key routines such as
110225 ** sqlite3_open().
110226 **
110227 ** This routine is a no-op except on its very first call for the process,
110228 ** or for the first call after a call to sqlite3_shutdown.
110229 **
110230 ** The first thread to call this routine runs the initialization to
110231 ** completion.  If subsequent threads call this routine before the first
110232 ** thread has finished the initialization process, then the subsequent
110233 ** threads must block until the first thread finishes with the initialization.
110234 **
110235 ** The first thread might call this routine recursively.  Recursive
110236 ** calls to this routine should not block, of course.  Otherwise the
110237 ** initialization process would never complete.
110238 **
110239 ** Let X be the first thread to enter this routine.  Let Y be some other
110240 ** thread.  Then while the initial invocation of this routine by X is
110241 ** incomplete, it is required that:
110242 **
110243 **    *  Calls to this routine from Y must block until the outer-most
110244 **       call by X completes.
110245 **
110246 **    *  Recursive calls to this routine from thread X return immediately
110247 **       without blocking.
110248 */
110249 SQLITE_API int sqlite3_initialize(void){
110250   sqlite3_mutex *pMaster;                      /* The main static mutex */
110251   int rc;                                      /* Result code */
110252 
110253 #ifdef SQLITE_OMIT_WSD
110254   rc = sqlite3_wsd_init(4096, 24);
110255   if( rc!=SQLITE_OK ){
110256     return rc;
110257   }
110258 #endif
110259 
110260   /* If SQLite is already completely initialized, then this call
110261   ** to sqlite3_initialize() should be a no-op.  But the initialization
110262   ** must be complete.  So isInit must not be set until the very end
110263   ** of this routine.
110264   */
110265   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
110266 
110267   /* Make sure the mutex subsystem is initialized.  If unable to
110268   ** initialize the mutex subsystem, return early with the error.
110269   ** If the system is so sick that we are unable to allocate a mutex,
110270   ** there is not much SQLite is going to be able to do.
110271   **
110272   ** The mutex subsystem must take care of serializing its own
110273   ** initialization.
110274   */
110275   rc = sqlite3MutexInit();
110276   if( rc ) return rc;
110277 
110278   /* Initialize the malloc() system and the recursive pInitMutex mutex.
110279   ** This operation is protected by the STATIC_MASTER mutex.  Note that
110280   ** MutexAlloc() is called for a static mutex prior to initializing the
110281   ** malloc subsystem - this implies that the allocation of a static
110282   ** mutex must not require support from the malloc subsystem.
110283   */
110284   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
110285   sqlite3_mutex_enter(pMaster);
110286   sqlite3GlobalConfig.isMutexInit = 1;
110287   if( !sqlite3GlobalConfig.isMallocInit ){
110288     rc = sqlite3MallocInit();
110289   }
110290   if( rc==SQLITE_OK ){
110291     sqlite3GlobalConfig.isMallocInit = 1;
110292     if( !sqlite3GlobalConfig.pInitMutex ){
110293       sqlite3GlobalConfig.pInitMutex =
110294            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
110295       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
110296         rc = SQLITE_NOMEM;
110297       }
110298     }
110299   }
110300   if( rc==SQLITE_OK ){
110301     sqlite3GlobalConfig.nRefInitMutex++;
110302   }
110303   sqlite3_mutex_leave(pMaster);
110304 
110305   /* If rc is not SQLITE_OK at this point, then either the malloc
110306   ** subsystem could not be initialized or the system failed to allocate
110307   ** the pInitMutex mutex. Return an error in either case.  */
110308   if( rc!=SQLITE_OK ){
110309     return rc;
110310   }
110311 
110312   /* Do the rest of the initialization under the recursive mutex so
110313   ** that we will be able to handle recursive calls into
110314   ** sqlite3_initialize().  The recursive calls normally come through
110315   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
110316   ** recursive calls might also be possible.
110317   **
110318   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
110319   ** to the xInit method, so the xInit method need not be threadsafe.
110320   **
110321   ** The following mutex is what serializes access to the appdef pcache xInit
110322   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
110323   ** call to sqlite3PcacheInitialize().
110324   */
110325   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
110326   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
110327     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
110328     sqlite3GlobalConfig.inProgress = 1;
110329     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
110330     sqlite3RegisterGlobalFunctions();
110331     if( sqlite3GlobalConfig.isPCacheInit==0 ){
110332       rc = sqlite3PcacheInitialize();
110333     }
110334     if( rc==SQLITE_OK ){
110335       sqlite3GlobalConfig.isPCacheInit = 1;
110336       rc = sqlite3OsInit();
110337     }
110338     if( rc==SQLITE_OK ){
110339       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
110340           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
110341       sqlite3GlobalConfig.isInit = 1;
110342     }
110343     sqlite3GlobalConfig.inProgress = 0;
110344   }
110345   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
110346 
110347   /* Go back under the static mutex and clean up the recursive
110348   ** mutex to prevent a resource leak.
110349   */
110350   sqlite3_mutex_enter(pMaster);
110351   sqlite3GlobalConfig.nRefInitMutex--;
110352   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
110353     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
110354     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
110355     sqlite3GlobalConfig.pInitMutex = 0;
110356   }
110357   sqlite3_mutex_leave(pMaster);
110358 
110359   /* The following is just a sanity check to make sure SQLite has
110360   ** been compiled correctly.  It is important to run this code, but
110361   ** we don't want to run it too often and soak up CPU cycles for no
110362   ** reason.  So we run it once during initialization.
110363   */
110364 #ifndef NDEBUG
110365 #ifndef SQLITE_OMIT_FLOATING_POINT
110366   /* This section of code's only "output" is via assert() statements. */
110367   if ( rc==SQLITE_OK ){
110368     u64 x = (((u64)1)<<63)-1;
110369     double y;
110370     assert(sizeof(x)==8);
110371     assert(sizeof(x)==sizeof(y));
110372     memcpy(&y, &x, 8);
110373     assert( sqlite3IsNaN(y) );
110374   }
110375 #endif
110376 #endif
110377 
110378   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
110379   ** compile-time option.
110380   */
110381 #ifdef SQLITE_EXTRA_INIT
110382   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
110383     int SQLITE_EXTRA_INIT(void);
110384     rc = SQLITE_EXTRA_INIT();
110385   }
110386 #endif
110387 
110388   return rc;
110389 }
110390 
110391 /*
110392 ** Undo the effects of sqlite3_initialize().  Must not be called while
110393 ** there are outstanding database connections or memory allocations or
110394 ** while any part of SQLite is otherwise in use in any thread.  This
110395 ** routine is not threadsafe.  But it is safe to invoke this routine
110396 ** on when SQLite is already shut down.  If SQLite is already shut down
110397 ** when this routine is invoked, then this routine is a harmless no-op.
110398 */
110399 SQLITE_API int sqlite3_shutdown(void){
110400   if( sqlite3GlobalConfig.isInit ){
110401     sqlite3_os_end();
110402     sqlite3_reset_auto_extension();
110403     sqlite3GlobalConfig.isInit = 0;
110404   }
110405   if( sqlite3GlobalConfig.isPCacheInit ){
110406     sqlite3PcacheShutdown();
110407     sqlite3GlobalConfig.isPCacheInit = 0;
110408   }
110409   if( sqlite3GlobalConfig.isMallocInit ){
110410     sqlite3MallocEnd();
110411     sqlite3GlobalConfig.isMallocInit = 0;
110412   }
110413   if( sqlite3GlobalConfig.isMutexInit ){
110414     sqlite3MutexEnd();
110415     sqlite3GlobalConfig.isMutexInit = 0;
110416   }
110417 
110418   return SQLITE_OK;
110419 }
110420 
110421 /*
110422 ** This API allows applications to modify the global configuration of
110423 ** the SQLite library at run-time.
110424 **
110425 ** This routine should only be called when there are no outstanding
110426 ** database connections or memory allocations.  This routine is not
110427 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
110428 ** behavior.
110429 */
110430 SQLITE_API int sqlite3_config(int op, ...){
110431   va_list ap;
110432   int rc = SQLITE_OK;
110433 
110434   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
110435   ** the SQLite library is in use. */
110436   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
110437 
110438   va_start(ap, op);
110439   switch( op ){
110440 
110441     /* Mutex configuration options are only available in a threadsafe
110442     ** compile.
110443     */
110444 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
110445     case SQLITE_CONFIG_SINGLETHREAD: {
110446       /* Disable all mutexing */
110447       sqlite3GlobalConfig.bCoreMutex = 0;
110448       sqlite3GlobalConfig.bFullMutex = 0;
110449       break;
110450     }
110451     case SQLITE_CONFIG_MULTITHREAD: {
110452       /* Disable mutexing of database connections */
110453       /* Enable mutexing of core data structures */
110454       sqlite3GlobalConfig.bCoreMutex = 1;
110455       sqlite3GlobalConfig.bFullMutex = 0;
110456       break;
110457     }
110458     case SQLITE_CONFIG_SERIALIZED: {
110459       /* Enable all mutexing */
110460       sqlite3GlobalConfig.bCoreMutex = 1;
110461       sqlite3GlobalConfig.bFullMutex = 1;
110462       break;
110463     }
110464     case SQLITE_CONFIG_MUTEX: {
110465       /* Specify an alternative mutex implementation */
110466       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
110467       break;
110468     }
110469     case SQLITE_CONFIG_GETMUTEX: {
110470       /* Retrieve the current mutex implementation */
110471       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
110472       break;
110473     }
110474 #endif
110475 
110476 
110477     case SQLITE_CONFIG_MALLOC: {
110478       /* Specify an alternative malloc implementation */
110479       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
110480       break;
110481     }
110482     case SQLITE_CONFIG_GETMALLOC: {
110483       /* Retrieve the current malloc() implementation */
110484       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
110485       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
110486       break;
110487     }
110488     case SQLITE_CONFIG_MEMSTATUS: {
110489       /* Enable or disable the malloc status collection */
110490       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
110491       break;
110492     }
110493     case SQLITE_CONFIG_SCRATCH: {
110494       /* Designate a buffer for scratch memory space */
110495       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
110496       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
110497       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
110498       break;
110499     }
110500     case SQLITE_CONFIG_PAGECACHE: {
110501       /* Designate a buffer for page cache memory space */
110502       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
110503       sqlite3GlobalConfig.szPage = va_arg(ap, int);
110504       sqlite3GlobalConfig.nPage = va_arg(ap, int);
110505       break;
110506     }
110507 
110508     case SQLITE_CONFIG_PCACHE: {
110509       /* Specify an alternative page cache implementation */
110510       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
110511       break;
110512     }
110513 
110514     case SQLITE_CONFIG_GETPCACHE: {
110515       if( sqlite3GlobalConfig.pcache.xInit==0 ){
110516         sqlite3PCacheSetDefault();
110517       }
110518       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
110519       break;
110520     }
110521 
110522 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
110523     case SQLITE_CONFIG_HEAP: {
110524       /* Designate a buffer for heap memory space */
110525       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
110526       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
110527       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
110528 
110529       if( sqlite3GlobalConfig.mnReq<1 ){
110530         sqlite3GlobalConfig.mnReq = 1;
110531       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
110532         /* cap min request size at 2^12 */
110533         sqlite3GlobalConfig.mnReq = (1<<12);
110534       }
110535 
110536       if( sqlite3GlobalConfig.pHeap==0 ){
110537         /* If the heap pointer is NULL, then restore the malloc implementation
110538         ** back to NULL pointers too.  This will cause the malloc to go
110539         ** back to its default implementation when sqlite3_initialize() is
110540         ** run.
110541         */
110542         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
110543       }else{
110544         /* The heap pointer is not NULL, then install one of the
110545         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
110546         ** ENABLE_MEMSYS5 is defined, return an error.
110547         */
110548 #ifdef SQLITE_ENABLE_MEMSYS3
110549         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
110550 #endif
110551 #ifdef SQLITE_ENABLE_MEMSYS5
110552         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
110553 #endif
110554       }
110555       break;
110556     }
110557 #endif
110558 
110559     case SQLITE_CONFIG_LOOKASIDE: {
110560       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
110561       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
110562       break;
110563     }
110564 
110565     /* Record a pointer to the logger funcction and its first argument.
110566     ** The default is NULL.  Logging is disabled if the function pointer is
110567     ** NULL.
110568     */
110569     case SQLITE_CONFIG_LOG: {
110570       /* MSVC is picky about pulling func ptrs from va lists.
110571       ** http://support.microsoft.com/kb/47961
110572       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
110573       */
110574       typedef void(*LOGFUNC_t)(void*,int,const char*);
110575       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
110576       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
110577       break;
110578     }
110579 
110580     case SQLITE_CONFIG_URI: {
110581       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
110582       break;
110583     }
110584 
110585     default: {
110586       rc = SQLITE_ERROR;
110587       break;
110588     }
110589   }
110590   va_end(ap);
110591   return rc;
110592 }
110593 
110594 /*
110595 ** Set up the lookaside buffers for a database connection.
110596 ** Return SQLITE_OK on success.
110597 ** If lookaside is already active, return SQLITE_BUSY.
110598 **
110599 ** The sz parameter is the number of bytes in each lookaside slot.
110600 ** The cnt parameter is the number of slots.  If pStart is NULL the
110601 ** space for the lookaside memory is obtained from sqlite3_malloc().
110602 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
110603 ** the lookaside memory.
110604 */
110605 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
110606   void *pStart;
110607   if( db->lookaside.nOut ){
110608     return SQLITE_BUSY;
110609   }
110610   /* Free any existing lookaside buffer for this handle before
110611   ** allocating a new one so we don't have to have space for
110612   ** both at the same time.
110613   */
110614   if( db->lookaside.bMalloced ){
110615     sqlite3_free(db->lookaside.pStart);
110616   }
110617   /* The size of a lookaside slot needs to be larger than a pointer
110618   ** to be useful.
110619   */
110620   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
110621   if( cnt<0 ) cnt = 0;
110622   if( sz==0 || cnt==0 ){
110623     sz = 0;
110624     pStart = 0;
110625   }else if( pBuf==0 ){
110626     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
110627     sqlite3BeginBenignMalloc();
110628     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
110629     sqlite3EndBenignMalloc();
110630   }else{
110631     sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
110632     pStart = pBuf;
110633   }
110634   db->lookaside.pStart = pStart;
110635   db->lookaside.pFree = 0;
110636   db->lookaside.sz = (u16)sz;
110637   if( pStart ){
110638     int i;
110639     LookasideSlot *p;
110640     assert( sz > (int)sizeof(LookasideSlot*) );
110641     p = (LookasideSlot*)pStart;
110642     for(i=cnt-1; i>=0; i--){
110643       p->pNext = db->lookaside.pFree;
110644       db->lookaside.pFree = p;
110645       p = (LookasideSlot*)&((u8*)p)[sz];
110646     }
110647     db->lookaside.pEnd = p;
110648     db->lookaside.bEnabled = 1;
110649     db->lookaside.bMalloced = pBuf==0 ?1:0;
110650   }else{
110651     db->lookaside.pEnd = 0;
110652     db->lookaside.bEnabled = 0;
110653     db->lookaside.bMalloced = 0;
110654   }
110655   return SQLITE_OK;
110656 }
110657 
110658 /*
110659 ** Return the mutex associated with a database connection.
110660 */
110661 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
110662   return db->mutex;
110663 }
110664 
110665 /*
110666 ** Configuration settings for an individual database connection
110667 */
110668 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
110669   va_list ap;
110670   int rc;
110671   va_start(ap, op);
110672   switch( op ){
110673     case SQLITE_DBCONFIG_LOOKASIDE: {
110674       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
110675       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
110676       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
110677       rc = setupLookaside(db, pBuf, sz, cnt);
110678       break;
110679     }
110680     default: {
110681       static const struct {
110682         int op;      /* The opcode */
110683         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
110684       } aFlagOp[] = {
110685         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
110686         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
110687       };
110688       unsigned int i;
110689       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
110690       for(i=0; i<ArraySize(aFlagOp); i++){
110691         if( aFlagOp[i].op==op ){
110692           int onoff = va_arg(ap, int);
110693           int *pRes = va_arg(ap, int*);
110694           int oldFlags = db->flags;
110695           if( onoff>0 ){
110696             db->flags |= aFlagOp[i].mask;
110697           }else if( onoff==0 ){
110698             db->flags &= ~aFlagOp[i].mask;
110699           }
110700           if( oldFlags!=db->flags ){
110701             sqlite3ExpirePreparedStatements(db);
110702           }
110703           if( pRes ){
110704             *pRes = (db->flags & aFlagOp[i].mask)!=0;
110705           }
110706           rc = SQLITE_OK;
110707           break;
110708         }
110709       }
110710       break;
110711     }
110712   }
110713   va_end(ap);
110714   return rc;
110715 }
110716 
110717 
110718 /*
110719 ** Return true if the buffer z[0..n-1] contains all spaces.
110720 */
110721 static int allSpaces(const char *z, int n){
110722   while( n>0 && z[n-1]==' ' ){ n--; }
110723   return n==0;
110724 }
110725 
110726 /*
110727 ** This is the default collating function named "BINARY" which is always
110728 ** available.
110729 **
110730 ** If the padFlag argument is not NULL then space padding at the end
110731 ** of strings is ignored.  This implements the RTRIM collation.
110732 */
110733 static int binCollFunc(
110734   void *padFlag,
110735   int nKey1, const void *pKey1,
110736   int nKey2, const void *pKey2
110737 ){
110738   int rc, n;
110739   n = nKey1<nKey2 ? nKey1 : nKey2;
110740   rc = memcmp(pKey1, pKey2, n);
110741   if( rc==0 ){
110742     if( padFlag
110743      && allSpaces(((char*)pKey1)+n, nKey1-n)
110744      && allSpaces(((char*)pKey2)+n, nKey2-n)
110745     ){
110746       /* Leave rc unchanged at 0 */
110747     }else{
110748       rc = nKey1 - nKey2;
110749     }
110750   }
110751   return rc;
110752 }
110753 
110754 /*
110755 ** Another built-in collating sequence: NOCASE.
110756 **
110757 ** This collating sequence is intended to be used for "case independant
110758 ** comparison". SQLite's knowledge of upper and lower case equivalents
110759 ** extends only to the 26 characters used in the English language.
110760 **
110761 ** At the moment there is only a UTF-8 implementation.
110762 */
110763 static int nocaseCollatingFunc(
110764   void *NotUsed,
110765   int nKey1, const void *pKey1,
110766   int nKey2, const void *pKey2
110767 ){
110768   int r = sqlite3StrNICmp(
110769       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
110770   UNUSED_PARAMETER(NotUsed);
110771   if( 0==r ){
110772     r = nKey1-nKey2;
110773   }
110774   return r;
110775 }
110776 
110777 /*
110778 ** Return the ROWID of the most recent insert
110779 */
110780 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
110781   return db->lastRowid;
110782 }
110783 
110784 /*
110785 ** Return the number of changes in the most recent call to sqlite3_exec().
110786 */
110787 SQLITE_API int sqlite3_changes(sqlite3 *db){
110788   return db->nChange;
110789 }
110790 
110791 /*
110792 ** Return the number of changes since the database handle was opened.
110793 */
110794 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
110795   return db->nTotalChange;
110796 }
110797 
110798 /*
110799 ** Close all open savepoints. This function only manipulates fields of the
110800 ** database handle object, it does not close any savepoints that may be open
110801 ** at the b-tree/pager level.
110802 */
110803 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
110804   while( db->pSavepoint ){
110805     Savepoint *pTmp = db->pSavepoint;
110806     db->pSavepoint = pTmp->pNext;
110807     sqlite3DbFree(db, pTmp);
110808   }
110809   db->nSavepoint = 0;
110810   db->nStatement = 0;
110811   db->isTransactionSavepoint = 0;
110812 }
110813 
110814 /*
110815 ** Invoke the destructor function associated with FuncDef p, if any. Except,
110816 ** if this is not the last copy of the function, do not invoke it. Multiple
110817 ** copies of a single function are created when create_function() is called
110818 ** with SQLITE_ANY as the encoding.
110819 */
110820 static void functionDestroy(sqlite3 *db, FuncDef *p){
110821   FuncDestructor *pDestructor = p->pDestructor;
110822   if( pDestructor ){
110823     pDestructor->nRef--;
110824     if( pDestructor->nRef==0 ){
110825       pDestructor->xDestroy(pDestructor->pUserData);
110826       sqlite3DbFree(db, pDestructor);
110827     }
110828   }
110829 }
110830 
110831 /*
110832 ** Close an existing SQLite database
110833 */
110834 SQLITE_API int sqlite3_close(sqlite3 *db){
110835   HashElem *i;                    /* Hash table iterator */
110836   int j;
110837 
110838   if( !db ){
110839     return SQLITE_OK;
110840   }
110841   if( !sqlite3SafetyCheckSickOrOk(db) ){
110842     return SQLITE_MISUSE_BKPT;
110843   }
110844   sqlite3_mutex_enter(db->mutex);
110845 
110846   /* Force xDestroy calls on all virtual tables */
110847   sqlite3ResetInternalSchema(db, -1);
110848 
110849   /* If a transaction is open, the ResetInternalSchema() call above
110850   ** will not have called the xDisconnect() method on any virtual
110851   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
110852   ** call will do so. We need to do this before the check for active
110853   ** SQL statements below, as the v-table implementation may be storing
110854   ** some prepared statements internally.
110855   */
110856   sqlite3VtabRollback(db);
110857 
110858   /* If there are any outstanding VMs, return SQLITE_BUSY. */
110859   if( db->pVdbe ){
110860     sqlite3Error(db, SQLITE_BUSY,
110861         "unable to close due to unfinalised statements");
110862     sqlite3_mutex_leave(db->mutex);
110863     return SQLITE_BUSY;
110864   }
110865   assert( sqlite3SafetyCheckSickOrOk(db) );
110866 
110867   for(j=0; j<db->nDb; j++){
110868     Btree *pBt = db->aDb[j].pBt;
110869     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
110870       sqlite3Error(db, SQLITE_BUSY,
110871           "unable to close due to unfinished backup operation");
110872       sqlite3_mutex_leave(db->mutex);
110873       return SQLITE_BUSY;
110874     }
110875   }
110876 
110877   /* Free any outstanding Savepoint structures. */
110878   sqlite3CloseSavepoints(db);
110879 
110880   for(j=0; j<db->nDb; j++){
110881     struct Db *pDb = &db->aDb[j];
110882     if( pDb->pBt ){
110883       sqlite3BtreeClose(pDb->pBt);
110884       pDb->pBt = 0;
110885       if( j!=1 ){
110886         pDb->pSchema = 0;
110887       }
110888     }
110889   }
110890   sqlite3ResetInternalSchema(db, -1);
110891 
110892   /* Tell the code in notify.c that the connection no longer holds any
110893   ** locks and does not require any further unlock-notify callbacks.
110894   */
110895   sqlite3ConnectionClosed(db);
110896 
110897   assert( db->nDb<=2 );
110898   assert( db->aDb==db->aDbStatic );
110899   for(j=0; j<ArraySize(db->aFunc.a); j++){
110900     FuncDef *pNext, *pHash, *p;
110901     for(p=db->aFunc.a[j]; p; p=pHash){
110902       pHash = p->pHash;
110903       while( p ){
110904         functionDestroy(db, p);
110905         pNext = p->pNext;
110906         sqlite3DbFree(db, p);
110907         p = pNext;
110908       }
110909     }
110910   }
110911   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
110912     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
110913     /* Invoke any destructors registered for collation sequence user data. */
110914     for(j=0; j<3; j++){
110915       if( pColl[j].xDel ){
110916         pColl[j].xDel(pColl[j].pUser);
110917       }
110918     }
110919     sqlite3DbFree(db, pColl);
110920   }
110921   sqlite3HashClear(&db->aCollSeq);
110922 #ifndef SQLITE_OMIT_VIRTUALTABLE
110923   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
110924     Module *pMod = (Module *)sqliteHashData(i);
110925     if( pMod->xDestroy ){
110926       pMod->xDestroy(pMod->pAux);
110927     }
110928     sqlite3DbFree(db, pMod);
110929   }
110930   sqlite3HashClear(&db->aModule);
110931 #endif
110932 
110933   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
110934   if( db->pErr ){
110935     sqlite3ValueFree(db->pErr);
110936   }
110937   sqlite3CloseExtensions(db);
110938 
110939   db->magic = SQLITE_MAGIC_ERROR;
110940 
110941   /* The temp-database schema is allocated differently from the other schema
110942   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
110943   ** So it needs to be freed here. Todo: Why not roll the temp schema into
110944   ** the same sqliteMalloc() as the one that allocates the database
110945   ** structure?
110946   */
110947   sqlite3DbFree(db, db->aDb[1].pSchema);
110948   sqlite3_mutex_leave(db->mutex);
110949   db->magic = SQLITE_MAGIC_CLOSED;
110950   sqlite3_mutex_free(db->mutex);
110951   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
110952   if( db->lookaside.bMalloced ){
110953     sqlite3_free(db->lookaside.pStart);
110954   }
110955   sqlite3_free(db);
110956   return SQLITE_OK;
110957 }
110958 
110959 /*
110960 ** Rollback all database files.
110961 */
110962 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
110963   int i;
110964   int inTrans = 0;
110965   assert( sqlite3_mutex_held(db->mutex) );
110966   sqlite3BeginBenignMalloc();
110967   for(i=0; i<db->nDb; i++){
110968     if( db->aDb[i].pBt ){
110969       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
110970         inTrans = 1;
110971       }
110972       sqlite3BtreeRollback(db->aDb[i].pBt);
110973       db->aDb[i].inTrans = 0;
110974     }
110975   }
110976   sqlite3VtabRollback(db);
110977   sqlite3EndBenignMalloc();
110978 
110979   if( db->flags&SQLITE_InternChanges ){
110980     sqlite3ExpirePreparedStatements(db);
110981     sqlite3ResetInternalSchema(db, -1);
110982   }
110983 
110984   /* Any deferred constraint violations have now been resolved. */
110985   db->nDeferredCons = 0;
110986 
110987   /* If one has been configured, invoke the rollback-hook callback */
110988   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
110989     db->xRollbackCallback(db->pRollbackArg);
110990   }
110991 }
110992 
110993 /*
110994 ** Return a static string that describes the kind of error specified in the
110995 ** argument.
110996 */
110997 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
110998   static const char* const aMsg[] = {
110999     /* SQLITE_OK          */ "not an error",
111000     /* SQLITE_ERROR       */ "SQL logic error or missing database",
111001     /* SQLITE_INTERNAL    */ 0,
111002     /* SQLITE_PERM        */ "access permission denied",
111003     /* SQLITE_ABORT       */ "callback requested query abort",
111004     /* SQLITE_BUSY        */ "database is locked",
111005     /* SQLITE_LOCKED      */ "database table is locked",
111006     /* SQLITE_NOMEM       */ "out of memory",
111007     /* SQLITE_READONLY    */ "attempt to write a readonly database",
111008     /* SQLITE_INTERRUPT   */ "interrupted",
111009     /* SQLITE_IOERR       */ "disk I/O error",
111010     /* SQLITE_CORRUPT     */ "database disk image is malformed",
111011     /* SQLITE_NOTFOUND    */ "unknown operation",
111012     /* SQLITE_FULL        */ "database or disk is full",
111013     /* SQLITE_CANTOPEN    */ "unable to open database file",
111014     /* SQLITE_PROTOCOL    */ "locking protocol",
111015     /* SQLITE_EMPTY       */ "table contains no data",
111016     /* SQLITE_SCHEMA      */ "database schema has changed",
111017     /* SQLITE_TOOBIG      */ "string or blob too big",
111018     /* SQLITE_CONSTRAINT  */ "constraint failed",
111019     /* SQLITE_MISMATCH    */ "datatype mismatch",
111020     /* SQLITE_MISUSE      */ "library routine called out of sequence",
111021     /* SQLITE_NOLFS       */ "large file support is disabled",
111022     /* SQLITE_AUTH        */ "authorization denied",
111023     /* SQLITE_FORMAT      */ "auxiliary database format error",
111024     /* SQLITE_RANGE       */ "bind or column index out of range",
111025     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
111026   };
111027   rc &= 0xff;
111028   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
111029     return aMsg[rc];
111030   }else{
111031     return "unknown error";
111032   }
111033 }
111034 
111035 /*
111036 ** This routine implements a busy callback that sleeps and tries
111037 ** again until a timeout value is reached.  The timeout value is
111038 ** an integer number of milliseconds passed in as the first
111039 ** argument.
111040 */
111041 static int sqliteDefaultBusyCallback(
111042  void *ptr,               /* Database connection */
111043  int count                /* Number of times table has been busy */
111044 ){
111045 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
111046   static const u8 delays[] =
111047      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
111048   static const u8 totals[] =
111049      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
111050 # define NDELAY ArraySize(delays)
111051   sqlite3 *db = (sqlite3 *)ptr;
111052   int timeout = db->busyTimeout;
111053   int delay, prior;
111054 
111055   assert( count>=0 );
111056   if( count < NDELAY ){
111057     delay = delays[count];
111058     prior = totals[count];
111059   }else{
111060     delay = delays[NDELAY-1];
111061     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
111062   }
111063   if( prior + delay > timeout ){
111064     delay = timeout - prior;
111065     if( delay<=0 ) return 0;
111066   }
111067   sqlite3OsSleep(db->pVfs, delay*1000);
111068   return 1;
111069 #else
111070   sqlite3 *db = (sqlite3 *)ptr;
111071   int timeout = ((sqlite3 *)ptr)->busyTimeout;
111072   if( (count+1)*1000 > timeout ){
111073     return 0;
111074   }
111075   sqlite3OsSleep(db->pVfs, 1000000);
111076   return 1;
111077 #endif
111078 }
111079 
111080 /*
111081 ** Invoke the given busy handler.
111082 **
111083 ** This routine is called when an operation failed with a lock.
111084 ** If this routine returns non-zero, the lock is retried.  If it
111085 ** returns 0, the operation aborts with an SQLITE_BUSY error.
111086 */
111087 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
111088   int rc;
111089   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
111090   rc = p->xFunc(p->pArg, p->nBusy);
111091   if( rc==0 ){
111092     p->nBusy = -1;
111093   }else{
111094     p->nBusy++;
111095   }
111096   return rc;
111097 }
111098 
111099 /*
111100 ** This routine sets the busy callback for an Sqlite database to the
111101 ** given callback function with the given argument.
111102 */
111103 SQLITE_API int sqlite3_busy_handler(
111104   sqlite3 *db,
111105   int (*xBusy)(void*,int),
111106   void *pArg
111107 ){
111108   sqlite3_mutex_enter(db->mutex);
111109   db->busyHandler.xFunc = xBusy;
111110   db->busyHandler.pArg = pArg;
111111   db->busyHandler.nBusy = 0;
111112   sqlite3_mutex_leave(db->mutex);
111113   return SQLITE_OK;
111114 }
111115 
111116 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
111117 /*
111118 ** This routine sets the progress callback for an Sqlite database to the
111119 ** given callback function with the given argument. The progress callback will
111120 ** be invoked every nOps opcodes.
111121 */
111122 SQLITE_API void sqlite3_progress_handler(
111123   sqlite3 *db,
111124   int nOps,
111125   int (*xProgress)(void*),
111126   void *pArg
111127 ){
111128   sqlite3_mutex_enter(db->mutex);
111129   if( nOps>0 ){
111130     db->xProgress = xProgress;
111131     db->nProgressOps = nOps;
111132     db->pProgressArg = pArg;
111133   }else{
111134     db->xProgress = 0;
111135     db->nProgressOps = 0;
111136     db->pProgressArg = 0;
111137   }
111138   sqlite3_mutex_leave(db->mutex);
111139 }
111140 #endif
111141 
111142 
111143 /*
111144 ** This routine installs a default busy handler that waits for the
111145 ** specified number of milliseconds before returning 0.
111146 */
111147 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
111148   if( ms>0 ){
111149     db->busyTimeout = ms;
111150     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
111151   }else{
111152     sqlite3_busy_handler(db, 0, 0);
111153   }
111154   return SQLITE_OK;
111155 }
111156 
111157 /*
111158 ** Cause any pending operation to stop at its earliest opportunity.
111159 */
111160 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
111161   db->u1.isInterrupted = 1;
111162 }
111163 
111164 
111165 /*
111166 ** This function is exactly the same as sqlite3_create_function(), except
111167 ** that it is designed to be called by internal code. The difference is
111168 ** that if a malloc() fails in sqlite3_create_function(), an error code
111169 ** is returned and the mallocFailed flag cleared.
111170 */
111171 SQLITE_PRIVATE int sqlite3CreateFunc(
111172   sqlite3 *db,
111173   const char *zFunctionName,
111174   int nArg,
111175   int enc,
111176   void *pUserData,
111177   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111178   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111179   void (*xFinal)(sqlite3_context*),
111180   FuncDestructor *pDestructor
111181 ){
111182   FuncDef *p;
111183   int nName;
111184 
111185   assert( sqlite3_mutex_held(db->mutex) );
111186   if( zFunctionName==0 ||
111187       (xFunc && (xFinal || xStep)) ||
111188       (!xFunc && (xFinal && !xStep)) ||
111189       (!xFunc && (!xFinal && xStep)) ||
111190       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
111191       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
111192     return SQLITE_MISUSE_BKPT;
111193   }
111194 
111195 #ifndef SQLITE_OMIT_UTF16
111196   /* If SQLITE_UTF16 is specified as the encoding type, transform this
111197   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
111198   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
111199   **
111200   ** If SQLITE_ANY is specified, add three versions of the function
111201   ** to the hash table.
111202   */
111203   if( enc==SQLITE_UTF16 ){
111204     enc = SQLITE_UTF16NATIVE;
111205   }else if( enc==SQLITE_ANY ){
111206     int rc;
111207     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
111208          pUserData, xFunc, xStep, xFinal, pDestructor);
111209     if( rc==SQLITE_OK ){
111210       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
111211           pUserData, xFunc, xStep, xFinal, pDestructor);
111212     }
111213     if( rc!=SQLITE_OK ){
111214       return rc;
111215     }
111216     enc = SQLITE_UTF16BE;
111217   }
111218 #else
111219   enc = SQLITE_UTF8;
111220 #endif
111221 
111222   /* Check if an existing function is being overridden or deleted. If so,
111223   ** and there are active VMs, then return SQLITE_BUSY. If a function
111224   ** is being overridden/deleted but there are no active VMs, allow the
111225   ** operation to continue but invalidate all precompiled statements.
111226   */
111227   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
111228   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
111229     if( db->activeVdbeCnt ){
111230       sqlite3Error(db, SQLITE_BUSY,
111231         "unable to delete/modify user-function due to active statements");
111232       assert( !db->mallocFailed );
111233       return SQLITE_BUSY;
111234     }else{
111235       sqlite3ExpirePreparedStatements(db);
111236     }
111237   }
111238 
111239   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
111240   assert(p || db->mallocFailed);
111241   if( !p ){
111242     return SQLITE_NOMEM;
111243   }
111244 
111245   /* If an older version of the function with a configured destructor is
111246   ** being replaced invoke the destructor function here. */
111247   functionDestroy(db, p);
111248 
111249   if( pDestructor ){
111250     pDestructor->nRef++;
111251   }
111252   p->pDestructor = pDestructor;
111253   p->flags = 0;
111254   p->xFunc = xFunc;
111255   p->xStep = xStep;
111256   p->xFinalize = xFinal;
111257   p->pUserData = pUserData;
111258   p->nArg = (u16)nArg;
111259   return SQLITE_OK;
111260 }
111261 
111262 /*
111263 ** Create new user functions.
111264 */
111265 SQLITE_API int sqlite3_create_function(
111266   sqlite3 *db,
111267   const char *zFunc,
111268   int nArg,
111269   int enc,
111270   void *p,
111271   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111272   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111273   void (*xFinal)(sqlite3_context*)
111274 ){
111275   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
111276                                     xFinal, 0);
111277 }
111278 
111279 SQLITE_API int sqlite3_create_function_v2(
111280   sqlite3 *db,
111281   const char *zFunc,
111282   int nArg,
111283   int enc,
111284   void *p,
111285   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
111286   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
111287   void (*xFinal)(sqlite3_context*),
111288   void (*xDestroy)(void *)
111289 ){
111290   int rc = SQLITE_ERROR;
111291   FuncDestructor *pArg = 0;
111292   sqlite3_mutex_enter(db->mutex);
111293   if( xDestroy ){
111294     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
111295     if( !pArg ){
111296       xDestroy(p);
111297       goto out;
111298     }
111299     pArg->xDestroy = xDestroy;
111300     pArg->pUserData = p;
111301   }
111302   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
111303   if( pArg && pArg->nRef==0 ){
111304     assert( rc!=SQLITE_OK );
111305     xDestroy(p);
111306     sqlite3DbFree(db, pArg);
111307   }
111308 
111309  out:
111310   rc = sqlite3ApiExit(db, rc);
111311   sqlite3_mutex_leave(db->mutex);
111312   return rc;
111313 }
111314 
111315 #ifndef SQLITE_OMIT_UTF16
111316 SQLITE_API int sqlite3_create_function16(
111317   sqlite3 *db,
111318   const void *zFunctionName,
111319   int nArg,
111320   int eTextRep,
111321   void *p,
111322   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
111323   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
111324   void (*xFinal)(sqlite3_context*)
111325 ){
111326   int rc;
111327   char *zFunc8;
111328   sqlite3_mutex_enter(db->mutex);
111329   assert( !db->mallocFailed );
111330   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
111331   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
111332   sqlite3DbFree(db, zFunc8);
111333   rc = sqlite3ApiExit(db, rc);
111334   sqlite3_mutex_leave(db->mutex);
111335   return rc;
111336 }
111337 #endif
111338 
111339 
111340 /*
111341 ** Declare that a function has been overloaded by a virtual table.
111342 **
111343 ** If the function already exists as a regular global function, then
111344 ** this routine is a no-op.  If the function does not exist, then create
111345 ** a new one that always throws a run-time error.
111346 **
111347 ** When virtual tables intend to provide an overloaded function, they
111348 ** should call this routine to make sure the global function exists.
111349 ** A global function must exist in order for name resolution to work
111350 ** properly.
111351 */
111352 SQLITE_API int sqlite3_overload_function(
111353   sqlite3 *db,
111354   const char *zName,
111355   int nArg
111356 ){
111357   int nName = sqlite3Strlen30(zName);
111358   int rc;
111359   sqlite3_mutex_enter(db->mutex);
111360   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
111361     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
111362                       0, sqlite3InvalidFunction, 0, 0, 0);
111363   }
111364   rc = sqlite3ApiExit(db, SQLITE_OK);
111365   sqlite3_mutex_leave(db->mutex);
111366   return rc;
111367 }
111368 
111369 #ifndef SQLITE_OMIT_TRACE
111370 /*
111371 ** Register a trace function.  The pArg from the previously registered trace
111372 ** is returned.
111373 **
111374 ** A NULL trace function means that no tracing is executes.  A non-NULL
111375 ** trace is a pointer to a function that is invoked at the start of each
111376 ** SQL statement.
111377 */
111378 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
111379   void *pOld;
111380   sqlite3_mutex_enter(db->mutex);
111381   pOld = db->pTraceArg;
111382   db->xTrace = xTrace;
111383   db->pTraceArg = pArg;
111384   sqlite3_mutex_leave(db->mutex);
111385   return pOld;
111386 }
111387 /*
111388 ** Register a profile function.  The pArg from the previously registered
111389 ** profile function is returned.
111390 **
111391 ** A NULL profile function means that no profiling is executes.  A non-NULL
111392 ** profile is a pointer to a function that is invoked at the conclusion of
111393 ** each SQL statement that is run.
111394 */
111395 SQLITE_API void *sqlite3_profile(
111396   sqlite3 *db,
111397   void (*xProfile)(void*,const char*,sqlite_uint64),
111398   void *pArg
111399 ){
111400   void *pOld;
111401   sqlite3_mutex_enter(db->mutex);
111402   pOld = db->pProfileArg;
111403   db->xProfile = xProfile;
111404   db->pProfileArg = pArg;
111405   sqlite3_mutex_leave(db->mutex);
111406   return pOld;
111407 }
111408 #endif /* SQLITE_OMIT_TRACE */
111409 
111410 /*** EXPERIMENTAL ***
111411 **
111412 ** Register a function to be invoked when a transaction comments.
111413 ** If the invoked function returns non-zero, then the commit becomes a
111414 ** rollback.
111415 */
111416 SQLITE_API void *sqlite3_commit_hook(
111417   sqlite3 *db,              /* Attach the hook to this database */
111418   int (*xCallback)(void*),  /* Function to invoke on each commit */
111419   void *pArg                /* Argument to the function */
111420 ){
111421   void *pOld;
111422   sqlite3_mutex_enter(db->mutex);
111423   pOld = db->pCommitArg;
111424   db->xCommitCallback = xCallback;
111425   db->pCommitArg = pArg;
111426   sqlite3_mutex_leave(db->mutex);
111427   return pOld;
111428 }
111429 
111430 /*
111431 ** Register a callback to be invoked each time a row is updated,
111432 ** inserted or deleted using this database connection.
111433 */
111434 SQLITE_API void *sqlite3_update_hook(
111435   sqlite3 *db,              /* Attach the hook to this database */
111436   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
111437   void *pArg                /* Argument to the function */
111438 ){
111439   void *pRet;
111440   sqlite3_mutex_enter(db->mutex);
111441   pRet = db->pUpdateArg;
111442   db->xUpdateCallback = xCallback;
111443   db->pUpdateArg = pArg;
111444   sqlite3_mutex_leave(db->mutex);
111445   return pRet;
111446 }
111447 
111448 /*
111449 ** Register a callback to be invoked each time a transaction is rolled
111450 ** back by this database connection.
111451 */
111452 SQLITE_API void *sqlite3_rollback_hook(
111453   sqlite3 *db,              /* Attach the hook to this database */
111454   void (*xCallback)(void*), /* Callback function */
111455   void *pArg                /* Argument to the function */
111456 ){
111457   void *pRet;
111458   sqlite3_mutex_enter(db->mutex);
111459   pRet = db->pRollbackArg;
111460   db->xRollbackCallback = xCallback;
111461   db->pRollbackArg = pArg;
111462   sqlite3_mutex_leave(db->mutex);
111463   return pRet;
111464 }
111465 
111466 #ifndef SQLITE_OMIT_WAL
111467 /*
111468 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
111469 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
111470 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
111471 ** wal_autocheckpoint()).
111472 */
111473 SQLITE_PRIVATE int sqlite3WalDefaultHook(
111474   void *pClientData,     /* Argument */
111475   sqlite3 *db,           /* Connection */
111476   const char *zDb,       /* Database */
111477   int nFrame             /* Size of WAL */
111478 ){
111479   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
111480     sqlite3BeginBenignMalloc();
111481     sqlite3_wal_checkpoint(db, zDb);
111482     sqlite3EndBenignMalloc();
111483   }
111484   return SQLITE_OK;
111485 }
111486 #endif /* SQLITE_OMIT_WAL */
111487 
111488 /*
111489 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
111490 ** a database after committing a transaction if there are nFrame or
111491 ** more frames in the log file. Passing zero or a negative value as the
111492 ** nFrame parameter disables automatic checkpoints entirely.
111493 **
111494 ** The callback registered by this function replaces any existing callback
111495 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
111496 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
111497 ** configured by this function.
111498 */
111499 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
111500 #ifdef SQLITE_OMIT_WAL
111501   UNUSED_PARAMETER(db);
111502   UNUSED_PARAMETER(nFrame);
111503 #else
111504   if( nFrame>0 ){
111505     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
111506   }else{
111507     sqlite3_wal_hook(db, 0, 0);
111508   }
111509 #endif
111510   return SQLITE_OK;
111511 }
111512 
111513 /*
111514 ** Register a callback to be invoked each time a transaction is written
111515 ** into the write-ahead-log by this database connection.
111516 */
111517 SQLITE_API void *sqlite3_wal_hook(
111518   sqlite3 *db,                    /* Attach the hook to this db handle */
111519   int(*xCallback)(void *, sqlite3*, const char*, int),
111520   void *pArg                      /* First argument passed to xCallback() */
111521 ){
111522 #ifndef SQLITE_OMIT_WAL
111523   void *pRet;
111524   sqlite3_mutex_enter(db->mutex);
111525   pRet = db->pWalArg;
111526   db->xWalCallback = xCallback;
111527   db->pWalArg = pArg;
111528   sqlite3_mutex_leave(db->mutex);
111529   return pRet;
111530 #else
111531   return 0;
111532 #endif
111533 }
111534 
111535 /*
111536 ** Checkpoint database zDb.
111537 */
111538 SQLITE_API int sqlite3_wal_checkpoint_v2(
111539   sqlite3 *db,                    /* Database handle */
111540   const char *zDb,                /* Name of attached database (or NULL) */
111541   int eMode,                      /* SQLITE_CHECKPOINT_* value */
111542   int *pnLog,                     /* OUT: Size of WAL log in frames */
111543   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
111544 ){
111545 #ifdef SQLITE_OMIT_WAL
111546   return SQLITE_OK;
111547 #else
111548   int rc;                         /* Return code */
111549   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
111550 
111551   /* Initialize the output variables to -1 in case an error occurs. */
111552   if( pnLog ) *pnLog = -1;
111553   if( pnCkpt ) *pnCkpt = -1;
111554 
111555   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
111556   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
111557   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
111558   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
111559     return SQLITE_MISUSE;
111560   }
111561 
111562   sqlite3_mutex_enter(db->mutex);
111563   if( zDb && zDb[0] ){
111564     iDb = sqlite3FindDbName(db, zDb);
111565   }
111566   if( iDb<0 ){
111567     rc = SQLITE_ERROR;
111568     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
111569   }else{
111570     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
111571     sqlite3Error(db, rc, 0);
111572   }
111573   rc = sqlite3ApiExit(db, rc);
111574   sqlite3_mutex_leave(db->mutex);
111575   return rc;
111576 #endif
111577 }
111578 
111579 
111580 /*
111581 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
111582 ** to contains a zero-length string, all attached databases are
111583 ** checkpointed.
111584 */
111585 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
111586   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
111587 }
111588 
111589 #ifndef SQLITE_OMIT_WAL
111590 /*
111591 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
111592 ** not currently open in WAL mode.
111593 **
111594 ** If a transaction is open on the database being checkpointed, this
111595 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
111596 ** an error occurs while running the checkpoint, an SQLite error code is
111597 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
111598 **
111599 ** The mutex on database handle db should be held by the caller. The mutex
111600 ** associated with the specific b-tree being checkpointed is taken by
111601 ** this function while the checkpoint is running.
111602 **
111603 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
111604 ** checkpointed. If an error is encountered it is returned immediately -
111605 ** no attempt is made to checkpoint any remaining databases.
111606 **
111607 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
111608 */
111609 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
111610   int rc = SQLITE_OK;             /* Return code */
111611   int i;                          /* Used to iterate through attached dbs */
111612   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
111613 
111614   assert( sqlite3_mutex_held(db->mutex) );
111615   assert( !pnLog || *pnLog==-1 );
111616   assert( !pnCkpt || *pnCkpt==-1 );
111617 
111618   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
111619     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
111620       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
111621       pnLog = 0;
111622       pnCkpt = 0;
111623       if( rc==SQLITE_BUSY ){
111624         bBusy = 1;
111625         rc = SQLITE_OK;
111626       }
111627     }
111628   }
111629 
111630   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
111631 }
111632 #endif /* SQLITE_OMIT_WAL */
111633 
111634 /*
111635 ** This function returns true if main-memory should be used instead of
111636 ** a temporary file for transient pager files and statement journals.
111637 ** The value returned depends on the value of db->temp_store (runtime
111638 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
111639 ** following table describes the relationship between these two values
111640 ** and this functions return value.
111641 **
111642 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
111643 **   -----------------     --------------     ------------------------------
111644 **   0                     any                file      (return 0)
111645 **   1                     1                  file      (return 0)
111646 **   1                     2                  memory    (return 1)
111647 **   1                     0                  file      (return 0)
111648 **   2                     1                  file      (return 0)
111649 **   2                     2                  memory    (return 1)
111650 **   2                     0                  memory    (return 1)
111651 **   3                     any                memory    (return 1)
111652 */
111653 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
111654 #if SQLITE_TEMP_STORE==1
111655   return ( db->temp_store==2 );
111656 #endif
111657 #if SQLITE_TEMP_STORE==2
111658   return ( db->temp_store!=1 );
111659 #endif
111660 #if SQLITE_TEMP_STORE==3
111661   return 1;
111662 #endif
111663 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
111664   return 0;
111665 #endif
111666 }
111667 
111668 /*
111669 ** Return UTF-8 encoded English language explanation of the most recent
111670 ** error.
111671 */
111672 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
111673   const char *z;
111674   if( !db ){
111675     return sqlite3ErrStr(SQLITE_NOMEM);
111676   }
111677   if( !sqlite3SafetyCheckSickOrOk(db) ){
111678     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
111679   }
111680   sqlite3_mutex_enter(db->mutex);
111681   if( db->mallocFailed ){
111682     z = sqlite3ErrStr(SQLITE_NOMEM);
111683   }else{
111684     z = (char*)sqlite3_value_text(db->pErr);
111685     assert( !db->mallocFailed );
111686     if( z==0 ){
111687       z = sqlite3ErrStr(db->errCode);
111688     }
111689   }
111690   sqlite3_mutex_leave(db->mutex);
111691   return z;
111692 }
111693 
111694 #ifndef SQLITE_OMIT_UTF16
111695 /*
111696 ** Return UTF-16 encoded English language explanation of the most recent
111697 ** error.
111698 */
111699 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
111700   static const u16 outOfMem[] = {
111701     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
111702   };
111703   static const u16 misuse[] = {
111704     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
111705     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
111706     'c', 'a', 'l', 'l', 'e', 'd', ' ',
111707     'o', 'u', 't', ' ',
111708     'o', 'f', ' ',
111709     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
111710   };
111711 
111712   const void *z;
111713   if( !db ){
111714     return (void *)outOfMem;
111715   }
111716   if( !sqlite3SafetyCheckSickOrOk(db) ){
111717     return (void *)misuse;
111718   }
111719   sqlite3_mutex_enter(db->mutex);
111720   if( db->mallocFailed ){
111721     z = (void *)outOfMem;
111722   }else{
111723     z = sqlite3_value_text16(db->pErr);
111724     if( z==0 ){
111725       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
111726            SQLITE_UTF8, SQLITE_STATIC);
111727       z = sqlite3_value_text16(db->pErr);
111728     }
111729     /* A malloc() may have failed within the call to sqlite3_value_text16()
111730     ** above. If this is the case, then the db->mallocFailed flag needs to
111731     ** be cleared before returning. Do this directly, instead of via
111732     ** sqlite3ApiExit(), to avoid setting the database handle error message.
111733     */
111734     db->mallocFailed = 0;
111735   }
111736   sqlite3_mutex_leave(db->mutex);
111737   return z;
111738 }
111739 #endif /* SQLITE_OMIT_UTF16 */
111740 
111741 /*
111742 ** Return the most recent error code generated by an SQLite routine. If NULL is
111743 ** passed to this function, we assume a malloc() failed during sqlite3_open().
111744 */
111745 SQLITE_API int sqlite3_errcode(sqlite3 *db){
111746   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
111747     return SQLITE_MISUSE_BKPT;
111748   }
111749   if( !db || db->mallocFailed ){
111750     return SQLITE_NOMEM;
111751   }
111752   return db->errCode & db->errMask;
111753 }
111754 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
111755   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
111756     return SQLITE_MISUSE_BKPT;
111757   }
111758   if( !db || db->mallocFailed ){
111759     return SQLITE_NOMEM;
111760   }
111761   return db->errCode;
111762 }
111763 
111764 /*
111765 ** Create a new collating function for database "db".  The name is zName
111766 ** and the encoding is enc.
111767 */
111768 static int createCollation(
111769   sqlite3* db,
111770   const char *zName,
111771   u8 enc,
111772   u8 collType,
111773   void* pCtx,
111774   int(*xCompare)(void*,int,const void*,int,const void*),
111775   void(*xDel)(void*)
111776 ){
111777   CollSeq *pColl;
111778   int enc2;
111779   int nName = sqlite3Strlen30(zName);
111780 
111781   assert( sqlite3_mutex_held(db->mutex) );
111782 
111783   /* If SQLITE_UTF16 is specified as the encoding type, transform this
111784   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
111785   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
111786   */
111787   enc2 = enc;
111788   testcase( enc2==SQLITE_UTF16 );
111789   testcase( enc2==SQLITE_UTF16_ALIGNED );
111790   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
111791     enc2 = SQLITE_UTF16NATIVE;
111792   }
111793   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
111794     return SQLITE_MISUSE_BKPT;
111795   }
111796 
111797   /* Check if this call is removing or replacing an existing collation
111798   ** sequence. If so, and there are active VMs, return busy. If there
111799   ** are no active VMs, invalidate any pre-compiled statements.
111800   */
111801   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
111802   if( pColl && pColl->xCmp ){
111803     if( db->activeVdbeCnt ){
111804       sqlite3Error(db, SQLITE_BUSY,
111805         "unable to delete/modify collation sequence due to active statements");
111806       return SQLITE_BUSY;
111807     }
111808     sqlite3ExpirePreparedStatements(db);
111809 
111810     /* If collation sequence pColl was created directly by a call to
111811     ** sqlite3_create_collation, and not generated by synthCollSeq(),
111812     ** then any copies made by synthCollSeq() need to be invalidated.
111813     ** Also, collation destructor - CollSeq.xDel() - function may need
111814     ** to be called.
111815     */
111816     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
111817       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
111818       int j;
111819       for(j=0; j<3; j++){
111820         CollSeq *p = &aColl[j];
111821         if( p->enc==pColl->enc ){
111822           if( p->xDel ){
111823             p->xDel(p->pUser);
111824           }
111825           p->xCmp = 0;
111826         }
111827       }
111828     }
111829   }
111830 
111831   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
111832   if( pColl==0 ) return SQLITE_NOMEM;
111833   pColl->xCmp = xCompare;
111834   pColl->pUser = pCtx;
111835   pColl->xDel = xDel;
111836   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
111837   pColl->type = collType;
111838   sqlite3Error(db, SQLITE_OK, 0);
111839   return SQLITE_OK;
111840 }
111841 
111842 
111843 /*
111844 ** This array defines hard upper bounds on limit values.  The
111845 ** initializer must be kept in sync with the SQLITE_LIMIT_*
111846 ** #defines in sqlite3.h.
111847 */
111848 static const int aHardLimit[] = {
111849   SQLITE_MAX_LENGTH,
111850   SQLITE_MAX_SQL_LENGTH,
111851   SQLITE_MAX_COLUMN,
111852   SQLITE_MAX_EXPR_DEPTH,
111853   SQLITE_MAX_COMPOUND_SELECT,
111854   SQLITE_MAX_VDBE_OP,
111855   SQLITE_MAX_FUNCTION_ARG,
111856   SQLITE_MAX_ATTACHED,
111857   SQLITE_MAX_LIKE_PATTERN_LENGTH,
111858   SQLITE_MAX_VARIABLE_NUMBER,
111859   SQLITE_MAX_TRIGGER_DEPTH,
111860 };
111861 
111862 /*
111863 ** Make sure the hard limits are set to reasonable values
111864 */
111865 #if SQLITE_MAX_LENGTH<100
111866 # error SQLITE_MAX_LENGTH must be at least 100
111867 #endif
111868 #if SQLITE_MAX_SQL_LENGTH<100
111869 # error SQLITE_MAX_SQL_LENGTH must be at least 100
111870 #endif
111871 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
111872 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
111873 #endif
111874 #if SQLITE_MAX_COMPOUND_SELECT<2
111875 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
111876 #endif
111877 #if SQLITE_MAX_VDBE_OP<40
111878 # error SQLITE_MAX_VDBE_OP must be at least 40
111879 #endif
111880 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
111881 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
111882 #endif
111883 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
111884 # error SQLITE_MAX_ATTACHED must be between 0 and 62
111885 #endif
111886 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
111887 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
111888 #endif
111889 #if SQLITE_MAX_COLUMN>32767
111890 # error SQLITE_MAX_COLUMN must not exceed 32767
111891 #endif
111892 #if SQLITE_MAX_TRIGGER_DEPTH<1
111893 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
111894 #endif
111895 
111896 
111897 /*
111898 ** Change the value of a limit.  Report the old value.
111899 ** If an invalid limit index is supplied, report -1.
111900 ** Make no changes but still report the old value if the
111901 ** new limit is negative.
111902 **
111903 ** A new lower limit does not shrink existing constructs.
111904 ** It merely prevents new constructs that exceed the limit
111905 ** from forming.
111906 */
111907 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
111908   int oldLimit;
111909 
111910 
111911   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
111912   ** there is a hard upper bound set at compile-time by a C preprocessor
111913   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
111914   ** "_MAX_".)
111915   */
111916   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
111917   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
111918   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
111919   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
111920   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
111921   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
111922   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
111923   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
111924   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
111925                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
111926   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
111927   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
111928   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
111929 
111930 
111931   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
111932     return -1;
111933   }
111934   oldLimit = db->aLimit[limitId];
111935   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
111936     if( newLimit>aHardLimit[limitId] ){
111937       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
111938     }
111939     db->aLimit[limitId] = newLimit;
111940   }
111941   return oldLimit;                     /* IMP: R-53341-35419 */
111942 }
111943 
111944 /*
111945 ** This function is used to parse both URIs and non-URI filenames passed by the
111946 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
111947 ** URIs specified as part of ATTACH statements.
111948 **
111949 ** The first argument to this function is the name of the VFS to use (or
111950 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
111951 ** query parameter. The second argument contains the URI (or non-URI filename)
111952 ** itself. When this function is called the *pFlags variable should contain
111953 ** the default flags to open the database handle with. The value stored in
111954 ** *pFlags may be updated before returning if the URI filename contains
111955 ** "cache=xxx" or "mode=xxx" query parameters.
111956 **
111957 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
111958 ** the VFS that should be used to open the database file. *pzFile is set to
111959 ** point to a buffer containing the name of the file to open. It is the
111960 ** responsibility of the caller to eventually call sqlite3_free() to release
111961 ** this buffer.
111962 **
111963 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
111964 ** may be set to point to a buffer containing an English language error
111965 ** message. It is the responsibility of the caller to eventually release
111966 ** this buffer by calling sqlite3_free().
111967 */
111968 SQLITE_PRIVATE int sqlite3ParseUri(
111969   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
111970   const char *zUri,               /* Nul-terminated URI to parse */
111971   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
111972   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
111973   char **pzFile,                  /* OUT: Filename component of URI */
111974   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
111975 ){
111976   int rc = SQLITE_OK;
111977   unsigned int flags = *pFlags;
111978   const char *zVfs = zDefaultVfs;
111979   char *zFile;
111980   char c;
111981   int nUri = sqlite3Strlen30(zUri);
111982 
111983   assert( *pzErrMsg==0 );
111984 
111985   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
111986    && nUri>=5 && memcmp(zUri, "file:", 5)==0
111987   ){
111988     char *zOpt;
111989     int eState;                   /* Parser state when parsing URI */
111990     int iIn;                      /* Input character index */
111991     int iOut = 0;                 /* Output character index */
111992     int nByte = nUri+2;           /* Bytes of space to allocate */
111993 
111994     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
111995     ** method that there may be extra parameters following the file-name.  */
111996     flags |= SQLITE_OPEN_URI;
111997 
111998     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
111999     zFile = sqlite3_malloc(nByte);
112000     if( !zFile ) return SQLITE_NOMEM;
112001 
112002     /* Discard the scheme and authority segments of the URI. */
112003     if( zUri[5]=='/' && zUri[6]=='/' ){
112004       iIn = 7;
112005       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
112006 
112007       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
112008         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
112009             iIn-7, &zUri[7]);
112010         rc = SQLITE_ERROR;
112011         goto parse_uri_out;
112012       }
112013     }else{
112014       iIn = 5;
112015     }
112016 
112017     /* Copy the filename and any query parameters into the zFile buffer.
112018     ** Decode %HH escape codes along the way.
112019     **
112020     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
112021     ** on the parsing context. As follows:
112022     **
112023     **   0: Parsing file-name.
112024     **   1: Parsing name section of a name=value query parameter.
112025     **   2: Parsing value section of a name=value query parameter.
112026     */
112027     eState = 0;
112028     while( (c = zUri[iIn])!=0 && c!='#' ){
112029       iIn++;
112030       if( c=='%'
112031        && sqlite3Isxdigit(zUri[iIn])
112032        && sqlite3Isxdigit(zUri[iIn+1])
112033       ){
112034         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
112035         octet += sqlite3HexToInt(zUri[iIn++]);
112036 
112037         assert( octet>=0 && octet<256 );
112038         if( octet==0 ){
112039           /* This branch is taken when "%00" appears within the URI. In this
112040           ** case we ignore all text in the remainder of the path, name or
112041           ** value currently being parsed. So ignore the current character
112042           ** and skip to the next "?", "=" or "&", as appropriate. */
112043           while( (c = zUri[iIn])!=0 && c!='#'
112044               && (eState!=0 || c!='?')
112045               && (eState!=1 || (c!='=' && c!='&'))
112046               && (eState!=2 || c!='&')
112047           ){
112048             iIn++;
112049           }
112050           continue;
112051         }
112052         c = octet;
112053       }else if( eState==1 && (c=='&' || c=='=') ){
112054         if( zFile[iOut-1]==0 ){
112055           /* An empty option name. Ignore this option altogether. */
112056           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
112057           continue;
112058         }
112059         if( c=='&' ){
112060           zFile[iOut++] = '\0';
112061         }else{
112062           eState = 2;
112063         }
112064         c = 0;
112065       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
112066         c = 0;
112067         eState = 1;
112068       }
112069       zFile[iOut++] = c;
112070     }
112071     if( eState==1 ) zFile[iOut++] = '\0';
112072     zFile[iOut++] = '\0';
112073     zFile[iOut++] = '\0';
112074 
112075     /* Check if there were any options specified that should be interpreted
112076     ** here. Options that are interpreted here include "vfs" and those that
112077     ** correspond to flags that may be passed to the sqlite3_open_v2()
112078     ** method. */
112079     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
112080     while( zOpt[0] ){
112081       int nOpt = sqlite3Strlen30(zOpt);
112082       char *zVal = &zOpt[nOpt+1];
112083       int nVal = sqlite3Strlen30(zVal);
112084 
112085       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
112086         zVfs = zVal;
112087       }else{
112088         struct OpenMode {
112089           const char *z;
112090           int mode;
112091         } *aMode = 0;
112092         char *zModeType = 0;
112093         int mask = 0;
112094         int limit = 0;
112095 
112096         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
112097           static struct OpenMode aCacheMode[] = {
112098             { "shared",  SQLITE_OPEN_SHAREDCACHE },
112099             { "private", SQLITE_OPEN_PRIVATECACHE },
112100             { 0, 0 }
112101           };
112102 
112103           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
112104           aMode = aCacheMode;
112105           limit = mask;
112106           zModeType = "cache";
112107         }
112108         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
112109           static struct OpenMode aOpenMode[] = {
112110             { "ro",  SQLITE_OPEN_READONLY },
112111             { "rw",  SQLITE_OPEN_READWRITE },
112112             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
112113             { 0, 0 }
112114           };
112115 
112116           mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
112117           aMode = aOpenMode;
112118           limit = mask & flags;
112119           zModeType = "access";
112120         }
112121 
112122         if( aMode ){
112123           int i;
112124           int mode = 0;
112125           for(i=0; aMode[i].z; i++){
112126             const char *z = aMode[i].z;
112127             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
112128               mode = aMode[i].mode;
112129               break;
112130             }
112131           }
112132           if( mode==0 ){
112133             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
112134             rc = SQLITE_ERROR;
112135             goto parse_uri_out;
112136           }
112137           if( mode>limit ){
112138             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
112139                                         zModeType, zVal);
112140             rc = SQLITE_PERM;
112141             goto parse_uri_out;
112142           }
112143           flags = (flags & ~mask) | mode;
112144         }
112145       }
112146 
112147       zOpt = &zVal[nVal+1];
112148     }
112149 
112150   }else{
112151     zFile = sqlite3_malloc(nUri+2);
112152     if( !zFile ) return SQLITE_NOMEM;
112153     memcpy(zFile, zUri, nUri);
112154     zFile[nUri] = '\0';
112155     zFile[nUri+1] = '\0';
112156   }
112157 
112158   *ppVfs = sqlite3_vfs_find(zVfs);
112159   if( *ppVfs==0 ){
112160     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
112161     rc = SQLITE_ERROR;
112162   }
112163  parse_uri_out:
112164   if( rc!=SQLITE_OK ){
112165     sqlite3_free(zFile);
112166     zFile = 0;
112167   }
112168   *pFlags = flags;
112169   *pzFile = zFile;
112170   return rc;
112171 }
112172 
112173 
112174 /*
112175 ** This routine does the work of opening a database on behalf of
112176 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
112177 ** is UTF-8 encoded.
112178 */
112179 static int openDatabase(
112180   const char *zFilename, /* Database filename UTF-8 encoded */
112181   sqlite3 **ppDb,        /* OUT: Returned database handle */
112182   unsigned int flags,    /* Operational flags */
112183   const char *zVfs       /* Name of the VFS to use */
112184 ){
112185   sqlite3 *db;                    /* Store allocated handle here */
112186   int rc;                         /* Return code */
112187   int isThreadsafe;               /* True for threadsafe connections */
112188   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
112189   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
112190 
112191   *ppDb = 0;
112192 #ifndef SQLITE_OMIT_AUTOINIT
112193   rc = sqlite3_initialize();
112194   if( rc ) return rc;
112195 #endif
112196 
112197   /* Only allow sensible combinations of bits in the flags argument.
112198   ** Throw an error if any non-sense combination is used.  If we
112199   ** do not block illegal combinations here, it could trigger
112200   ** assert() statements in deeper layers.  Sensible combinations
112201   ** are:
112202   **
112203   **  1:  SQLITE_OPEN_READONLY
112204   **  2:  SQLITE_OPEN_READWRITE
112205   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
112206   */
112207   assert( SQLITE_OPEN_READONLY  == 0x01 );
112208   assert( SQLITE_OPEN_READWRITE == 0x02 );
112209   assert( SQLITE_OPEN_CREATE    == 0x04 );
112210   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
112211   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
112212   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
112213   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
112214 
112215   if( sqlite3GlobalConfig.bCoreMutex==0 ){
112216     isThreadsafe = 0;
112217   }else if( flags & SQLITE_OPEN_NOMUTEX ){
112218     isThreadsafe = 0;
112219   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
112220     isThreadsafe = 1;
112221   }else{
112222     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
112223   }
112224   if( flags & SQLITE_OPEN_PRIVATECACHE ){
112225     flags &= ~SQLITE_OPEN_SHAREDCACHE;
112226   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
112227     flags |= SQLITE_OPEN_SHAREDCACHE;
112228   }
112229 
112230   /* Remove harmful bits from the flags parameter
112231   **
112232   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
112233   ** dealt with in the previous code block.  Besides these, the only
112234   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
112235   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
112236   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
112237   ** off all other flags.
112238   */
112239   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
112240                SQLITE_OPEN_EXCLUSIVE |
112241                SQLITE_OPEN_MAIN_DB |
112242                SQLITE_OPEN_TEMP_DB |
112243                SQLITE_OPEN_TRANSIENT_DB |
112244                SQLITE_OPEN_MAIN_JOURNAL |
112245                SQLITE_OPEN_TEMP_JOURNAL |
112246                SQLITE_OPEN_SUBJOURNAL |
112247                SQLITE_OPEN_MASTER_JOURNAL |
112248                SQLITE_OPEN_NOMUTEX |
112249                SQLITE_OPEN_FULLMUTEX |
112250                SQLITE_OPEN_WAL
112251              );
112252 
112253   /* Allocate the sqlite data structure */
112254   db = sqlite3MallocZero( sizeof(sqlite3) );
112255   if( db==0 ) goto opendb_out;
112256   if( isThreadsafe ){
112257     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
112258     if( db->mutex==0 ){
112259       sqlite3_free(db);
112260       db = 0;
112261       goto opendb_out;
112262     }
112263   }
112264   sqlite3_mutex_enter(db->mutex);
112265   db->errMask = 0xff;
112266   db->nDb = 2;
112267   db->magic = SQLITE_MAGIC_BUSY;
112268   db->aDb = db->aDbStatic;
112269 
112270   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
112271   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
112272   db->autoCommit = 1;
112273   db->nextAutovac = -1;
112274   db->nextPagesize = 0;
112275   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
112276 #if SQLITE_DEFAULT_FILE_FORMAT<4
112277                  | SQLITE_LegacyFileFmt
112278 #endif
112279 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
112280                  | SQLITE_LoadExtension
112281 #endif
112282 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
112283                  | SQLITE_RecTriggers
112284 #endif
112285 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
112286                  | SQLITE_ForeignKeys
112287 #endif
112288       ;
112289   sqlite3HashInit(&db->aCollSeq);
112290 #ifndef SQLITE_OMIT_VIRTUALTABLE
112291   sqlite3HashInit(&db->aModule);
112292 #endif
112293 
112294   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
112295   ** and UTF-16, so add a version for each to avoid any unnecessary
112296   ** conversions. The only error that can occur here is a malloc() failure.
112297   */
112298   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
112299                   binCollFunc, 0);
112300   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
112301                   binCollFunc, 0);
112302   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
112303                   binCollFunc, 0);
112304   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
112305                   binCollFunc, 0);
112306   if( db->mallocFailed ){
112307     goto opendb_out;
112308   }
112309   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
112310   assert( db->pDfltColl!=0 );
112311 
112312   /* Also add a UTF-8 case-insensitive collation sequence. */
112313   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
112314                   nocaseCollatingFunc, 0);
112315 
112316   /* Parse the filename/URI argument. */
112317   db->openFlags = flags;
112318   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
112319   if( rc!=SQLITE_OK ){
112320     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
112321     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
112322     sqlite3_free(zErrMsg);
112323     goto opendb_out;
112324   }
112325 
112326   /* Open the backend database driver */
112327   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
112328                         flags | SQLITE_OPEN_MAIN_DB);
112329   if( rc!=SQLITE_OK ){
112330     if( rc==SQLITE_IOERR_NOMEM ){
112331       rc = SQLITE_NOMEM;
112332     }
112333     sqlite3Error(db, rc, 0);
112334     goto opendb_out;
112335   }
112336   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
112337   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
112338 
112339 
112340   /* The default safety_level for the main database is 'full'; for the temp
112341   ** database it is 'NONE'. This matches the pager layer defaults.
112342   */
112343   db->aDb[0].zName = "main";
112344   db->aDb[0].safety_level = 3;
112345   db->aDb[1].zName = "temp";
112346   db->aDb[1].safety_level = 1;
112347 
112348   db->magic = SQLITE_MAGIC_OPEN;
112349   if( db->mallocFailed ){
112350     goto opendb_out;
112351   }
112352 
112353   /* Register all built-in functions, but do not attempt to read the
112354   ** database schema yet. This is delayed until the first time the database
112355   ** is accessed.
112356   */
112357   sqlite3Error(db, SQLITE_OK, 0);
112358   sqlite3RegisterBuiltinFunctions(db);
112359 
112360   /* Load automatic extensions - extensions that have been registered
112361   ** using the sqlite3_automatic_extension() API.
112362   */
112363   sqlite3AutoLoadExtensions(db);
112364   rc = sqlite3_errcode(db);
112365   if( rc!=SQLITE_OK ){
112366     goto opendb_out;
112367   }
112368 
112369 #ifdef SQLITE_ENABLE_FTS1
112370   if( !db->mallocFailed ){
112371     extern int sqlite3Fts1Init(sqlite3*);
112372     rc = sqlite3Fts1Init(db);
112373   }
112374 #endif
112375 
112376 #ifdef SQLITE_ENABLE_FTS2
112377   if( !db->mallocFailed && rc==SQLITE_OK ){
112378     extern int sqlite3Fts2Init(sqlite3*);
112379     rc = sqlite3Fts2Init(db);
112380   }
112381 #endif
112382 
112383 #ifdef SQLITE_ENABLE_FTS3
112384   if( !db->mallocFailed && rc==SQLITE_OK ){
112385     rc = sqlite3Fts3Init(db);
112386   }
112387 #endif
112388 
112389 #ifdef SQLITE_ENABLE_ICU
112390   if( !db->mallocFailed && rc==SQLITE_OK ){
112391     rc = sqlite3IcuInit(db);
112392   }
112393 #endif
112394 
112395 #ifdef SQLITE_ENABLE_RTREE
112396   if( !db->mallocFailed && rc==SQLITE_OK){
112397     rc = sqlite3RtreeInit(db);
112398   }
112399 #endif
112400 
112401   sqlite3Error(db, rc, 0);
112402 
112403   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
112404   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
112405   ** mode.  Doing nothing at all also makes NORMAL the default.
112406   */
112407 #ifdef SQLITE_DEFAULT_LOCKING_MODE
112408   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
112409   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
112410                           SQLITE_DEFAULT_LOCKING_MODE);
112411 #endif
112412 
112413   /* Enable the lookaside-malloc subsystem */
112414   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
112415                         sqlite3GlobalConfig.nLookaside);
112416 
112417   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
112418 
112419 opendb_out:
112420   sqlite3_free(zOpen);
112421   if( db ){
112422     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
112423     sqlite3_mutex_leave(db->mutex);
112424   }
112425   rc = sqlite3_errcode(db);
112426   if( rc==SQLITE_NOMEM ){
112427     sqlite3_close(db);
112428     db = 0;
112429   }else if( rc!=SQLITE_OK ){
112430     db->magic = SQLITE_MAGIC_SICK;
112431   }
112432   *ppDb = db;
112433   return sqlite3ApiExit(0, rc);
112434 }
112435 
112436 /*
112437 ** Open a new database handle.
112438 */
112439 SQLITE_API int sqlite3_open(
112440   const char *zFilename,
112441   sqlite3 **ppDb
112442 ){
112443   return openDatabase(zFilename, ppDb,
112444                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
112445 }
112446 SQLITE_API int sqlite3_open_v2(
112447   const char *filename,   /* Database filename (UTF-8) */
112448   sqlite3 **ppDb,         /* OUT: SQLite db handle */
112449   int flags,              /* Flags */
112450   const char *zVfs        /* Name of VFS module to use */
112451 ){
112452   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
112453 }
112454 
112455 #ifndef SQLITE_OMIT_UTF16
112456 /*
112457 ** Open a new database handle.
112458 */
112459 SQLITE_API int sqlite3_open16(
112460   const void *zFilename,
112461   sqlite3 **ppDb
112462 ){
112463   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
112464   sqlite3_value *pVal;
112465   int rc;
112466 
112467   assert( zFilename );
112468   assert( ppDb );
112469   *ppDb = 0;
112470 #ifndef SQLITE_OMIT_AUTOINIT
112471   rc = sqlite3_initialize();
112472   if( rc ) return rc;
112473 #endif
112474   pVal = sqlite3ValueNew(0);
112475   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
112476   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
112477   if( zFilename8 ){
112478     rc = openDatabase(zFilename8, ppDb,
112479                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
112480     assert( *ppDb || rc==SQLITE_NOMEM );
112481     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
112482       ENC(*ppDb) = SQLITE_UTF16NATIVE;
112483     }
112484   }else{
112485     rc = SQLITE_NOMEM;
112486   }
112487   sqlite3ValueFree(pVal);
112488 
112489   return sqlite3ApiExit(0, rc);
112490 }
112491 #endif /* SQLITE_OMIT_UTF16 */
112492 
112493 /*
112494 ** Register a new collation sequence with the database handle db.
112495 */
112496 SQLITE_API int sqlite3_create_collation(
112497   sqlite3* db,
112498   const char *zName,
112499   int enc,
112500   void* pCtx,
112501   int(*xCompare)(void*,int,const void*,int,const void*)
112502 ){
112503   int rc;
112504   sqlite3_mutex_enter(db->mutex);
112505   assert( !db->mallocFailed );
112506   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
112507   rc = sqlite3ApiExit(db, rc);
112508   sqlite3_mutex_leave(db->mutex);
112509   return rc;
112510 }
112511 
112512 /*
112513 ** Register a new collation sequence with the database handle db.
112514 */
112515 SQLITE_API int sqlite3_create_collation_v2(
112516   sqlite3* db,
112517   const char *zName,
112518   int enc,
112519   void* pCtx,
112520   int(*xCompare)(void*,int,const void*,int,const void*),
112521   void(*xDel)(void*)
112522 ){
112523   int rc;
112524   sqlite3_mutex_enter(db->mutex);
112525   assert( !db->mallocFailed );
112526   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
112527   rc = sqlite3ApiExit(db, rc);
112528   sqlite3_mutex_leave(db->mutex);
112529   return rc;
112530 }
112531 
112532 #ifndef SQLITE_OMIT_UTF16
112533 /*
112534 ** Register a new collation sequence with the database handle db.
112535 */
112536 SQLITE_API int sqlite3_create_collation16(
112537   sqlite3* db,
112538   const void *zName,
112539   int enc,
112540   void* pCtx,
112541   int(*xCompare)(void*,int,const void*,int,const void*)
112542 ){
112543   int rc = SQLITE_OK;
112544   char *zName8;
112545   sqlite3_mutex_enter(db->mutex);
112546   assert( !db->mallocFailed );
112547   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
112548   if( zName8 ){
112549     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
112550     sqlite3DbFree(db, zName8);
112551   }
112552   rc = sqlite3ApiExit(db, rc);
112553   sqlite3_mutex_leave(db->mutex);
112554   return rc;
112555 }
112556 #endif /* SQLITE_OMIT_UTF16 */
112557 
112558 /*
112559 ** Register a collation sequence factory callback with the database handle
112560 ** db. Replace any previously installed collation sequence factory.
112561 */
112562 SQLITE_API int sqlite3_collation_needed(
112563   sqlite3 *db,
112564   void *pCollNeededArg,
112565   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
112566 ){
112567   sqlite3_mutex_enter(db->mutex);
112568   db->xCollNeeded = xCollNeeded;
112569   db->xCollNeeded16 = 0;
112570   db->pCollNeededArg = pCollNeededArg;
112571   sqlite3_mutex_leave(db->mutex);
112572   return SQLITE_OK;
112573 }
112574 
112575 #ifndef SQLITE_OMIT_UTF16
112576 /*
112577 ** Register a collation sequence factory callback with the database handle
112578 ** db. Replace any previously installed collation sequence factory.
112579 */
112580 SQLITE_API int sqlite3_collation_needed16(
112581   sqlite3 *db,
112582   void *pCollNeededArg,
112583   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
112584 ){
112585   sqlite3_mutex_enter(db->mutex);
112586   db->xCollNeeded = 0;
112587   db->xCollNeeded16 = xCollNeeded16;
112588   db->pCollNeededArg = pCollNeededArg;
112589   sqlite3_mutex_leave(db->mutex);
112590   return SQLITE_OK;
112591 }
112592 #endif /* SQLITE_OMIT_UTF16 */
112593 
112594 #ifndef SQLITE_OMIT_DEPRECATED
112595 /*
112596 ** This function is now an anachronism. It used to be used to recover from a
112597 ** malloc() failure, but SQLite now does this automatically.
112598 */
112599 SQLITE_API int sqlite3_global_recover(void){
112600   return SQLITE_OK;
112601 }
112602 #endif
112603 
112604 /*
112605 ** Test to see whether or not the database connection is in autocommit
112606 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
112607 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
112608 ** by the next COMMIT or ROLLBACK.
112609 **
112610 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
112611 */
112612 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
112613   return db->autoCommit;
112614 }
112615 
112616 /*
112617 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
112618 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
112619 ** constants.  They server two purposes:
112620 **
112621 **   1.  Serve as a convenient place to set a breakpoint in a debugger
112622 **       to detect when version error conditions occurs.
112623 **
112624 **   2.  Invoke sqlite3_log() to provide the source code location where
112625 **       a low-level error is first detected.
112626 */
112627 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
112628   testcase( sqlite3GlobalConfig.xLog!=0 );
112629   sqlite3_log(SQLITE_CORRUPT,
112630               "database corruption at line %d of [%.10s]",
112631               lineno, 20+sqlite3_sourceid());
112632   return SQLITE_CORRUPT;
112633 }
112634 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
112635   testcase( sqlite3GlobalConfig.xLog!=0 );
112636   sqlite3_log(SQLITE_MISUSE,
112637               "misuse at line %d of [%.10s]",
112638               lineno, 20+sqlite3_sourceid());
112639   return SQLITE_MISUSE;
112640 }
112641 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
112642   testcase( sqlite3GlobalConfig.xLog!=0 );
112643   sqlite3_log(SQLITE_CANTOPEN,
112644               "cannot open file at line %d of [%.10s]",
112645               lineno, 20+sqlite3_sourceid());
112646   return SQLITE_CANTOPEN;
112647 }
112648 
112649 
112650 #ifndef SQLITE_OMIT_DEPRECATED
112651 /*
112652 ** This is a convenience routine that makes sure that all thread-specific
112653 ** data for this thread has been deallocated.
112654 **
112655 ** SQLite no longer uses thread-specific data so this routine is now a
112656 ** no-op.  It is retained for historical compatibility.
112657 */
112658 SQLITE_API void sqlite3_thread_cleanup(void){
112659 }
112660 #endif
112661 
112662 /*
112663 ** Return meta information about a specific column of a database table.
112664 ** See comment in sqlite3.h (sqlite.h.in) for details.
112665 */
112666 #ifdef SQLITE_ENABLE_COLUMN_METADATA
112667 SQLITE_API int sqlite3_table_column_metadata(
112668   sqlite3 *db,                /* Connection handle */
112669   const char *zDbName,        /* Database name or NULL */
112670   const char *zTableName,     /* Table name */
112671   const char *zColumnName,    /* Column name */
112672   char const **pzDataType,    /* OUTPUT: Declared data type */
112673   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
112674   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
112675   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
112676   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
112677 ){
112678   int rc;
112679   char *zErrMsg = 0;
112680   Table *pTab = 0;
112681   Column *pCol = 0;
112682   int iCol;
112683 
112684   char const *zDataType = 0;
112685   char const *zCollSeq = 0;
112686   int notnull = 0;
112687   int primarykey = 0;
112688   int autoinc = 0;
112689 
112690   /* Ensure the database schema has been loaded */
112691   sqlite3_mutex_enter(db->mutex);
112692   sqlite3BtreeEnterAll(db);
112693   rc = sqlite3Init(db, &zErrMsg);
112694   if( SQLITE_OK!=rc ){
112695     goto error_out;
112696   }
112697 
112698   /* Locate the table in question */
112699   pTab = sqlite3FindTable(db, zTableName, zDbName);
112700   if( !pTab || pTab->pSelect ){
112701     pTab = 0;
112702     goto error_out;
112703   }
112704 
112705   /* Find the column for which info is requested */
112706   if( sqlite3IsRowid(zColumnName) ){
112707     iCol = pTab->iPKey;
112708     if( iCol>=0 ){
112709       pCol = &pTab->aCol[iCol];
112710     }
112711   }else{
112712     for(iCol=0; iCol<pTab->nCol; iCol++){
112713       pCol = &pTab->aCol[iCol];
112714       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
112715         break;
112716       }
112717     }
112718     if( iCol==pTab->nCol ){
112719       pTab = 0;
112720       goto error_out;
112721     }
112722   }
112723 
112724   /* The following block stores the meta information that will be returned
112725   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
112726   ** and autoinc. At this point there are two possibilities:
112727   **
112728   **     1. The specified column name was rowid", "oid" or "_rowid_"
112729   **        and there is no explicitly declared IPK column.
112730   **
112731   **     2. The table is not a view and the column name identified an
112732   **        explicitly declared column. Copy meta information from *pCol.
112733   */
112734   if( pCol ){
112735     zDataType = pCol->zType;
112736     zCollSeq = pCol->zColl;
112737     notnull = pCol->notNull!=0;
112738     primarykey  = pCol->isPrimKey!=0;
112739     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
112740   }else{
112741     zDataType = "INTEGER";
112742     primarykey = 1;
112743   }
112744   if( !zCollSeq ){
112745     zCollSeq = "BINARY";
112746   }
112747 
112748 error_out:
112749   sqlite3BtreeLeaveAll(db);
112750 
112751   /* Whether the function call succeeded or failed, set the output parameters
112752   ** to whatever their local counterparts contain. If an error did occur,
112753   ** this has the effect of zeroing all output parameters.
112754   */
112755   if( pzDataType ) *pzDataType = zDataType;
112756   if( pzCollSeq ) *pzCollSeq = zCollSeq;
112757   if( pNotNull ) *pNotNull = notnull;
112758   if( pPrimaryKey ) *pPrimaryKey = primarykey;
112759   if( pAutoinc ) *pAutoinc = autoinc;
112760 
112761   if( SQLITE_OK==rc && !pTab ){
112762     sqlite3DbFree(db, zErrMsg);
112763     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
112764         zColumnName);
112765     rc = SQLITE_ERROR;
112766   }
112767   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
112768   sqlite3DbFree(db, zErrMsg);
112769   rc = sqlite3ApiExit(db, rc);
112770   sqlite3_mutex_leave(db->mutex);
112771   return rc;
112772 }
112773 #endif
112774 
112775 /*
112776 ** Sleep for a little while.  Return the amount of time slept.
112777 */
112778 SQLITE_API int sqlite3_sleep(int ms){
112779   sqlite3_vfs *pVfs;
112780   int rc;
112781   pVfs = sqlite3_vfs_find(0);
112782   if( pVfs==0 ) return 0;
112783 
112784   /* This function works in milliseconds, but the underlying OsSleep()
112785   ** API uses microseconds. Hence the 1000's.
112786   */
112787   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
112788   return rc;
112789 }
112790 
112791 /*
112792 ** Enable or disable the extended result codes.
112793 */
112794 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
112795   sqlite3_mutex_enter(db->mutex);
112796   db->errMask = onoff ? 0xffffffff : 0xff;
112797   sqlite3_mutex_leave(db->mutex);
112798   return SQLITE_OK;
112799 }
112800 
112801 /*
112802 ** Invoke the xFileControl method on a particular database.
112803 */
112804 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
112805   int rc = SQLITE_ERROR;
112806   int iDb;
112807   sqlite3_mutex_enter(db->mutex);
112808   if( zDbName==0 ){
112809     iDb = 0;
112810   }else{
112811     for(iDb=0; iDb<db->nDb; iDb++){
112812       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
112813     }
112814   }
112815   if( iDb<db->nDb ){
112816     Btree *pBtree = db->aDb[iDb].pBt;
112817     if( pBtree ){
112818       Pager *pPager;
112819       sqlite3_file *fd;
112820       sqlite3BtreeEnter(pBtree);
112821       pPager = sqlite3BtreePager(pBtree);
112822       assert( pPager!=0 );
112823       fd = sqlite3PagerFile(pPager);
112824       assert( fd!=0 );
112825       if( op==SQLITE_FCNTL_FILE_POINTER ){
112826         *(sqlite3_file**)pArg = fd;
112827         rc = SQLITE_OK;
112828       }else if( fd->pMethods ){
112829         rc = sqlite3OsFileControl(fd, op, pArg);
112830       }else{
112831         rc = SQLITE_NOTFOUND;
112832       }
112833       sqlite3BtreeLeave(pBtree);
112834     }
112835   }
112836   sqlite3_mutex_leave(db->mutex);
112837   return rc;
112838 }
112839 
112840 /*
112841 ** Interface to the testing logic.
112842 */
112843 SQLITE_API int sqlite3_test_control(int op, ...){
112844   int rc = 0;
112845 #ifndef SQLITE_OMIT_BUILTIN_TEST
112846   va_list ap;
112847   va_start(ap, op);
112848   switch( op ){
112849 
112850     /*
112851     ** Save the current state of the PRNG.
112852     */
112853     case SQLITE_TESTCTRL_PRNG_SAVE: {
112854       sqlite3PrngSaveState();
112855       break;
112856     }
112857 
112858     /*
112859     ** Restore the state of the PRNG to the last state saved using
112860     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
112861     ** this verb acts like PRNG_RESET.
112862     */
112863     case SQLITE_TESTCTRL_PRNG_RESTORE: {
112864       sqlite3PrngRestoreState();
112865       break;
112866     }
112867 
112868     /*
112869     ** Reset the PRNG back to its uninitialized state.  The next call
112870     ** to sqlite3_randomness() will reseed the PRNG using a single call
112871     ** to the xRandomness method of the default VFS.
112872     */
112873     case SQLITE_TESTCTRL_PRNG_RESET: {
112874       sqlite3PrngResetState();
112875       break;
112876     }
112877 
112878     /*
112879     **  sqlite3_test_control(BITVEC_TEST, size, program)
112880     **
112881     ** Run a test against a Bitvec object of size.  The program argument
112882     ** is an array of integers that defines the test.  Return -1 on a
112883     ** memory allocation error, 0 on success, or non-zero for an error.
112884     ** See the sqlite3BitvecBuiltinTest() for additional information.
112885     */
112886     case SQLITE_TESTCTRL_BITVEC_TEST: {
112887       int sz = va_arg(ap, int);
112888       int *aProg = va_arg(ap, int*);
112889       rc = sqlite3BitvecBuiltinTest(sz, aProg);
112890       break;
112891     }
112892 
112893     /*
112894     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
112895     **
112896     ** Register hooks to call to indicate which malloc() failures
112897     ** are benign.
112898     */
112899     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
112900       typedef void (*void_function)(void);
112901       void_function xBenignBegin;
112902       void_function xBenignEnd;
112903       xBenignBegin = va_arg(ap, void_function);
112904       xBenignEnd = va_arg(ap, void_function);
112905       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
112906       break;
112907     }
112908 
112909     /*
112910     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
112911     **
112912     ** Set the PENDING byte to the value in the argument, if X>0.
112913     ** Make no changes if X==0.  Return the value of the pending byte
112914     ** as it existing before this routine was called.
112915     **
112916     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
112917     ** an incompatible database file format.  Changing the PENDING byte
112918     ** while any database connection is open results in undefined and
112919     ** dileterious behavior.
112920     */
112921     case SQLITE_TESTCTRL_PENDING_BYTE: {
112922       rc = PENDING_BYTE;
112923 #ifndef SQLITE_OMIT_WSD
112924       {
112925         unsigned int newVal = va_arg(ap, unsigned int);
112926         if( newVal ) sqlite3PendingByte = newVal;
112927       }
112928 #endif
112929       break;
112930     }
112931 
112932     /*
112933     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
112934     **
112935     ** This action provides a run-time test to see whether or not
112936     ** assert() was enabled at compile-time.  If X is true and assert()
112937     ** is enabled, then the return value is true.  If X is true and
112938     ** assert() is disabled, then the return value is zero.  If X is
112939     ** false and assert() is enabled, then the assertion fires and the
112940     ** process aborts.  If X is false and assert() is disabled, then the
112941     ** return value is zero.
112942     */
112943     case SQLITE_TESTCTRL_ASSERT: {
112944       volatile int x = 0;
112945       assert( (x = va_arg(ap,int))!=0 );
112946       rc = x;
112947       break;
112948     }
112949 
112950 
112951     /*
112952     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
112953     **
112954     ** This action provides a run-time test to see how the ALWAYS and
112955     ** NEVER macros were defined at compile-time.
112956     **
112957     ** The return value is ALWAYS(X).
112958     **
112959     ** The recommended test is X==2.  If the return value is 2, that means
112960     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
112961     ** default setting.  If the return value is 1, then ALWAYS() is either
112962     ** hard-coded to true or else it asserts if its argument is false.
112963     ** The first behavior (hard-coded to true) is the case if
112964     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
112965     ** behavior (assert if the argument to ALWAYS() is false) is the case if
112966     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
112967     **
112968     ** The run-time test procedure might look something like this:
112969     **
112970     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
112971     **      // ALWAYS() and NEVER() are no-op pass-through macros
112972     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
112973     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
112974     **    }else{
112975     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
112976     **    }
112977     */
112978     case SQLITE_TESTCTRL_ALWAYS: {
112979       int x = va_arg(ap,int);
112980       rc = ALWAYS(x);
112981       break;
112982     }
112983 
112984     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
112985     **
112986     ** Set the nReserve size to N for the main database on the database
112987     ** connection db.
112988     */
112989     case SQLITE_TESTCTRL_RESERVE: {
112990       sqlite3 *db = va_arg(ap, sqlite3*);
112991       int x = va_arg(ap,int);
112992       sqlite3_mutex_enter(db->mutex);
112993       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
112994       sqlite3_mutex_leave(db->mutex);
112995       break;
112996     }
112997 
112998     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
112999     **
113000     ** Enable or disable various optimizations for testing purposes.  The
113001     ** argument N is a bitmask of optimizations to be disabled.  For normal
113002     ** operation N should be 0.  The idea is that a test program (like the
113003     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
113004     ** with various optimizations disabled to verify that the same answer
113005     ** is obtained in every case.
113006     */
113007     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
113008       sqlite3 *db = va_arg(ap, sqlite3*);
113009       int x = va_arg(ap,int);
113010       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
113011       break;
113012     }
113013 
113014 #ifdef SQLITE_N_KEYWORD
113015     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
113016     **
113017     ** If zWord is a keyword recognized by the parser, then return the
113018     ** number of keywords.  Or if zWord is not a keyword, return 0.
113019     **
113020     ** This test feature is only available in the amalgamation since
113021     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
113022     ** is built using separate source files.
113023     */
113024     case SQLITE_TESTCTRL_ISKEYWORD: {
113025       const char *zWord = va_arg(ap, const char*);
113026       int n = sqlite3Strlen30(zWord);
113027       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
113028       break;
113029     }
113030 #endif
113031 
113032     /* sqlite3_test_control(SQLITE_TESTCTRL_PGHDRSZ)
113033     **
113034     ** Return the size of a pcache header in bytes.
113035     */
113036     case SQLITE_TESTCTRL_PGHDRSZ: {
113037       rc = sizeof(PgHdr);
113038       break;
113039     }
113040 
113041     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
113042     **
113043     ** Pass pFree into sqlite3ScratchFree().
113044     ** If sz>0 then allocate a scratch buffer into pNew.
113045     */
113046     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
113047       void *pFree, **ppNew;
113048       int sz;
113049       sz = va_arg(ap, int);
113050       ppNew = va_arg(ap, void**);
113051       pFree = va_arg(ap, void*);
113052       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
113053       sqlite3ScratchFree(pFree);
113054       break;
113055     }
113056 
113057     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
113058     **
113059     ** If parameter onoff is non-zero, configure the wrappers so that all
113060     ** subsequent calls to localtime() and variants fail. If onoff is zero,
113061     ** undo this setting.
113062     */
113063     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
113064       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
113065       break;
113066     }
113067 
113068   }
113069   va_end(ap);
113070 #endif /* SQLITE_OMIT_BUILTIN_TEST */
113071   return rc;
113072 }
113073 
113074 /*
113075 ** This is a utility routine, useful to VFS implementations, that checks
113076 ** to see if a database file was a URI that contained a specific query
113077 ** parameter, and if so obtains the value of the query parameter.
113078 **
113079 ** The zFilename argument is the filename pointer passed into the xOpen()
113080 ** method of a VFS implementation.  The zParam argument is the name of the
113081 ** query parameter we seek.  This routine returns the value of the zParam
113082 ** parameter if it exists.  If the parameter does not exist, this routine
113083 ** returns a NULL pointer.
113084 */
113085 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
113086   zFilename += sqlite3Strlen30(zFilename) + 1;
113087   while( zFilename[0] ){
113088     int x = strcmp(zFilename, zParam);
113089     zFilename += sqlite3Strlen30(zFilename) + 1;
113090     if( x==0 ) return zFilename;
113091     zFilename += sqlite3Strlen30(zFilename) + 1;
113092   }
113093   return 0;
113094 }
113095 
113096 /************** End of main.c ************************************************/
113097 /************** Begin file notify.c ******************************************/
113098 /*
113099 ** 2009 March 3
113100 **
113101 ** The author disclaims copyright to this source code.  In place of
113102 ** a legal notice, here is a blessing:
113103 **
113104 **    May you do good and not evil.
113105 **    May you find forgiveness for yourself and forgive others.
113106 **    May you share freely, never taking more than you give.
113107 **
113108 *************************************************************************
113109 **
113110 ** This file contains the implementation of the sqlite3_unlock_notify()
113111 ** API method and its associated functionality.
113112 */
113113 
113114 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
113115 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
113116 
113117 /*
113118 ** Public interfaces:
113119 **
113120 **   sqlite3ConnectionBlocked()
113121 **   sqlite3ConnectionUnlocked()
113122 **   sqlite3ConnectionClosed()
113123 **   sqlite3_unlock_notify()
113124 */
113125 
113126 #define assertMutexHeld() \
113127   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
113128 
113129 /*
113130 ** Head of a linked list of all sqlite3 objects created by this process
113131 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
113132 ** is not NULL. This variable may only accessed while the STATIC_MASTER
113133 ** mutex is held.
113134 */
113135 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
113136 
113137 #ifndef NDEBUG
113138 /*
113139 ** This function is a complex assert() that verifies the following
113140 ** properties of the blocked connections list:
113141 **
113142 **   1) Each entry in the list has a non-NULL value for either
113143 **      pUnlockConnection or pBlockingConnection, or both.
113144 **
113145 **   2) All entries in the list that share a common value for
113146 **      xUnlockNotify are grouped together.
113147 **
113148 **   3) If the argument db is not NULL, then none of the entries in the
113149 **      blocked connections list have pUnlockConnection or pBlockingConnection
113150 **      set to db. This is used when closing connection db.
113151 */
113152 static void checkListProperties(sqlite3 *db){
113153   sqlite3 *p;
113154   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
113155     int seen = 0;
113156     sqlite3 *p2;
113157 
113158     /* Verify property (1) */
113159     assert( p->pUnlockConnection || p->pBlockingConnection );
113160 
113161     /* Verify property (2) */
113162     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
113163       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
113164       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
113165       assert( db==0 || p->pUnlockConnection!=db );
113166       assert( db==0 || p->pBlockingConnection!=db );
113167     }
113168   }
113169 }
113170 #else
113171 # define checkListProperties(x)
113172 #endif
113173 
113174 /*
113175 ** Remove connection db from the blocked connections list. If connection
113176 ** db is not currently a part of the list, this function is a no-op.
113177 */
113178 static void removeFromBlockedList(sqlite3 *db){
113179   sqlite3 **pp;
113180   assertMutexHeld();
113181   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
113182     if( *pp==db ){
113183       *pp = (*pp)->pNextBlocked;
113184       break;
113185     }
113186   }
113187 }
113188 
113189 /*
113190 ** Add connection db to the blocked connections list. It is assumed
113191 ** that it is not already a part of the list.
113192 */
113193 static void addToBlockedList(sqlite3 *db){
113194   sqlite3 **pp;
113195   assertMutexHeld();
113196   for(
113197     pp=&sqlite3BlockedList;
113198     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
113199     pp=&(*pp)->pNextBlocked
113200   );
113201   db->pNextBlocked = *pp;
113202   *pp = db;
113203 }
113204 
113205 /*
113206 ** Obtain the STATIC_MASTER mutex.
113207 */
113208 static void enterMutex(void){
113209   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
113210   checkListProperties(0);
113211 }
113212 
113213 /*
113214 ** Release the STATIC_MASTER mutex.
113215 */
113216 static void leaveMutex(void){
113217   assertMutexHeld();
113218   checkListProperties(0);
113219   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
113220 }
113221 
113222 /*
113223 ** Register an unlock-notify callback.
113224 **
113225 ** This is called after connection "db" has attempted some operation
113226 ** but has received an SQLITE_LOCKED error because another connection
113227 ** (call it pOther) in the same process was busy using the same shared
113228 ** cache.  pOther is found by looking at db->pBlockingConnection.
113229 **
113230 ** If there is no blocking connection, the callback is invoked immediately,
113231 ** before this routine returns.
113232 **
113233 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
113234 ** a deadlock.
113235 **
113236 ** Otherwise, make arrangements to invoke xNotify when pOther drops
113237 ** its locks.
113238 **
113239 ** Each call to this routine overrides any prior callbacks registered
113240 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
113241 ** cancelled.
113242 */
113243 SQLITE_API int sqlite3_unlock_notify(
113244   sqlite3 *db,
113245   void (*xNotify)(void **, int),
113246   void *pArg
113247 ){
113248   int rc = SQLITE_OK;
113249 
113250   sqlite3_mutex_enter(db->mutex);
113251   enterMutex();
113252 
113253   if( xNotify==0 ){
113254     removeFromBlockedList(db);
113255     db->pBlockingConnection = 0;
113256     db->pUnlockConnection = 0;
113257     db->xUnlockNotify = 0;
113258     db->pUnlockArg = 0;
113259   }else if( 0==db->pBlockingConnection ){
113260     /* The blocking transaction has been concluded. Or there never was a
113261     ** blocking transaction. In either case, invoke the notify callback
113262     ** immediately.
113263     */
113264     xNotify(&pArg, 1);
113265   }else{
113266     sqlite3 *p;
113267 
113268     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
113269     if( p ){
113270       rc = SQLITE_LOCKED;              /* Deadlock detected. */
113271     }else{
113272       db->pUnlockConnection = db->pBlockingConnection;
113273       db->xUnlockNotify = xNotify;
113274       db->pUnlockArg = pArg;
113275       removeFromBlockedList(db);
113276       addToBlockedList(db);
113277     }
113278   }
113279 
113280   leaveMutex();
113281   assert( !db->mallocFailed );
113282   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
113283   sqlite3_mutex_leave(db->mutex);
113284   return rc;
113285 }
113286 
113287 /*
113288 ** This function is called while stepping or preparing a statement
113289 ** associated with connection db. The operation will return SQLITE_LOCKED
113290 ** to the user because it requires a lock that will not be available
113291 ** until connection pBlocker concludes its current transaction.
113292 */
113293 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
113294   enterMutex();
113295   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
113296     addToBlockedList(db);
113297   }
113298   db->pBlockingConnection = pBlocker;
113299   leaveMutex();
113300 }
113301 
113302 /*
113303 ** This function is called when
113304 ** the transaction opened by database db has just finished. Locks held
113305 ** by database connection db have been released.
113306 **
113307 ** This function loops through each entry in the blocked connections
113308 ** list and does the following:
113309 **
113310 **   1) If the sqlite3.pBlockingConnection member of a list entry is
113311 **      set to db, then set pBlockingConnection=0.
113312 **
113313 **   2) If the sqlite3.pUnlockConnection member of a list entry is
113314 **      set to db, then invoke the configured unlock-notify callback and
113315 **      set pUnlockConnection=0.
113316 **
113317 **   3) If the two steps above mean that pBlockingConnection==0 and
113318 **      pUnlockConnection==0, remove the entry from the blocked connections
113319 **      list.
113320 */
113321 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
113322   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
113323   int nArg = 0;                            /* Number of entries in aArg[] */
113324   sqlite3 **pp;                            /* Iterator variable */
113325   void **aArg;               /* Arguments to the unlock callback */
113326   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
113327   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
113328 
113329   aArg = aStatic;
113330   enterMutex();         /* Enter STATIC_MASTER mutex */
113331 
113332   /* This loop runs once for each entry in the blocked-connections list. */
113333   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
113334     sqlite3 *p = *pp;
113335 
113336     /* Step 1. */
113337     if( p->pBlockingConnection==db ){
113338       p->pBlockingConnection = 0;
113339     }
113340 
113341     /* Step 2. */
113342     if( p->pUnlockConnection==db ){
113343       assert( p->xUnlockNotify );
113344       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
113345         xUnlockNotify(aArg, nArg);
113346         nArg = 0;
113347       }
113348 
113349       sqlite3BeginBenignMalloc();
113350       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
113351       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
113352       if( (!aDyn && nArg==(int)ArraySize(aStatic))
113353        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
113354       ){
113355         /* The aArg[] array needs to grow. */
113356         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
113357         if( pNew ){
113358           memcpy(pNew, aArg, nArg*sizeof(void *));
113359           sqlite3_free(aDyn);
113360           aDyn = aArg = pNew;
113361         }else{
113362           /* This occurs when the array of context pointers that need to
113363           ** be passed to the unlock-notify callback is larger than the
113364           ** aStatic[] array allocated on the stack and the attempt to
113365           ** allocate a larger array from the heap has failed.
113366           **
113367           ** This is a difficult situation to handle. Returning an error
113368           ** code to the caller is insufficient, as even if an error code
113369           ** is returned the transaction on connection db will still be
113370           ** closed and the unlock-notify callbacks on blocked connections
113371           ** will go unissued. This might cause the application to wait
113372           ** indefinitely for an unlock-notify callback that will never
113373           ** arrive.
113374           **
113375           ** Instead, invoke the unlock-notify callback with the context
113376           ** array already accumulated. We can then clear the array and
113377           ** begin accumulating any further context pointers without
113378           ** requiring any dynamic allocation. This is sub-optimal because
113379           ** it means that instead of one callback with a large array of
113380           ** context pointers the application will receive two or more
113381           ** callbacks with smaller arrays of context pointers, which will
113382           ** reduce the applications ability to prioritize multiple
113383           ** connections. But it is the best that can be done under the
113384           ** circumstances.
113385           */
113386           xUnlockNotify(aArg, nArg);
113387           nArg = 0;
113388         }
113389       }
113390       sqlite3EndBenignMalloc();
113391 
113392       aArg[nArg++] = p->pUnlockArg;
113393       xUnlockNotify = p->xUnlockNotify;
113394       p->pUnlockConnection = 0;
113395       p->xUnlockNotify = 0;
113396       p->pUnlockArg = 0;
113397     }
113398 
113399     /* Step 3. */
113400     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
113401       /* Remove connection p from the blocked connections list. */
113402       *pp = p->pNextBlocked;
113403       p->pNextBlocked = 0;
113404     }else{
113405       pp = &p->pNextBlocked;
113406     }
113407   }
113408 
113409   if( nArg!=0 ){
113410     xUnlockNotify(aArg, nArg);
113411   }
113412   sqlite3_free(aDyn);
113413   leaveMutex();         /* Leave STATIC_MASTER mutex */
113414 }
113415 
113416 /*
113417 ** This is called when the database connection passed as an argument is
113418 ** being closed. The connection is removed from the blocked list.
113419 */
113420 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
113421   sqlite3ConnectionUnlocked(db);
113422   enterMutex();
113423   removeFromBlockedList(db);
113424   checkListProperties(db);
113425   leaveMutex();
113426 }
113427 #endif
113428 
113429 /************** End of notify.c **********************************************/
113430 /************** Begin file fts3.c ********************************************/
113431 /*
113432 ** 2006 Oct 10
113433 **
113434 ** The author disclaims copyright to this source code.  In place of
113435 ** a legal notice, here is a blessing:
113436 **
113437 **    May you do good and not evil.
113438 **    May you find forgiveness for yourself and forgive others.
113439 **    May you share freely, never taking more than you give.
113440 **
113441 ******************************************************************************
113442 **
113443 ** This is an SQLite module implementing full-text search.
113444 */
113445 
113446 /*
113447 ** The code in this file is only compiled if:
113448 **
113449 **     * The FTS3 module is being built as an extension
113450 **       (in which case SQLITE_CORE is not defined), or
113451 **
113452 **     * The FTS3 module is being built into the core of
113453 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
113454 */
113455 
113456 /* The full-text index is stored in a series of b+tree (-like)
113457 ** structures called segments which map terms to doclists.  The
113458 ** structures are like b+trees in layout, but are constructed from the
113459 ** bottom up in optimal fashion and are not updatable.  Since trees
113460 ** are built from the bottom up, things will be described from the
113461 ** bottom up.
113462 **
113463 **
113464 **** Varints ****
113465 ** The basic unit of encoding is a variable-length integer called a
113466 ** varint.  We encode variable-length integers in little-endian order
113467 ** using seven bits * per byte as follows:
113468 **
113469 ** KEY:
113470 **         A = 0xxxxxxx    7 bits of data and one flag bit
113471 **         B = 1xxxxxxx    7 bits of data and one flag bit
113472 **
113473 **  7 bits - A
113474 ** 14 bits - BA
113475 ** 21 bits - BBA
113476 ** and so on.
113477 **
113478 ** This is similar in concept to how sqlite encodes "varints" but
113479 ** the encoding is not the same.  SQLite varints are big-endian
113480 ** are are limited to 9 bytes in length whereas FTS3 varints are
113481 ** little-endian and can be up to 10 bytes in length (in theory).
113482 **
113483 ** Example encodings:
113484 **
113485 **     1:    0x01
113486 **   127:    0x7f
113487 **   128:    0x81 0x00
113488 **
113489 **
113490 **** Document lists ****
113491 ** A doclist (document list) holds a docid-sorted list of hits for a
113492 ** given term.  Doclists hold docids and associated token positions.
113493 ** A docid is the unique integer identifier for a single document.
113494 ** A position is the index of a word within the document.  The first
113495 ** word of the document has a position of 0.
113496 **
113497 ** FTS3 used to optionally store character offsets using a compile-time
113498 ** option.  But that functionality is no longer supported.
113499 **
113500 ** A doclist is stored like this:
113501 **
113502 ** array {
113503 **   varint docid;
113504 **   array {                (position list for column 0)
113505 **     varint position;     (2 more than the delta from previous position)
113506 **   }
113507 **   array {
113508 **     varint POS_COLUMN;   (marks start of position list for new column)
113509 **     varint column;       (index of new column)
113510 **     array {
113511 **       varint position;   (2 more than the delta from previous position)
113512 **     }
113513 **   }
113514 **   varint POS_END;        (marks end of positions for this document.
113515 ** }
113516 **
113517 ** Here, array { X } means zero or more occurrences of X, adjacent in
113518 ** memory.  A "position" is an index of a token in the token stream
113519 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
113520 ** in the same logical place as the position element, and act as sentinals
113521 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
113522 ** The positions numbers are not stored literally but rather as two more
113523 ** than the difference from the prior position, or the just the position plus
113524 ** 2 for the first position.  Example:
113525 **
113526 **   label:       A B C D E  F  G H   I  J K
113527 **   value:     123 5 9 1 1 14 35 0 234 72 0
113528 **
113529 ** The 123 value is the first docid.  For column zero in this document
113530 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
113531 ** at D signals the start of a new column; the 1 at E indicates that the
113532 ** new column is column number 1.  There are two positions at 12 and 45
113533 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
113534 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
113535 ** terminates with the 0 at K.
113536 **
113537 ** A "position-list" is the list of positions for multiple columns for
113538 ** a single docid.  A "column-list" is the set of positions for a single
113539 ** column.  Hence, a position-list consists of one or more column-lists,
113540 ** a document record consists of a docid followed by a position-list and
113541 ** a doclist consists of one or more document records.
113542 **
113543 ** A bare doclist omits the position information, becoming an
113544 ** array of varint-encoded docids.
113545 **
113546 **** Segment leaf nodes ****
113547 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
113548 ** nodes are written using LeafWriter, and read using LeafReader (to
113549 ** iterate through a single leaf node's data) and LeavesReader (to
113550 ** iterate through a segment's entire leaf layer).  Leaf nodes have
113551 ** the format:
113552 **
113553 ** varint iHeight;             (height from leaf level, always 0)
113554 ** varint nTerm;               (length of first term)
113555 ** char pTerm[nTerm];          (content of first term)
113556 ** varint nDoclist;            (length of term's associated doclist)
113557 ** char pDoclist[nDoclist];    (content of doclist)
113558 ** array {
113559 **                             (further terms are delta-encoded)
113560 **   varint nPrefix;           (length of prefix shared with previous term)
113561 **   varint nSuffix;           (length of unshared suffix)
113562 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
113563 **   varint nDoclist;          (length of term's associated doclist)
113564 **   char pDoclist[nDoclist];  (content of doclist)
113565 ** }
113566 **
113567 ** Here, array { X } means zero or more occurrences of X, adjacent in
113568 ** memory.
113569 **
113570 ** Leaf nodes are broken into blocks which are stored contiguously in
113571 ** the %_segments table in sorted order.  This means that when the end
113572 ** of a node is reached, the next term is in the node with the next
113573 ** greater node id.
113574 **
113575 ** New data is spilled to a new leaf node when the current node
113576 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
113577 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
113578 ** node (a leaf node with a single term and doclist).  The goal of
113579 ** these settings is to pack together groups of small doclists while
113580 ** making it efficient to directly access large doclists.  The
113581 ** assumption is that large doclists represent terms which are more
113582 ** likely to be query targets.
113583 **
113584 ** TODO(shess) It may be useful for blocking decisions to be more
113585 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
113586 ** node rather than splitting into 2k and .5k nodes.  My intuition is
113587 ** that this might extend through 2x or 4x the pagesize.
113588 **
113589 **
113590 **** Segment interior nodes ****
113591 ** Segment interior nodes store blockids for subtree nodes and terms
113592 ** to describe what data is stored by the each subtree.  Interior
113593 ** nodes are written using InteriorWriter, and read using
113594 ** InteriorReader.  InteriorWriters are created as needed when
113595 ** SegmentWriter creates new leaf nodes, or when an interior node
113596 ** itself grows too big and must be split.  The format of interior
113597 ** nodes:
113598 **
113599 ** varint iHeight;           (height from leaf level, always >0)
113600 ** varint iBlockid;          (block id of node's leftmost subtree)
113601 ** optional {
113602 **   varint nTerm;           (length of first term)
113603 **   char pTerm[nTerm];      (content of first term)
113604 **   array {
113605 **                                (further terms are delta-encoded)
113606 **     varint nPrefix;            (length of shared prefix with previous term)
113607 **     varint nSuffix;            (length of unshared suffix)
113608 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
113609 **   }
113610 ** }
113611 **
113612 ** Here, optional { X } means an optional element, while array { X }
113613 ** means zero or more occurrences of X, adjacent in memory.
113614 **
113615 ** An interior node encodes n terms separating n+1 subtrees.  The
113616 ** subtree blocks are contiguous, so only the first subtree's blockid
113617 ** is encoded.  The subtree at iBlockid will contain all terms less
113618 ** than the first term encoded (or all terms if no term is encoded).
113619 ** Otherwise, for terms greater than or equal to pTerm[i] but less
113620 ** than pTerm[i+1], the subtree for that term will be rooted at
113621 ** iBlockid+i.  Interior nodes only store enough term data to
113622 ** distinguish adjacent children (if the rightmost term of the left
113623 ** child is "something", and the leftmost term of the right child is
113624 ** "wicked", only "w" is stored).
113625 **
113626 ** New data is spilled to a new interior node at the same height when
113627 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
113628 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
113629 ** interior nodes and making the tree too skinny.  The interior nodes
113630 ** at a given height are naturally tracked by interior nodes at
113631 ** height+1, and so on.
113632 **
113633 **
113634 **** Segment directory ****
113635 ** The segment directory in table %_segdir stores meta-information for
113636 ** merging and deleting segments, and also the root node of the
113637 ** segment's tree.
113638 **
113639 ** The root node is the top node of the segment's tree after encoding
113640 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
113641 ** This could be either a leaf node or an interior node.  If the top
113642 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
113643 ** and a new root interior node is generated (which should always fit
113644 ** within ROOT_MAX because it only needs space for 2 varints, the
113645 ** height and the blockid of the previous root).
113646 **
113647 ** The meta-information in the segment directory is:
113648 **   level               - segment level (see below)
113649 **   idx                 - index within level
113650 **                       - (level,idx uniquely identify a segment)
113651 **   start_block         - first leaf node
113652 **   leaves_end_block    - last leaf node
113653 **   end_block           - last block (including interior nodes)
113654 **   root                - contents of root node
113655 **
113656 ** If the root node is a leaf node, then start_block,
113657 ** leaves_end_block, and end_block are all 0.
113658 **
113659 **
113660 **** Segment merging ****
113661 ** To amortize update costs, segments are grouped into levels and
113662 ** merged in batches.  Each increase in level represents exponentially
113663 ** more documents.
113664 **
113665 ** New documents (actually, document updates) are tokenized and
113666 ** written individually (using LeafWriter) to a level 0 segment, with
113667 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
113668 ** level 0 segments are merged into a single level 1 segment.  Level 1
113669 ** is populated like level 0, and eventually MERGE_COUNT level 1
113670 ** segments are merged to a single level 2 segment (representing
113671 ** MERGE_COUNT^2 updates), and so on.
113672 **
113673 ** A segment merge traverses all segments at a given level in
113674 ** parallel, performing a straightforward sorted merge.  Since segment
113675 ** leaf nodes are written in to the %_segments table in order, this
113676 ** merge traverses the underlying sqlite disk structures efficiently.
113677 ** After the merge, all segment blocks from the merged level are
113678 ** deleted.
113679 **
113680 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
113681 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
113682 ** very similar performance numbers to 16 on insertion, though they're
113683 ** a tiny bit slower (perhaps due to more overhead in merge-time
113684 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
113685 ** 16, 2 about 66% slower than 16.
113686 **
113687 ** At query time, high MERGE_COUNT increases the number of segments
113688 ** which need to be scanned and merged.  For instance, with 100k docs
113689 ** inserted:
113690 **
113691 **    MERGE_COUNT   segments
113692 **       16           25
113693 **        8           12
113694 **        4           10
113695 **        2            6
113696 **
113697 ** This appears to have only a moderate impact on queries for very
113698 ** frequent terms (which are somewhat dominated by segment merge
113699 ** costs), and infrequent and non-existent terms still seem to be fast
113700 ** even with many segments.
113701 **
113702 ** TODO(shess) That said, it would be nice to have a better query-side
113703 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
113704 ** optimizations to things like doclist merging will swing the sweet
113705 ** spot around.
113706 **
113707 **
113708 **
113709 **** Handling of deletions and updates ****
113710 ** Since we're using a segmented structure, with no docid-oriented
113711 ** index into the term index, we clearly cannot simply update the term
113712 ** index when a document is deleted or updated.  For deletions, we
113713 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
113714 ** we simply write the new doclist.  Segment merges overwrite older
113715 ** data for a particular docid with newer data, so deletes or updates
113716 ** will eventually overtake the earlier data and knock it out.  The
113717 ** query logic likewise merges doclists so that newer data knocks out
113718 ** older data.
113719 **
113720 ** TODO(shess) Provide a VACUUM type operation to clear out all
113721 ** deletions and duplications.  This would basically be a forced merge
113722 ** into a single segment.
113723 */
113724 
113725 /************** Include fts3Int.h in the middle of fts3.c ********************/
113726 /************** Begin file fts3Int.h *****************************************/
113727 /*
113728 ** 2009 Nov 12
113729 **
113730 ** The author disclaims copyright to this source code.  In place of
113731 ** a legal notice, here is a blessing:
113732 **
113733 **    May you do good and not evil.
113734 **    May you find forgiveness for yourself and forgive others.
113735 **    May you share freely, never taking more than you give.
113736 **
113737 ******************************************************************************
113738 **
113739 */
113740 #ifndef _FTSINT_H
113741 #define _FTSINT_H
113742 
113743 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
113744 # define NDEBUG 1
113745 #endif
113746 
113747 /*
113748 ** FTS4 is really an extension for FTS3.  It is enabled using the
113749 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
113750 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
113751 */
113752 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
113753 # define SQLITE_ENABLE_FTS3
113754 #endif
113755 
113756 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
113757 
113758 /* If not building as part of the core, include sqlite3ext.h. */
113759 #ifndef SQLITE_CORE
113760 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
113761 #endif
113762 
113763 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
113764 /************** Begin file fts3_tokenizer.h **********************************/
113765 /*
113766 ** 2006 July 10
113767 **
113768 ** The author disclaims copyright to this source code.
113769 **
113770 *************************************************************************
113771 ** Defines the interface to tokenizers used by fulltext-search.  There
113772 ** are three basic components:
113773 **
113774 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
113775 ** interface functions.  This is essentially the class structure for
113776 ** tokenizers.
113777 **
113778 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
113779 ** including customization information defined at creation time.
113780 **
113781 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
113782 ** tokens from a particular input.
113783 */
113784 #ifndef _FTS3_TOKENIZER_H_
113785 #define _FTS3_TOKENIZER_H_
113786 
113787 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
113788 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
113789 ** we will need a way to register the API consistently.
113790 */
113791 
113792 /*
113793 ** Structures used by the tokenizer interface. When a new tokenizer
113794 ** implementation is registered, the caller provides a pointer to
113795 ** an sqlite3_tokenizer_module containing pointers to the callback
113796 ** functions that make up an implementation.
113797 **
113798 ** When an fts3 table is created, it passes any arguments passed to
113799 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
113800 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
113801 ** implementation. The xCreate() function in turn returns an
113802 ** sqlite3_tokenizer structure representing the specific tokenizer to
113803 ** be used for the fts3 table (customized by the tokenizer clause arguments).
113804 **
113805 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
113806 ** method is called. It returns an sqlite3_tokenizer_cursor object
113807 ** that may be used to tokenize a specific input buffer based on
113808 ** the tokenization rules supplied by a specific sqlite3_tokenizer
113809 ** object.
113810 */
113811 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
113812 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
113813 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
113814 
113815 struct sqlite3_tokenizer_module {
113816 
113817   /*
113818   ** Structure version. Should always be set to 0.
113819   */
113820   int iVersion;
113821 
113822   /*
113823   ** Create a new tokenizer. The values in the argv[] array are the
113824   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
113825   ** TABLE statement that created the fts3 table. For example, if
113826   ** the following SQL is executed:
113827   **
113828   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
113829   **
113830   ** then argc is set to 2, and the argv[] array contains pointers
113831   ** to the strings "arg1" and "arg2".
113832   **
113833   ** This method should return either SQLITE_OK (0), or an SQLite error
113834   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
113835   ** to point at the newly created tokenizer structure. The generic
113836   ** sqlite3_tokenizer.pModule variable should not be initialised by
113837   ** this callback. The caller will do so.
113838   */
113839   int (*xCreate)(
113840     int argc,                           /* Size of argv array */
113841     const char *const*argv,             /* Tokenizer argument strings */
113842     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
113843   );
113844 
113845   /*
113846   ** Destroy an existing tokenizer. The fts3 module calls this method
113847   ** exactly once for each successful call to xCreate().
113848   */
113849   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
113850 
113851   /*
113852   ** Create a tokenizer cursor to tokenize an input buffer. The caller
113853   ** is responsible for ensuring that the input buffer remains valid
113854   ** until the cursor is closed (using the xClose() method).
113855   */
113856   int (*xOpen)(
113857     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
113858     const char *pInput, int nBytes,      /* Input buffer */
113859     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
113860   );
113861 
113862   /*
113863   ** Destroy an existing tokenizer cursor. The fts3 module calls this
113864   ** method exactly once for each successful call to xOpen().
113865   */
113866   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
113867 
113868   /*
113869   ** Retrieve the next token from the tokenizer cursor pCursor. This
113870   ** method should either return SQLITE_OK and set the values of the
113871   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
113872   ** the end of the buffer has been reached, or an SQLite error code.
113873   **
113874   ** *ppToken should be set to point at a buffer containing the
113875   ** normalized version of the token (i.e. after any case-folding and/or
113876   ** stemming has been performed). *pnBytes should be set to the length
113877   ** of this buffer in bytes. The input text that generated the token is
113878   ** identified by the byte offsets returned in *piStartOffset and
113879   ** *piEndOffset. *piStartOffset should be set to the index of the first
113880   ** byte of the token in the input buffer. *piEndOffset should be set
113881   ** to the index of the first byte just past the end of the token in
113882   ** the input buffer.
113883   **
113884   ** The buffer *ppToken is set to point at is managed by the tokenizer
113885   ** implementation. It is only required to be valid until the next call
113886   ** to xNext() or xClose().
113887   */
113888   /* TODO(shess) current implementation requires pInput to be
113889   ** nul-terminated.  This should either be fixed, or pInput/nBytes
113890   ** should be converted to zInput.
113891   */
113892   int (*xNext)(
113893     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
113894     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
113895     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
113896     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
113897     int *piPosition      /* OUT: Number of tokens returned before this one */
113898   );
113899 };
113900 
113901 struct sqlite3_tokenizer {
113902   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
113903   /* Tokenizer implementations will typically add additional fields */
113904 };
113905 
113906 struct sqlite3_tokenizer_cursor {
113907   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
113908   /* Tokenizer implementations will typically add additional fields */
113909 };
113910 
113911 int fts3_global_term_cnt(int iTerm, int iCol);
113912 int fts3_term_cnt(int iTerm, int iCol);
113913 
113914 
113915 #endif /* _FTS3_TOKENIZER_H_ */
113916 
113917 /************** End of fts3_tokenizer.h **************************************/
113918 /************** Continuing where we left off in fts3Int.h ********************/
113919 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
113920 /************** Begin file fts3_hash.h ***************************************/
113921 /*
113922 ** 2001 September 22
113923 **
113924 ** The author disclaims copyright to this source code.  In place of
113925 ** a legal notice, here is a blessing:
113926 **
113927 **    May you do good and not evil.
113928 **    May you find forgiveness for yourself and forgive others.
113929 **    May you share freely, never taking more than you give.
113930 **
113931 *************************************************************************
113932 ** This is the header file for the generic hash-table implemenation
113933 ** used in SQLite.  We've modified it slightly to serve as a standalone
113934 ** hash table implementation for the full-text indexing module.
113935 **
113936 */
113937 #ifndef _FTS3_HASH_H_
113938 #define _FTS3_HASH_H_
113939 
113940 /* Forward declarations of structures. */
113941 typedef struct Fts3Hash Fts3Hash;
113942 typedef struct Fts3HashElem Fts3HashElem;
113943 
113944 /* A complete hash table is an instance of the following structure.
113945 ** The internals of this structure are intended to be opaque -- client
113946 ** code should not attempt to access or modify the fields of this structure
113947 ** directly.  Change this structure only by using the routines below.
113948 ** However, many of the "procedures" and "functions" for modifying and
113949 ** accessing this structure are really macros, so we can't really make
113950 ** this structure opaque.
113951 */
113952 struct Fts3Hash {
113953   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
113954   char copyKey;           /* True if copy of key made on insert */
113955   int count;              /* Number of entries in this table */
113956   Fts3HashElem *first;    /* The first element of the array */
113957   int htsize;             /* Number of buckets in the hash table */
113958   struct _fts3ht {        /* the hash table */
113959     int count;               /* Number of entries with this hash */
113960     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
113961   } *ht;
113962 };
113963 
113964 /* Each element in the hash table is an instance of the following
113965 ** structure.  All elements are stored on a single doubly-linked list.
113966 **
113967 ** Again, this structure is intended to be opaque, but it can't really
113968 ** be opaque because it is used by macros.
113969 */
113970 struct Fts3HashElem {
113971   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
113972   void *data;                /* Data associated with this element */
113973   void *pKey; int nKey;      /* Key associated with this element */
113974 };
113975 
113976 /*
113977 ** There are 2 different modes of operation for a hash table:
113978 **
113979 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
113980 **                           (including the null-terminator, if any).  Case
113981 **                           is respected in comparisons.
113982 **
113983 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
113984 **                           memcmp() is used to compare keys.
113985 **
113986 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
113987 */
113988 #define FTS3_HASH_STRING    1
113989 #define FTS3_HASH_BINARY    2
113990 
113991 /*
113992 ** Access routines.  To delete, insert a NULL pointer.
113993 */
113994 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
113995 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
113996 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
113997 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
113998 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
113999 
114000 /*
114001 ** Shorthand for the functions above
114002 */
114003 #define fts3HashInit     sqlite3Fts3HashInit
114004 #define fts3HashInsert   sqlite3Fts3HashInsert
114005 #define fts3HashFind     sqlite3Fts3HashFind
114006 #define fts3HashClear    sqlite3Fts3HashClear
114007 #define fts3HashFindElem sqlite3Fts3HashFindElem
114008 
114009 /*
114010 ** Macros for looping over all elements of a hash table.  The idiom is
114011 ** like this:
114012 **
114013 **   Fts3Hash h;
114014 **   Fts3HashElem *p;
114015 **   ...
114016 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
114017 **     SomeStructure *pData = fts3HashData(p);
114018 **     // do something with pData
114019 **   }
114020 */
114021 #define fts3HashFirst(H)  ((H)->first)
114022 #define fts3HashNext(E)   ((E)->next)
114023 #define fts3HashData(E)   ((E)->data)
114024 #define fts3HashKey(E)    ((E)->pKey)
114025 #define fts3HashKeysize(E) ((E)->nKey)
114026 
114027 /*
114028 ** Number of entries in a hash table
114029 */
114030 #define fts3HashCount(H)  ((H)->count)
114031 
114032 #endif /* _FTS3_HASH_H_ */
114033 
114034 /************** End of fts3_hash.h *******************************************/
114035 /************** Continuing where we left off in fts3Int.h ********************/
114036 
114037 /*
114038 ** This constant controls how often segments are merged. Once there are
114039 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
114040 ** segment of level N+1.
114041 */
114042 #define FTS3_MERGE_COUNT 16
114043 
114044 /*
114045 ** This is the maximum amount of data (in bytes) to store in the
114046 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
114047 ** populated as documents are inserted/updated/deleted in a transaction
114048 ** and used to create a new segment when the transaction is committed.
114049 ** However if this limit is reached midway through a transaction, a new
114050 ** segment is created and the hash table cleared immediately.
114051 */
114052 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
114053 
114054 /*
114055 ** Macro to return the number of elements in an array. SQLite has a
114056 ** similar macro called ArraySize(). Use a different name to avoid
114057 ** a collision when building an amalgamation with built-in FTS3.
114058 */
114059 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
114060 
114061 
114062 #ifndef MIN
114063 # define MIN(x,y) ((x)<(y)?(x):(y))
114064 #endif
114065 
114066 /*
114067 ** Maximum length of a varint encoded integer. The varint format is different
114068 ** from that used by SQLite, so the maximum length is 10, not 9.
114069 */
114070 #define FTS3_VARINT_MAX 10
114071 
114072 /*
114073 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
114074 ** in the document set and zero or more prefix indexes. All indexes are stored
114075 ** as one or more b+-trees in the %_segments and %_segdir tables.
114076 **
114077 ** It is possible to determine which index a b+-tree belongs to based on the
114078 ** value stored in the "%_segdir.level" column. Given this value L, the index
114079 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
114080 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
114081 ** between 1024 and 2047 to index 1, and so on.
114082 **
114083 ** It is considered impossible for an index to use more than 1024 levels. In
114084 ** theory though this may happen, but only after at least
114085 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
114086 */
114087 #define FTS3_SEGDIR_MAXLEVEL      1024
114088 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
114089 
114090 /*
114091 ** The testcase() macro is only used by the amalgamation.  If undefined,
114092 ** make it a no-op.
114093 */
114094 #ifndef testcase
114095 # define testcase(X)
114096 #endif
114097 
114098 /*
114099 ** Terminator values for position-lists and column-lists.
114100 */
114101 #define POS_COLUMN  (1)     /* Column-list terminator */
114102 #define POS_END     (0)     /* Position-list terminator */
114103 
114104 /*
114105 ** This section provides definitions to allow the
114106 ** FTS3 extension to be compiled outside of the
114107 ** amalgamation.
114108 */
114109 #ifndef SQLITE_AMALGAMATION
114110 /*
114111 ** Macros indicating that conditional expressions are always true or
114112 ** false.
114113 */
114114 #ifdef SQLITE_COVERAGE_TEST
114115 # define ALWAYS(x) (1)
114116 # define NEVER(X)  (0)
114117 #else
114118 # define ALWAYS(x) (x)
114119 # define NEVER(X)  (x)
114120 #endif
114121 
114122 /*
114123 ** Internal types used by SQLite.
114124 */
114125 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
114126 typedef short int i16;            /* 2-byte (or larger) signed integer */
114127 typedef unsigned int u32;         /* 4-byte unsigned integer */
114128 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
114129 
114130 /*
114131 ** Macro used to suppress compiler warnings for unused parameters.
114132 */
114133 #define UNUSED_PARAMETER(x) (void)(x)
114134 
114135 /*
114136 ** Activate assert() only if SQLITE_TEST is enabled.
114137 */
114138 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
114139 # define NDEBUG 1
114140 #endif
114141 
114142 /*
114143 ** The TESTONLY macro is used to enclose variable declarations or
114144 ** other bits of code that are needed to support the arguments
114145 ** within testcase() and assert() macros.
114146 */
114147 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
114148 # define TESTONLY(X)  X
114149 #else
114150 # define TESTONLY(X)
114151 #endif
114152 
114153 #endif /* SQLITE_AMALGAMATION */
114154 
114155 typedef struct Fts3Table Fts3Table;
114156 typedef struct Fts3Cursor Fts3Cursor;
114157 typedef struct Fts3Expr Fts3Expr;
114158 typedef struct Fts3Phrase Fts3Phrase;
114159 typedef struct Fts3PhraseToken Fts3PhraseToken;
114160 
114161 typedef struct Fts3Doclist Fts3Doclist;
114162 typedef struct Fts3SegFilter Fts3SegFilter;
114163 typedef struct Fts3DeferredToken Fts3DeferredToken;
114164 typedef struct Fts3SegReader Fts3SegReader;
114165 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
114166 
114167 /*
114168 ** A connection to a fulltext index is an instance of the following
114169 ** structure. The xCreate and xConnect methods create an instance
114170 ** of this structure and xDestroy and xDisconnect free that instance.
114171 ** All other methods receive a pointer to the structure as one of their
114172 ** arguments.
114173 */
114174 struct Fts3Table {
114175   sqlite3_vtab base;              /* Base class used by SQLite core */
114176   sqlite3 *db;                    /* The database connection */
114177   const char *zDb;                /* logical database name */
114178   const char *zName;              /* virtual table name */
114179   int nColumn;                    /* number of named columns in virtual table */
114180   char **azColumn;                /* column names.  malloced */
114181   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
114182 
114183   /* Precompiled statements used by the implementation. Each of these
114184   ** statements is run and reset within a single virtual table API call.
114185   */
114186   sqlite3_stmt *aStmt[27];
114187 
114188   char *zReadExprlist;
114189   char *zWriteExprlist;
114190 
114191   int nNodeSize;                  /* Soft limit for node size */
114192   u8 bHasStat;                    /* True if %_stat table exists */
114193   u8 bHasDocsize;                 /* True if %_docsize table exists */
114194   u8 bDescIdx;                    /* True if doclists are in reverse order */
114195   int nPgsz;                      /* Page size for host database */
114196   char *zSegmentsTbl;             /* Name of %_segments table */
114197   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
114198 
114199   /* TODO: Fix the first paragraph of this comment.
114200   **
114201   ** The following hash table is used to buffer pending index updates during
114202   ** transactions. Variable nPendingData estimates the memory size of the
114203   ** pending data, including hash table overhead, but not malloc overhead.
114204   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
114205   ** automatically. Variable iPrevDocid is the docid of the most recently
114206   ** inserted record.
114207   **
114208   ** A single FTS4 table may have multiple full-text indexes. For each index
114209   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
114210   ** terms that appear in the document set. Each subsequent index in aIndex[]
114211   ** is an index of prefixes of a specific length.
114212   */
114213   int nIndex;                     /* Size of aIndex[] */
114214   struct Fts3Index {
114215     int nPrefix;                  /* Prefix length (0 for main terms index) */
114216     Fts3Hash hPending;            /* Pending terms table for this index */
114217   } *aIndex;
114218   int nMaxPendingData;            /* Max pending data before flush to disk */
114219   int nPendingData;               /* Current bytes of pending data */
114220   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
114221 
114222 #if defined(SQLITE_DEBUG)
114223   /* State variables used for validating that the transaction control
114224   ** methods of the virtual table are called at appropriate times.  These
114225   ** values do not contribution to the FTS computation; they are used for
114226   ** verifying the SQLite core.
114227   */
114228   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
114229   int mxSavepoint;       /* Largest valid xSavepoint integer */
114230 #endif
114231 };
114232 
114233 /*
114234 ** When the core wants to read from the virtual table, it creates a
114235 ** virtual table cursor (an instance of the following structure) using
114236 ** the xOpen method. Cursors are destroyed using the xClose method.
114237 */
114238 struct Fts3Cursor {
114239   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
114240   i16 eSearch;                    /* Search strategy (see below) */
114241   u8 isEof;                       /* True if at End Of Results */
114242   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
114243   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
114244   Fts3Expr *pExpr;                /* Parsed MATCH query string */
114245   int nPhrase;                    /* Number of matchable phrases in query */
114246   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
114247   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
114248   char *pNextId;                  /* Pointer into the body of aDoclist */
114249   char *aDoclist;                 /* List of docids for full-text queries */
114250   int nDoclist;                   /* Size of buffer at aDoclist */
114251   u8 bDesc;                       /* True to sort in descending order */
114252   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
114253   int nRowAvg;                    /* Average size of database rows, in pages */
114254   sqlite3_int64 nDoc;             /* Documents in table */
114255 
114256   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
114257   u32 *aMatchinfo;                /* Information about most recent match */
114258   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
114259   char *zMatchinfo;               /* Matchinfo specification */
114260 };
114261 
114262 #define FTS3_EVAL_FILTER    0
114263 #define FTS3_EVAL_NEXT      1
114264 #define FTS3_EVAL_MATCHINFO 2
114265 
114266 /*
114267 ** The Fts3Cursor.eSearch member is always set to one of the following.
114268 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
114269 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
114270 ** of the column to be searched.  For example, in
114271 **
114272 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
114273 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
114274 **
114275 ** Because the LHS of the MATCH operator is 2nd column "b",
114276 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
114277 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
114278 ** indicating that all columns should be searched,
114279 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
114280 */
114281 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
114282 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
114283 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
114284 
114285 
114286 struct Fts3Doclist {
114287   char *aAll;                    /* Array containing doclist (or NULL) */
114288   int nAll;                      /* Size of a[] in bytes */
114289   char *pNextDocid;              /* Pointer to next docid */
114290 
114291   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
114292   int bFreeList;                 /* True if pList should be sqlite3_free()d */
114293   char *pList;                   /* Pointer to position list following iDocid */
114294   int nList;                     /* Length of position list */
114295 };
114296 
114297 /*
114298 ** A "phrase" is a sequence of one or more tokens that must match in
114299 ** sequence.  A single token is the base case and the most common case.
114300 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
114301 ** nToken will be the number of tokens in the string.
114302 */
114303 struct Fts3PhraseToken {
114304   char *z;                        /* Text of the token */
114305   int n;                          /* Number of bytes in buffer z */
114306   int isPrefix;                   /* True if token ends with a "*" character */
114307 
114308   /* Variables above this point are populated when the expression is
114309   ** parsed (by code in fts3_expr.c). Below this point the variables are
114310   ** used when evaluating the expression. */
114311   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
114312   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
114313 };
114314 
114315 struct Fts3Phrase {
114316   /* Cache of doclist for this phrase. */
114317   Fts3Doclist doclist;
114318   int bIncr;                 /* True if doclist is loaded incrementally */
114319   int iDoclistToken;
114320 
114321   /* Variables below this point are populated by fts3_expr.c when parsing
114322   ** a MATCH expression. Everything above is part of the evaluation phase.
114323   */
114324   int nToken;                /* Number of tokens in the phrase */
114325   int iColumn;               /* Index of column this phrase must match */
114326   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
114327 };
114328 
114329 /*
114330 ** A tree of these objects forms the RHS of a MATCH operator.
114331 **
114332 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
114333 ** points to a malloced buffer, size nDoclist bytes, containing the results
114334 ** of this phrase query in FTS3 doclist format. As usual, the initial
114335 ** "Length" field found in doclists stored on disk is omitted from this
114336 ** buffer.
114337 **
114338 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
114339 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
114340 ** where nCol is the number of columns in the queried FTS table. The array
114341 ** is populated as follows:
114342 **
114343 **   aMI[iCol*3 + 0] = Undefined
114344 **   aMI[iCol*3 + 1] = Number of occurrences
114345 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
114346 **
114347 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
114348 ** when the expression node is.
114349 */
114350 struct Fts3Expr {
114351   int eType;                 /* One of the FTSQUERY_XXX values defined below */
114352   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
114353   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
114354   Fts3Expr *pLeft;           /* Left operand */
114355   Fts3Expr *pRight;          /* Right operand */
114356   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
114357 
114358   /* The following are used by the fts3_eval.c module. */
114359   sqlite3_int64 iDocid;      /* Current docid */
114360   u8 bEof;                   /* True this expression is at EOF already */
114361   u8 bStart;                 /* True if iDocid is valid */
114362   u8 bDeferred;              /* True if this expression is entirely deferred */
114363 
114364   u32 *aMI;
114365 };
114366 
114367 /*
114368 ** Candidate values for Fts3Query.eType. Note that the order of the first
114369 ** four values is in order of precedence when parsing expressions. For
114370 ** example, the following:
114371 **
114372 **   "a OR b AND c NOT d NEAR e"
114373 **
114374 ** is equivalent to:
114375 **
114376 **   "a OR (b AND (c NOT (d NEAR e)))"
114377 */
114378 #define FTSQUERY_NEAR   1
114379 #define FTSQUERY_NOT    2
114380 #define FTSQUERY_AND    3
114381 #define FTSQUERY_OR     4
114382 #define FTSQUERY_PHRASE 5
114383 
114384 
114385 /* fts3_write.c */
114386 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
114387 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
114388 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
114389 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
114390 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, sqlite3_int64,
114391   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
114392 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
114393   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
114394 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
114395 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, sqlite3_stmt **);
114396 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
114397 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
114398 
114399 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
114400 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
114401 
114402 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
114403 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
114404 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
114405 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
114406 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
114407 
114408 /* Special values interpreted by sqlite3SegReaderCursor() */
114409 #define FTS3_SEGCURSOR_PENDING        -1
114410 #define FTS3_SEGCURSOR_ALL            -2
114411 
114412 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
114413 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
114414 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
114415 
114416 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
114417     Fts3Table *, int, int, const char *, int, int, int, Fts3MultiSegReader *);
114418 
114419 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
114420 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
114421 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
114422 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
114423 #define FTS3_SEGMENT_PREFIX        0x00000008
114424 #define FTS3_SEGMENT_SCAN          0x00000010
114425 
114426 /* Type passed as 4th argument to SegmentReaderIterate() */
114427 struct Fts3SegFilter {
114428   const char *zTerm;
114429   int nTerm;
114430   int iCol;
114431   int flags;
114432 };
114433 
114434 struct Fts3MultiSegReader {
114435   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
114436   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
114437   int nSegment;                   /* Size of apSegment array */
114438   int nAdvance;                   /* How many seg-readers to advance */
114439   Fts3SegFilter *pFilter;         /* Pointer to filter object */
114440   char *aBuffer;                  /* Buffer to merge doclists in */
114441   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
114442 
114443   int iColFilter;                 /* If >=0, filter for this column */
114444   int bRestart;
114445 
114446   /* Used by fts3.c only. */
114447   int nCost;                      /* Cost of running iterator */
114448   int bLookup;                    /* True if a lookup of a single entry. */
114449 
114450   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
114451   char *zTerm;                    /* Pointer to term buffer */
114452   int nTerm;                      /* Size of zTerm in bytes */
114453   char *aDoclist;                 /* Pointer to doclist buffer */
114454   int nDoclist;                   /* Size of aDoclist[] in bytes */
114455 };
114456 
114457 /* fts3.c */
114458 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
114459 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
114460 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
114461 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
114462 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
114463 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
114464 
114465 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
114466 
114467 /* fts3_tokenizer.c */
114468 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
114469 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
114470 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
114471     sqlite3_tokenizer **, char **
114472 );
114473 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
114474 
114475 /* fts3_snippet.c */
114476 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
114477 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
114478   const char *, const char *, int, int
114479 );
114480 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
114481 
114482 /* fts3_expr.c */
114483 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
114484   char **, int, int, const char *, int, Fts3Expr **
114485 );
114486 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
114487 #ifdef SQLITE_TEST
114488 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
114489 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
114490 #endif
114491 
114492 /* fts3_aux.c */
114493 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
114494 
114495 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
114496 
114497 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
114498     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
114499 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
114500     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
114501 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
114502 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
114503 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
114504 
114505 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
114506 
114507 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
114508 #endif /* _FTSINT_H */
114509 
114510 /************** End of fts3Int.h *********************************************/
114511 /************** Continuing where we left off in fts3.c ***********************/
114512 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
114513 
114514 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
114515 # define SQLITE_CORE 1
114516 #endif
114517 
114518 /* #include <assert.h> */
114519 /* #include <stdlib.h> */
114520 /* #include <stddef.h> */
114521 /* #include <stdio.h> */
114522 /* #include <string.h> */
114523 /* #include <stdarg.h> */
114524 
114525 #ifndef SQLITE_CORE
114526   SQLITE_EXTENSION_INIT1
114527 #endif
114528 
114529 static int fts3EvalNext(Fts3Cursor *pCsr);
114530 static int fts3EvalStart(Fts3Cursor *pCsr);
114531 static int fts3TermSegReaderCursor(
114532     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
114533 
114534 /*
114535 ** Write a 64-bit variable-length integer to memory starting at p[0].
114536 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
114537 ** The number of bytes written is returned.
114538 */
114539 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
114540   unsigned char *q = (unsigned char *) p;
114541   sqlite_uint64 vu = v;
114542   do{
114543     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
114544     vu >>= 7;
114545   }while( vu!=0 );
114546   q[-1] &= 0x7f;  /* turn off high bit in final byte */
114547   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
114548   return (int) (q - (unsigned char *)p);
114549 }
114550 
114551 /*
114552 ** Read a 64-bit variable-length integer from memory starting at p[0].
114553 ** Return the number of bytes read, or 0 on error.
114554 ** The value is stored in *v.
114555 */
114556 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
114557   const unsigned char *q = (const unsigned char *) p;
114558   sqlite_uint64 x = 0, y = 1;
114559   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
114560     x += y * (*q++ & 0x7f);
114561     y <<= 7;
114562   }
114563   x += y * (*q++);
114564   *v = (sqlite_int64) x;
114565   return (int) (q - (unsigned char *)p);
114566 }
114567 
114568 /*
114569 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
114570 ** 32-bit integer before it is returned.
114571 */
114572 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
114573  sqlite_int64 i;
114574  int ret = sqlite3Fts3GetVarint(p, &i);
114575  *pi = (int) i;
114576  return ret;
114577 }
114578 
114579 /*
114580 ** Return the number of bytes required to encode v as a varint
114581 */
114582 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
114583   int i = 0;
114584   do{
114585     i++;
114586     v >>= 7;
114587   }while( v!=0 );
114588   return i;
114589 }
114590 
114591 /*
114592 ** Convert an SQL-style quoted string into a normal string by removing
114593 ** the quote characters.  The conversion is done in-place.  If the
114594 ** input does not begin with a quote character, then this routine
114595 ** is a no-op.
114596 **
114597 ** Examples:
114598 **
114599 **     "abc"   becomes   abc
114600 **     'xyz'   becomes   xyz
114601 **     [pqr]   becomes   pqr
114602 **     `mno`   becomes   mno
114603 **
114604 */
114605 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
114606   char quote;                     /* Quote character (if any ) */
114607 
114608   quote = z[0];
114609   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
114610     int iIn = 1;                  /* Index of next byte to read from input */
114611     int iOut = 0;                 /* Index of next byte to write to output */
114612 
114613     /* If the first byte was a '[', then the close-quote character is a ']' */
114614     if( quote=='[' ) quote = ']';
114615 
114616     while( ALWAYS(z[iIn]) ){
114617       if( z[iIn]==quote ){
114618         if( z[iIn+1]!=quote ) break;
114619         z[iOut++] = quote;
114620         iIn += 2;
114621       }else{
114622         z[iOut++] = z[iIn++];
114623       }
114624     }
114625     z[iOut] = '\0';
114626   }
114627 }
114628 
114629 /*
114630 ** Read a single varint from the doclist at *pp and advance *pp to point
114631 ** to the first byte past the end of the varint.  Add the value of the varint
114632 ** to *pVal.
114633 */
114634 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
114635   sqlite3_int64 iVal;
114636   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
114637   *pVal += iVal;
114638 }
114639 
114640 /*
114641 ** When this function is called, *pp points to the first byte following a
114642 ** varint that is part of a doclist (or position-list, or any other list
114643 ** of varints). This function moves *pp to point to the start of that varint,
114644 ** and sets *pVal by the varint value.
114645 **
114646 ** Argument pStart points to the first byte of the doclist that the
114647 ** varint is part of.
114648 */
114649 static void fts3GetReverseVarint(
114650   char **pp,
114651   char *pStart,
114652   sqlite3_int64 *pVal
114653 ){
114654   sqlite3_int64 iVal;
114655   char *p = *pp;
114656 
114657   /* Pointer p now points at the first byte past the varint we are
114658   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
114659   ** clear on character p[-1]. */
114660   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
114661   p++;
114662   *pp = p;
114663 
114664   sqlite3Fts3GetVarint(p, &iVal);
114665   *pVal = iVal;
114666 }
114667 
114668 /*
114669 ** The xDisconnect() virtual table method.
114670 */
114671 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
114672   Fts3Table *p = (Fts3Table *)pVtab;
114673   int i;
114674 
114675   assert( p->nPendingData==0 );
114676   assert( p->pSegments==0 );
114677 
114678   /* Free any prepared statements held */
114679   for(i=0; i<SizeofArray(p->aStmt); i++){
114680     sqlite3_finalize(p->aStmt[i]);
114681   }
114682   sqlite3_free(p->zSegmentsTbl);
114683   sqlite3_free(p->zReadExprlist);
114684   sqlite3_free(p->zWriteExprlist);
114685 
114686   /* Invoke the tokenizer destructor to free the tokenizer. */
114687   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
114688 
114689   sqlite3_free(p);
114690   return SQLITE_OK;
114691 }
114692 
114693 /*
114694 ** Construct one or more SQL statements from the format string given
114695 ** and then evaluate those statements. The success code is written
114696 ** into *pRc.
114697 **
114698 ** If *pRc is initially non-zero then this routine is a no-op.
114699 */
114700 static void fts3DbExec(
114701   int *pRc,              /* Success code */
114702   sqlite3 *db,           /* Database in which to run SQL */
114703   const char *zFormat,   /* Format string for SQL */
114704   ...                    /* Arguments to the format string */
114705 ){
114706   va_list ap;
114707   char *zSql;
114708   if( *pRc ) return;
114709   va_start(ap, zFormat);
114710   zSql = sqlite3_vmprintf(zFormat, ap);
114711   va_end(ap);
114712   if( zSql==0 ){
114713     *pRc = SQLITE_NOMEM;
114714   }else{
114715     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
114716     sqlite3_free(zSql);
114717   }
114718 }
114719 
114720 /*
114721 ** The xDestroy() virtual table method.
114722 */
114723 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
114724   int rc = SQLITE_OK;              /* Return code */
114725   Fts3Table *p = (Fts3Table *)pVtab;
114726   sqlite3 *db = p->db;
114727 
114728   /* Drop the shadow tables */
114729   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
114730   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
114731   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
114732   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
114733   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
114734 
114735   /* If everything has worked, invoke fts3DisconnectMethod() to free the
114736   ** memory associated with the Fts3Table structure and return SQLITE_OK.
114737   ** Otherwise, return an SQLite error code.
114738   */
114739   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
114740 }
114741 
114742 
114743 /*
114744 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
114745 ** passed as the first argument. This is done as part of the xConnect()
114746 ** and xCreate() methods.
114747 **
114748 ** If *pRc is non-zero when this function is called, it is a no-op.
114749 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
114750 ** before returning.
114751 */
114752 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
114753   if( *pRc==SQLITE_OK ){
114754     int i;                        /* Iterator variable */
114755     int rc;                       /* Return code */
114756     char *zSql;                   /* SQL statement passed to declare_vtab() */
114757     char *zCols;                  /* List of user defined columns */
114758 
114759     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
114760 
114761     /* Create a list of user columns for the virtual table */
114762     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
114763     for(i=1; zCols && i<p->nColumn; i++){
114764       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
114765     }
114766 
114767     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
114768     zSql = sqlite3_mprintf(
114769         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
114770     );
114771     if( !zCols || !zSql ){
114772       rc = SQLITE_NOMEM;
114773     }else{
114774       rc = sqlite3_declare_vtab(p->db, zSql);
114775     }
114776 
114777     sqlite3_free(zSql);
114778     sqlite3_free(zCols);
114779     *pRc = rc;
114780   }
114781 }
114782 
114783 /*
114784 ** Create the backing store tables (%_content, %_segments and %_segdir)
114785 ** required by the FTS3 table passed as the only argument. This is done
114786 ** as part of the vtab xCreate() method.
114787 **
114788 ** If the p->bHasDocsize boolean is true (indicating that this is an
114789 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
114790 ** %_stat tables required by FTS4.
114791 */
114792 static int fts3CreateTables(Fts3Table *p){
114793   int rc = SQLITE_OK;             /* Return code */
114794   int i;                          /* Iterator variable */
114795   char *zContentCols;             /* Columns of %_content table */
114796   sqlite3 *db = p->db;            /* The database connection */
114797 
114798   /* Create a list of user columns for the content table */
114799   zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
114800   for(i=0; zContentCols && i<p->nColumn; i++){
114801     char *z = p->azColumn[i];
114802     zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
114803   }
114804   if( zContentCols==0 ) rc = SQLITE_NOMEM;
114805 
114806   /* Create the content table */
114807   fts3DbExec(&rc, db,
114808      "CREATE TABLE %Q.'%q_content'(%s)",
114809      p->zDb, p->zName, zContentCols
114810   );
114811   sqlite3_free(zContentCols);
114812   /* Create other tables */
114813   fts3DbExec(&rc, db,
114814       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
114815       p->zDb, p->zName
114816   );
114817   fts3DbExec(&rc, db,
114818       "CREATE TABLE %Q.'%q_segdir'("
114819         "level INTEGER,"
114820         "idx INTEGER,"
114821         "start_block INTEGER,"
114822         "leaves_end_block INTEGER,"
114823         "end_block INTEGER,"
114824         "root BLOB,"
114825         "PRIMARY KEY(level, idx)"
114826       ");",
114827       p->zDb, p->zName
114828   );
114829   if( p->bHasDocsize ){
114830     fts3DbExec(&rc, db,
114831         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
114832         p->zDb, p->zName
114833     );
114834   }
114835   if( p->bHasStat ){
114836     fts3DbExec(&rc, db,
114837         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
114838         p->zDb, p->zName
114839     );
114840   }
114841   return rc;
114842 }
114843 
114844 /*
114845 ** Store the current database page-size in bytes in p->nPgsz.
114846 **
114847 ** If *pRc is non-zero when this function is called, it is a no-op.
114848 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
114849 ** before returning.
114850 */
114851 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
114852   if( *pRc==SQLITE_OK ){
114853     int rc;                       /* Return code */
114854     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
114855     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
114856 
114857     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
114858     if( !zSql ){
114859       rc = SQLITE_NOMEM;
114860     }else{
114861       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
114862       if( rc==SQLITE_OK ){
114863         sqlite3_step(pStmt);
114864         p->nPgsz = sqlite3_column_int(pStmt, 0);
114865         rc = sqlite3_finalize(pStmt);
114866       }else if( rc==SQLITE_AUTH ){
114867         p->nPgsz = 1024;
114868         rc = SQLITE_OK;
114869       }
114870     }
114871     assert( p->nPgsz>0 || rc!=SQLITE_OK );
114872     sqlite3_free(zSql);
114873     *pRc = rc;
114874   }
114875 }
114876 
114877 /*
114878 ** "Special" FTS4 arguments are column specifications of the following form:
114879 **
114880 **   <key> = <value>
114881 **
114882 ** There may not be whitespace surrounding the "=" character. The <value>
114883 ** term may be quoted, but the <key> may not.
114884 */
114885 static int fts3IsSpecialColumn(
114886   const char *z,
114887   int *pnKey,
114888   char **pzValue
114889 ){
114890   char *zValue;
114891   const char *zCsr = z;
114892 
114893   while( *zCsr!='=' ){
114894     if( *zCsr=='\0' ) return 0;
114895     zCsr++;
114896   }
114897 
114898   *pnKey = (int)(zCsr-z);
114899   zValue = sqlite3_mprintf("%s", &zCsr[1]);
114900   if( zValue ){
114901     sqlite3Fts3Dequote(zValue);
114902   }
114903   *pzValue = zValue;
114904   return 1;
114905 }
114906 
114907 /*
114908 ** Append the output of a printf() style formatting to an existing string.
114909 */
114910 static void fts3Appendf(
114911   int *pRc,                       /* IN/OUT: Error code */
114912   char **pz,                      /* IN/OUT: Pointer to string buffer */
114913   const char *zFormat,            /* Printf format string to append */
114914   ...                             /* Arguments for printf format string */
114915 ){
114916   if( *pRc==SQLITE_OK ){
114917     va_list ap;
114918     char *z;
114919     va_start(ap, zFormat);
114920     z = sqlite3_vmprintf(zFormat, ap);
114921     if( z && *pz ){
114922       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
114923       sqlite3_free(z);
114924       z = z2;
114925     }
114926     if( z==0 ) *pRc = SQLITE_NOMEM;
114927     sqlite3_free(*pz);
114928     *pz = z;
114929   }
114930 }
114931 
114932 /*
114933 ** Return a copy of input string zInput enclosed in double-quotes (") and
114934 ** with all double quote characters escaped. For example:
114935 **
114936 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
114937 **
114938 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
114939 ** is the callers responsibility to call sqlite3_free() to release this
114940 ** memory.
114941 */
114942 static char *fts3QuoteId(char const *zInput){
114943   int nRet;
114944   char *zRet;
114945   nRet = 2 + strlen(zInput)*2 + 1;
114946   zRet = sqlite3_malloc(nRet);
114947   if( zRet ){
114948     int i;
114949     char *z = zRet;
114950     *(z++) = '"';
114951     for(i=0; zInput[i]; i++){
114952       if( zInput[i]=='"' ) *(z++) = '"';
114953       *(z++) = zInput[i];
114954     }
114955     *(z++) = '"';
114956     *(z++) = '\0';
114957   }
114958   return zRet;
114959 }
114960 
114961 /*
114962 ** Return a list of comma separated SQL expressions that could be used
114963 ** in a SELECT statement such as the following:
114964 **
114965 **     SELECT <list of expressions> FROM %_content AS x ...
114966 **
114967 ** to return the docid, followed by each column of text data in order
114968 ** from left to write. If parameter zFunc is not NULL, then instead of
114969 ** being returned directly each column of text data is passed to an SQL
114970 ** function named zFunc first. For example, if zFunc is "unzip" and the
114971 ** table has the three user-defined columns "a", "b", and "c", the following
114972 ** string is returned:
114973 **
114974 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c')"
114975 **
114976 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
114977 ** is the responsibility of the caller to eventually free it.
114978 **
114979 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
114980 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
114981 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
114982 ** no error occurs, *pRc is left unmodified.
114983 */
114984 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
114985   char *zRet = 0;
114986   char *zFree = 0;
114987   char *zFunction;
114988   int i;
114989 
114990   if( !zFunc ){
114991     zFunction = "";
114992   }else{
114993     zFree = zFunction = fts3QuoteId(zFunc);
114994   }
114995   fts3Appendf(pRc, &zRet, "docid");
114996   for(i=0; i<p->nColumn; i++){
114997     fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
114998   }
114999   sqlite3_free(zFree);
115000   return zRet;
115001 }
115002 
115003 /*
115004 ** Return a list of N comma separated question marks, where N is the number
115005 ** of columns in the %_content table (one for the docid plus one for each
115006 ** user-defined text column).
115007 **
115008 ** If argument zFunc is not NULL, then all but the first question mark
115009 ** is preceded by zFunc and an open bracket, and followed by a closed
115010 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
115011 ** user-defined text columns, the following string is returned:
115012 **
115013 **     "?, zip(?), zip(?), zip(?)"
115014 **
115015 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
115016 ** is the responsibility of the caller to eventually free it.
115017 **
115018 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
115019 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
115020 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
115021 ** no error occurs, *pRc is left unmodified.
115022 */
115023 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
115024   char *zRet = 0;
115025   char *zFree = 0;
115026   char *zFunction;
115027   int i;
115028 
115029   if( !zFunc ){
115030     zFunction = "";
115031   }else{
115032     zFree = zFunction = fts3QuoteId(zFunc);
115033   }
115034   fts3Appendf(pRc, &zRet, "?");
115035   for(i=0; i<p->nColumn; i++){
115036     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
115037   }
115038   sqlite3_free(zFree);
115039   return zRet;
115040 }
115041 
115042 /*
115043 ** This function interprets the string at (*pp) as a non-negative integer
115044 ** value. It reads the integer and sets *pnOut to the value read, then
115045 ** sets *pp to point to the byte immediately following the last byte of
115046 ** the integer value.
115047 **
115048 ** Only decimal digits ('0'..'9') may be part of an integer value.
115049 **
115050 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
115051 ** the output value undefined. Otherwise SQLITE_OK is returned.
115052 **
115053 ** This function is used when parsing the "prefix=" FTS4 parameter.
115054 */
115055 static int fts3GobbleInt(const char **pp, int *pnOut){
115056   const char *p = *pp;            /* Iterator pointer */
115057   int nInt = 0;                   /* Output value */
115058 
115059   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
115060     nInt = nInt * 10 + (p[0] - '0');
115061   }
115062   if( p==*pp ) return SQLITE_ERROR;
115063   *pnOut = nInt;
115064   *pp = p;
115065   return SQLITE_OK;
115066 }
115067 
115068 /*
115069 ** This function is called to allocate an array of Fts3Index structures
115070 ** representing the indexes maintained by the current FTS table. FTS tables
115071 ** always maintain the main "terms" index, but may also maintain one or
115072 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
115073 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
115074 **
115075 ** Argument zParam is passed the value of the "prefix=" option if one was
115076 ** specified, or NULL otherwise.
115077 **
115078 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
115079 ** the allocated array. *pnIndex is set to the number of elements in the
115080 ** array. If an error does occur, an SQLite error code is returned.
115081 **
115082 ** Regardless of whether or not an error is returned, it is the responsibility
115083 ** of the caller to call sqlite3_free() on the output array to free it.
115084 */
115085 static int fts3PrefixParameter(
115086   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
115087   int *pnIndex,                   /* OUT: size of *apIndex[] array */
115088   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
115089 ){
115090   struct Fts3Index *aIndex;       /* Allocated array */
115091   int nIndex = 1;                 /* Number of entries in array */
115092 
115093   if( zParam && zParam[0] ){
115094     const char *p;
115095     nIndex++;
115096     for(p=zParam; *p; p++){
115097       if( *p==',' ) nIndex++;
115098     }
115099   }
115100 
115101   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
115102   *apIndex = aIndex;
115103   *pnIndex = nIndex;
115104   if( !aIndex ){
115105     return SQLITE_NOMEM;
115106   }
115107 
115108   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
115109   if( zParam ){
115110     const char *p = zParam;
115111     int i;
115112     for(i=1; i<nIndex; i++){
115113       int nPrefix;
115114       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
115115       aIndex[i].nPrefix = nPrefix;
115116       p++;
115117     }
115118   }
115119 
115120   return SQLITE_OK;
115121 }
115122 
115123 /*
115124 ** This function is the implementation of both the xConnect and xCreate
115125 ** methods of the FTS3 virtual table.
115126 **
115127 ** The argv[] array contains the following:
115128 **
115129 **   argv[0]   -> module name  ("fts3" or "fts4")
115130 **   argv[1]   -> database name
115131 **   argv[2]   -> table name
115132 **   argv[...] -> "column name" and other module argument fields.
115133 */
115134 static int fts3InitVtab(
115135   int isCreate,                   /* True for xCreate, false for xConnect */
115136   sqlite3 *db,                    /* The SQLite database connection */
115137   void *pAux,                     /* Hash table containing tokenizers */
115138   int argc,                       /* Number of elements in argv array */
115139   const char * const *argv,       /* xCreate/xConnect argument array */
115140   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
115141   char **pzErr                    /* Write any error message here */
115142 ){
115143   Fts3Hash *pHash = (Fts3Hash *)pAux;
115144   Fts3Table *p = 0;               /* Pointer to allocated vtab */
115145   int rc = SQLITE_OK;             /* Return code */
115146   int i;                          /* Iterator variable */
115147   int nByte;                      /* Size of allocation used for *p */
115148   int iCol;                       /* Column index */
115149   int nString = 0;                /* Bytes required to hold all column names */
115150   int nCol = 0;                   /* Number of columns in the FTS table */
115151   char *zCsr;                     /* Space for holding column names */
115152   int nDb;                        /* Bytes required to hold database name */
115153   int nName;                      /* Bytes required to hold table name */
115154   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
115155   const char **aCol;              /* Array of column names */
115156   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
115157 
115158   int nIndex;                     /* Size of aIndex[] array */
115159   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
115160 
115161   /* The results of parsing supported FTS4 key=value options: */
115162   int bNoDocsize = 0;             /* True to omit %_docsize table */
115163   int bDescIdx = 0;               /* True to store descending indexes */
115164   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
115165   char *zCompress = 0;            /* compress=? parameter (or NULL) */
115166   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
115167 
115168   assert( strlen(argv[0])==4 );
115169   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
115170        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
115171   );
115172 
115173   nDb = (int)strlen(argv[1]) + 1;
115174   nName = (int)strlen(argv[2]) + 1;
115175 
115176   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
115177   if( !aCol ) return SQLITE_NOMEM;
115178   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
115179 
115180   /* Loop through all of the arguments passed by the user to the FTS3/4
115181   ** module (i.e. all the column names and special arguments). This loop
115182   ** does the following:
115183   **
115184   **   + Figures out the number of columns the FTSX table will have, and
115185   **     the number of bytes of space that must be allocated to store copies
115186   **     of the column names.
115187   **
115188   **   + If there is a tokenizer specification included in the arguments,
115189   **     initializes the tokenizer pTokenizer.
115190   */
115191   for(i=3; rc==SQLITE_OK && i<argc; i++){
115192     char const *z = argv[i];
115193     int nKey;
115194     char *zVal;
115195 
115196     /* Check if this is a tokenizer specification */
115197     if( !pTokenizer
115198      && strlen(z)>8
115199      && 0==sqlite3_strnicmp(z, "tokenize", 8)
115200      && 0==sqlite3Fts3IsIdChar(z[8])
115201     ){
115202       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
115203     }
115204 
115205     /* Check if it is an FTS4 special argument. */
115206     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
115207       struct Fts4Option {
115208         const char *zOpt;
115209         int nOpt;
115210         char **pzVar;
115211       } aFts4Opt[] = {
115212         { "matchinfo",   9, 0 },            /* 0 -> MATCHINFO */
115213         { "prefix",      6, 0 },            /* 1 -> PREFIX */
115214         { "compress",    8, 0 },            /* 2 -> COMPRESS */
115215         { "uncompress", 10, 0 },            /* 3 -> UNCOMPRESS */
115216         { "order",       5, 0 }             /* 4 -> ORDER */
115217       };
115218 
115219       int iOpt;
115220       if( !zVal ){
115221         rc = SQLITE_NOMEM;
115222       }else{
115223         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
115224           struct Fts4Option *pOp = &aFts4Opt[iOpt];
115225           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
115226             break;
115227           }
115228         }
115229         if( iOpt==SizeofArray(aFts4Opt) ){
115230           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
115231           rc = SQLITE_ERROR;
115232         }else{
115233           switch( iOpt ){
115234             case 0:               /* MATCHINFO */
115235               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
115236                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
115237                 rc = SQLITE_ERROR;
115238               }
115239               bNoDocsize = 1;
115240               break;
115241 
115242             case 1:               /* PREFIX */
115243               sqlite3_free(zPrefix);
115244               zPrefix = zVal;
115245               zVal = 0;
115246               break;
115247 
115248             case 2:               /* COMPRESS */
115249               sqlite3_free(zCompress);
115250               zCompress = zVal;
115251               zVal = 0;
115252               break;
115253 
115254             case 3:               /* UNCOMPRESS */
115255               sqlite3_free(zUncompress);
115256               zUncompress = zVal;
115257               zVal = 0;
115258               break;
115259 
115260             case 4:               /* ORDER */
115261               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
115262                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 3))
115263               ){
115264                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
115265                 rc = SQLITE_ERROR;
115266               }
115267               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
115268               break;
115269           }
115270         }
115271         sqlite3_free(zVal);
115272       }
115273     }
115274 
115275     /* Otherwise, the argument is a column name. */
115276     else {
115277       nString += (int)(strlen(z) + 1);
115278       aCol[nCol++] = z;
115279     }
115280   }
115281   if( rc!=SQLITE_OK ) goto fts3_init_out;
115282 
115283   if( nCol==0 ){
115284     assert( nString==0 );
115285     aCol[0] = "content";
115286     nString = 8;
115287     nCol = 1;
115288   }
115289 
115290   if( pTokenizer==0 ){
115291     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
115292     if( rc!=SQLITE_OK ) goto fts3_init_out;
115293   }
115294   assert( pTokenizer );
115295 
115296   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
115297   if( rc==SQLITE_ERROR ){
115298     assert( zPrefix );
115299     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
115300   }
115301   if( rc!=SQLITE_OK ) goto fts3_init_out;
115302 
115303   /* Allocate and populate the Fts3Table structure. */
115304   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
115305           nCol * sizeof(char *) +              /* azColumn */
115306           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
115307           nName +                              /* zName */
115308           nDb +                                /* zDb */
115309           nString;                             /* Space for azColumn strings */
115310   p = (Fts3Table*)sqlite3_malloc(nByte);
115311   if( p==0 ){
115312     rc = SQLITE_NOMEM;
115313     goto fts3_init_out;
115314   }
115315   memset(p, 0, nByte);
115316   p->db = db;
115317   p->nColumn = nCol;
115318   p->nPendingData = 0;
115319   p->azColumn = (char **)&p[1];
115320   p->pTokenizer = pTokenizer;
115321   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
115322   p->bHasDocsize = (isFts4 && bNoDocsize==0);
115323   p->bHasStat = isFts4;
115324   p->bDescIdx = bDescIdx;
115325   TESTONLY( p->inTransaction = -1 );
115326   TESTONLY( p->mxSavepoint = -1 );
115327 
115328   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
115329   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
115330   p->nIndex = nIndex;
115331   for(i=0; i<nIndex; i++){
115332     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
115333   }
115334 
115335   /* Fill in the zName and zDb fields of the vtab structure. */
115336   zCsr = (char *)&p->aIndex[nIndex];
115337   p->zName = zCsr;
115338   memcpy(zCsr, argv[2], nName);
115339   zCsr += nName;
115340   p->zDb = zCsr;
115341   memcpy(zCsr, argv[1], nDb);
115342   zCsr += nDb;
115343 
115344   /* Fill in the azColumn array */
115345   for(iCol=0; iCol<nCol; iCol++){
115346     char *z;
115347     int n = 0;
115348     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
115349     memcpy(zCsr, z, n);
115350     zCsr[n] = '\0';
115351     sqlite3Fts3Dequote(zCsr);
115352     p->azColumn[iCol] = zCsr;
115353     zCsr += n+1;
115354     assert( zCsr <= &((char *)p)[nByte] );
115355   }
115356 
115357   if( (zCompress==0)!=(zUncompress==0) ){
115358     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
115359     rc = SQLITE_ERROR;
115360     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
115361   }
115362   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
115363   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
115364   if( rc!=SQLITE_OK ) goto fts3_init_out;
115365 
115366   /* If this is an xCreate call, create the underlying tables in the
115367   ** database. TODO: For xConnect(), it could verify that said tables exist.
115368   */
115369   if( isCreate ){
115370     rc = fts3CreateTables(p);
115371   }
115372 
115373   /* Figure out the page-size for the database. This is required in order to
115374   ** estimate the cost of loading large doclists from the database.  */
115375   fts3DatabasePageSize(&rc, p);
115376   p->nNodeSize = p->nPgsz-35;
115377 
115378   /* Declare the table schema to SQLite. */
115379   fts3DeclareVtab(&rc, p);
115380 
115381 fts3_init_out:
115382   sqlite3_free(zPrefix);
115383   sqlite3_free(aIndex);
115384   sqlite3_free(zCompress);
115385   sqlite3_free(zUncompress);
115386   sqlite3_free((void *)aCol);
115387   if( rc!=SQLITE_OK ){
115388     if( p ){
115389       fts3DisconnectMethod((sqlite3_vtab *)p);
115390     }else if( pTokenizer ){
115391       pTokenizer->pModule->xDestroy(pTokenizer);
115392     }
115393   }else{
115394     assert( p->pSegments==0 );
115395     *ppVTab = &p->base;
115396   }
115397   return rc;
115398 }
115399 
115400 /*
115401 ** The xConnect() and xCreate() methods for the virtual table. All the
115402 ** work is done in function fts3InitVtab().
115403 */
115404 static int fts3ConnectMethod(
115405   sqlite3 *db,                    /* Database connection */
115406   void *pAux,                     /* Pointer to tokenizer hash table */
115407   int argc,                       /* Number of elements in argv array */
115408   const char * const *argv,       /* xCreate/xConnect argument array */
115409   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
115410   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
115411 ){
115412   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
115413 }
115414 static int fts3CreateMethod(
115415   sqlite3 *db,                    /* Database connection */
115416   void *pAux,                     /* Pointer to tokenizer hash table */
115417   int argc,                       /* Number of elements in argv array */
115418   const char * const *argv,       /* xCreate/xConnect argument array */
115419   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
115420   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
115421 ){
115422   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
115423 }
115424 
115425 /*
115426 ** Implementation of the xBestIndex method for FTS3 tables. There
115427 ** are three possible strategies, in order of preference:
115428 **
115429 **   1. Direct lookup by rowid or docid.
115430 **   2. Full-text search using a MATCH operator on a non-docid column.
115431 **   3. Linear scan of %_content table.
115432 */
115433 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
115434   Fts3Table *p = (Fts3Table *)pVTab;
115435   int i;                          /* Iterator variable */
115436   int iCons = -1;                 /* Index of constraint to use */
115437 
115438   /* By default use a full table scan. This is an expensive option,
115439   ** so search through the constraints to see if a more efficient
115440   ** strategy is possible.
115441   */
115442   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
115443   pInfo->estimatedCost = 500000;
115444   for(i=0; i<pInfo->nConstraint; i++){
115445     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
115446     if( pCons->usable==0 ) continue;
115447 
115448     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
115449     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
115450      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
115451     ){
115452       pInfo->idxNum = FTS3_DOCID_SEARCH;
115453       pInfo->estimatedCost = 1.0;
115454       iCons = i;
115455     }
115456 
115457     /* A MATCH constraint. Use a full-text search.
115458     **
115459     ** If there is more than one MATCH constraint available, use the first
115460     ** one encountered. If there is both a MATCH constraint and a direct
115461     ** rowid/docid lookup, prefer the MATCH strategy. This is done even
115462     ** though the rowid/docid lookup is faster than a MATCH query, selecting
115463     ** it would lead to an "unable to use function MATCH in the requested
115464     ** context" error.
115465     */
115466     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
115467      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
115468     ){
115469       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
115470       pInfo->estimatedCost = 2.0;
115471       iCons = i;
115472       break;
115473     }
115474   }
115475 
115476   if( iCons>=0 ){
115477     pInfo->aConstraintUsage[iCons].argvIndex = 1;
115478     pInfo->aConstraintUsage[iCons].omit = 1;
115479   }
115480 
115481   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
115482   ** docid) order. Both ascending and descending are possible.
115483   */
115484   if( pInfo->nOrderBy==1 ){
115485     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
115486     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
115487       if( pOrder->desc ){
115488         pInfo->idxStr = "DESC";
115489       }else{
115490         pInfo->idxStr = "ASC";
115491       }
115492       pInfo->orderByConsumed = 1;
115493     }
115494   }
115495 
115496   assert( p->pSegments==0 );
115497   return SQLITE_OK;
115498 }
115499 
115500 /*
115501 ** Implementation of xOpen method.
115502 */
115503 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
115504   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
115505 
115506   UNUSED_PARAMETER(pVTab);
115507 
115508   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
115509   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
115510   ** if the allocation fails, return SQLITE_NOMEM.
115511   */
115512   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
115513   if( !pCsr ){
115514     return SQLITE_NOMEM;
115515   }
115516   memset(pCsr, 0, sizeof(Fts3Cursor));
115517   return SQLITE_OK;
115518 }
115519 
115520 /*
115521 ** Close the cursor.  For additional information see the documentation
115522 ** on the xClose method of the virtual table interface.
115523 */
115524 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
115525   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
115526   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
115527   sqlite3_finalize(pCsr->pStmt);
115528   sqlite3Fts3ExprFree(pCsr->pExpr);
115529   sqlite3Fts3FreeDeferredTokens(pCsr);
115530   sqlite3_free(pCsr->aDoclist);
115531   sqlite3_free(pCsr->aMatchinfo);
115532   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
115533   sqlite3_free(pCsr);
115534   return SQLITE_OK;
115535 }
115536 
115537 /*
115538 ** Position the pCsr->pStmt statement so that it is on the row
115539 ** of the %_content table that contains the last match.  Return
115540 ** SQLITE_OK on success.
115541 */
115542 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
115543   if( pCsr->isRequireSeek ){
115544     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
115545     pCsr->isRequireSeek = 0;
115546     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
115547       return SQLITE_OK;
115548     }else{
115549       int rc = sqlite3_reset(pCsr->pStmt);
115550       if( rc==SQLITE_OK ){
115551         /* If no row was found and no error has occured, then the %_content
115552         ** table is missing a row that is present in the full-text index.
115553         ** The data structures are corrupt.
115554         */
115555         rc = SQLITE_CORRUPT_VTAB;
115556       }
115557       pCsr->isEof = 1;
115558       if( pContext ){
115559         sqlite3_result_error_code(pContext, rc);
115560       }
115561       return rc;
115562     }
115563   }else{
115564     return SQLITE_OK;
115565   }
115566 }
115567 
115568 /*
115569 ** This function is used to process a single interior node when searching
115570 ** a b-tree for a term or term prefix. The node data is passed to this
115571 ** function via the zNode/nNode parameters. The term to search for is
115572 ** passed in zTerm/nTerm.
115573 **
115574 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
115575 ** of the child node that heads the sub-tree that may contain the term.
115576 **
115577 ** If piLast is not NULL, then *piLast is set to the right-most child node
115578 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
115579 ** a prefix.
115580 **
115581 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
115582 */
115583 static int fts3ScanInteriorNode(
115584   const char *zTerm,              /* Term to select leaves for */
115585   int nTerm,                      /* Size of term zTerm in bytes */
115586   const char *zNode,              /* Buffer containing segment interior node */
115587   int nNode,                      /* Size of buffer at zNode */
115588   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
115589   sqlite3_int64 *piLast           /* OUT: Selected child node */
115590 ){
115591   int rc = SQLITE_OK;             /* Return code */
115592   const char *zCsr = zNode;       /* Cursor to iterate through node */
115593   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
115594   char *zBuffer = 0;              /* Buffer to load terms into */
115595   int nAlloc = 0;                 /* Size of allocated buffer */
115596   int isFirstTerm = 1;            /* True when processing first term on page */
115597   sqlite3_int64 iChild;           /* Block id of child node to descend to */
115598 
115599   /* Skip over the 'height' varint that occurs at the start of every
115600   ** interior node. Then load the blockid of the left-child of the b-tree
115601   ** node into variable iChild.
115602   **
115603   ** Even if the data structure on disk is corrupted, this (reading two
115604   ** varints from the buffer) does not risk an overread. If zNode is a
115605   ** root node, then the buffer comes from a SELECT statement. SQLite does
115606   ** not make this guarantee explicitly, but in practice there are always
115607   ** either more than 20 bytes of allocated space following the nNode bytes of
115608   ** contents, or two zero bytes. Or, if the node is read from the %_segments
115609   ** table, then there are always 20 bytes of zeroed padding following the
115610   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
115611   */
115612   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
115613   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
115614   if( zCsr>zEnd ){
115615     return SQLITE_CORRUPT_VTAB;
115616   }
115617 
115618   while( zCsr<zEnd && (piFirst || piLast) ){
115619     int cmp;                      /* memcmp() result */
115620     int nSuffix;                  /* Size of term suffix */
115621     int nPrefix = 0;              /* Size of term prefix */
115622     int nBuffer;                  /* Total term size */
115623 
115624     /* Load the next term on the node into zBuffer. Use realloc() to expand
115625     ** the size of zBuffer if required.  */
115626     if( !isFirstTerm ){
115627       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
115628     }
115629     isFirstTerm = 0;
115630     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
115631 
115632     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
115633       rc = SQLITE_CORRUPT_VTAB;
115634       goto finish_scan;
115635     }
115636     if( nPrefix+nSuffix>nAlloc ){
115637       char *zNew;
115638       nAlloc = (nPrefix+nSuffix) * 2;
115639       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
115640       if( !zNew ){
115641         rc = SQLITE_NOMEM;
115642         goto finish_scan;
115643       }
115644       zBuffer = zNew;
115645     }
115646     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
115647     nBuffer = nPrefix + nSuffix;
115648     zCsr += nSuffix;
115649 
115650     /* Compare the term we are searching for with the term just loaded from
115651     ** the interior node. If the specified term is greater than or equal
115652     ** to the term from the interior node, then all terms on the sub-tree
115653     ** headed by node iChild are smaller than zTerm. No need to search
115654     ** iChild.
115655     **
115656     ** If the interior node term is larger than the specified term, then
115657     ** the tree headed by iChild may contain the specified term.
115658     */
115659     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
115660     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
115661       *piFirst = iChild;
115662       piFirst = 0;
115663     }
115664 
115665     if( piLast && cmp<0 ){
115666       *piLast = iChild;
115667       piLast = 0;
115668     }
115669 
115670     iChild++;
115671   };
115672 
115673   if( piFirst ) *piFirst = iChild;
115674   if( piLast ) *piLast = iChild;
115675 
115676  finish_scan:
115677   sqlite3_free(zBuffer);
115678   return rc;
115679 }
115680 
115681 
115682 /*
115683 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
115684 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
115685 ** contains a term. This function searches the sub-tree headed by the zNode
115686 ** node for the range of leaf nodes that may contain the specified term
115687 ** or terms for which the specified term is a prefix.
115688 **
115689 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
115690 ** left-most leaf node in the tree that may contain the specified term.
115691 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
115692 ** right-most leaf node that may contain a term for which the specified
115693 ** term is a prefix.
115694 **
115695 ** It is possible that the range of returned leaf nodes does not contain
115696 ** the specified term or any terms for which it is a prefix. However, if the
115697 ** segment does contain any such terms, they are stored within the identified
115698 ** range. Because this function only inspects interior segment nodes (and
115699 ** never loads leaf nodes into memory), it is not possible to be sure.
115700 **
115701 ** If an error occurs, an error code other than SQLITE_OK is returned.
115702 */
115703 static int fts3SelectLeaf(
115704   Fts3Table *p,                   /* Virtual table handle */
115705   const char *zTerm,              /* Term to select leaves for */
115706   int nTerm,                      /* Size of term zTerm in bytes */
115707   const char *zNode,              /* Buffer containing segment interior node */
115708   int nNode,                      /* Size of buffer at zNode */
115709   sqlite3_int64 *piLeaf,          /* Selected leaf node */
115710   sqlite3_int64 *piLeaf2          /* Selected leaf node */
115711 ){
115712   int rc;                         /* Return code */
115713   int iHeight;                    /* Height of this node in tree */
115714 
115715   assert( piLeaf || piLeaf2 );
115716 
115717   sqlite3Fts3GetVarint32(zNode, &iHeight);
115718   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
115719   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
115720 
115721   if( rc==SQLITE_OK && iHeight>1 ){
115722     char *zBlob = 0;              /* Blob read from %_segments table */
115723     int nBlob;                    /* Size of zBlob in bytes */
115724 
115725     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
115726       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
115727       if( rc==SQLITE_OK ){
115728         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
115729       }
115730       sqlite3_free(zBlob);
115731       piLeaf = 0;
115732       zBlob = 0;
115733     }
115734 
115735     if( rc==SQLITE_OK ){
115736       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
115737     }
115738     if( rc==SQLITE_OK ){
115739       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
115740     }
115741     sqlite3_free(zBlob);
115742   }
115743 
115744   return rc;
115745 }
115746 
115747 /*
115748 ** This function is used to create delta-encoded serialized lists of FTS3
115749 ** varints. Each call to this function appends a single varint to a list.
115750 */
115751 static void fts3PutDeltaVarint(
115752   char **pp,                      /* IN/OUT: Output pointer */
115753   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
115754   sqlite3_int64 iVal              /* Write this value to the list */
115755 ){
115756   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
115757   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
115758   *piPrev = iVal;
115759 }
115760 
115761 /*
115762 ** When this function is called, *ppPoslist is assumed to point to the
115763 ** start of a position-list. After it returns, *ppPoslist points to the
115764 ** first byte after the position-list.
115765 **
115766 ** A position list is list of positions (delta encoded) and columns for
115767 ** a single document record of a doclist.  So, in other words, this
115768 ** routine advances *ppPoslist so that it points to the next docid in
115769 ** the doclist, or to the first byte past the end of the doclist.
115770 **
115771 ** If pp is not NULL, then the contents of the position list are copied
115772 ** to *pp. *pp is set to point to the first byte past the last byte copied
115773 ** before this function returns.
115774 */
115775 static void fts3PoslistCopy(char **pp, char **ppPoslist){
115776   char *pEnd = *ppPoslist;
115777   char c = 0;
115778 
115779   /* The end of a position list is marked by a zero encoded as an FTS3
115780   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
115781   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
115782   ** of some other, multi-byte, value.
115783   **
115784   ** The following while-loop moves pEnd to point to the first byte that is not
115785   ** immediately preceded by a byte with the 0x80 bit set. Then increments
115786   ** pEnd once more so that it points to the byte immediately following the
115787   ** last byte in the position-list.
115788   */
115789   while( *pEnd | c ){
115790     c = *pEnd++ & 0x80;
115791     testcase( c!=0 && (*pEnd)==0 );
115792   }
115793   pEnd++;  /* Advance past the POS_END terminator byte */
115794 
115795   if( pp ){
115796     int n = (int)(pEnd - *ppPoslist);
115797     char *p = *pp;
115798     memcpy(p, *ppPoslist, n);
115799     p += n;
115800     *pp = p;
115801   }
115802   *ppPoslist = pEnd;
115803 }
115804 
115805 /*
115806 ** When this function is called, *ppPoslist is assumed to point to the
115807 ** start of a column-list. After it returns, *ppPoslist points to the
115808 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
115809 **
115810 ** A column-list is list of delta-encoded positions for a single column
115811 ** within a single document within a doclist.
115812 **
115813 ** The column-list is terminated either by a POS_COLUMN varint (1) or
115814 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
115815 ** the POS_COLUMN or POS_END that terminates the column-list.
115816 **
115817 ** If pp is not NULL, then the contents of the column-list are copied
115818 ** to *pp. *pp is set to point to the first byte past the last byte copied
115819 ** before this function returns.  The POS_COLUMN or POS_END terminator
115820 ** is not copied into *pp.
115821 */
115822 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
115823   char *pEnd = *ppPoslist;
115824   char c = 0;
115825 
115826   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
115827   ** not part of a multi-byte varint.
115828   */
115829   while( 0xFE & (*pEnd | c) ){
115830     c = *pEnd++ & 0x80;
115831     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
115832   }
115833   if( pp ){
115834     int n = (int)(pEnd - *ppPoslist);
115835     char *p = *pp;
115836     memcpy(p, *ppPoslist, n);
115837     p += n;
115838     *pp = p;
115839   }
115840   *ppPoslist = pEnd;
115841 }
115842 
115843 /*
115844 ** Value used to signify the end of an position-list. This is safe because
115845 ** it is not possible to have a document with 2^31 terms.
115846 */
115847 #define POSITION_LIST_END 0x7fffffff
115848 
115849 /*
115850 ** This function is used to help parse position-lists. When this function is
115851 ** called, *pp may point to the start of the next varint in the position-list
115852 ** being parsed, or it may point to 1 byte past the end of the position-list
115853 ** (in which case **pp will be a terminator bytes POS_END (0) or
115854 ** (1)).
115855 **
115856 ** If *pp points past the end of the current position-list, set *pi to
115857 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
115858 ** increment the current value of *pi by the value read, and set *pp to
115859 ** point to the next value before returning.
115860 **
115861 ** Before calling this routine *pi must be initialized to the value of
115862 ** the previous position, or zero if we are reading the first position
115863 ** in the position-list.  Because positions are delta-encoded, the value
115864 ** of the previous position is needed in order to compute the value of
115865 ** the next position.
115866 */
115867 static void fts3ReadNextPos(
115868   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
115869   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
115870 ){
115871   if( (**pp)&0xFE ){
115872     fts3GetDeltaVarint(pp, pi);
115873     *pi -= 2;
115874   }else{
115875     *pi = POSITION_LIST_END;
115876   }
115877 }
115878 
115879 /*
115880 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
115881 ** the value of iCol encoded as a varint to *pp.   This will start a new
115882 ** column list.
115883 **
115884 ** Set *pp to point to the byte just after the last byte written before
115885 ** returning (do not modify it if iCol==0). Return the total number of bytes
115886 ** written (0 if iCol==0).
115887 */
115888 static int fts3PutColNumber(char **pp, int iCol){
115889   int n = 0;                      /* Number of bytes written */
115890   if( iCol ){
115891     char *p = *pp;                /* Output pointer */
115892     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
115893     *p = 0x01;
115894     *pp = &p[n];
115895   }
115896   return n;
115897 }
115898 
115899 /*
115900 ** Compute the union of two position lists.  The output written
115901 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
115902 ** order and with any duplicates removed.  All pointers are
115903 ** updated appropriately.   The caller is responsible for insuring
115904 ** that there is enough space in *pp to hold the complete output.
115905 */
115906 static void fts3PoslistMerge(
115907   char **pp,                      /* Output buffer */
115908   char **pp1,                     /* Left input list */
115909   char **pp2                      /* Right input list */
115910 ){
115911   char *p = *pp;
115912   char *p1 = *pp1;
115913   char *p2 = *pp2;
115914 
115915   while( *p1 || *p2 ){
115916     int iCol1;         /* The current column index in pp1 */
115917     int iCol2;         /* The current column index in pp2 */
115918 
115919     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
115920     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
115921     else iCol1 = 0;
115922 
115923     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
115924     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
115925     else iCol2 = 0;
115926 
115927     if( iCol1==iCol2 ){
115928       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
115929       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
115930       sqlite3_int64 iPrev = 0;
115931       int n = fts3PutColNumber(&p, iCol1);
115932       p1 += n;
115933       p2 += n;
115934 
115935       /* At this point, both p1 and p2 point to the start of column-lists
115936       ** for the same column (the column with index iCol1 and iCol2).
115937       ** A column-list is a list of non-negative delta-encoded varints, each
115938       ** incremented by 2 before being stored. Each list is terminated by a
115939       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
115940       ** and writes the results to buffer p. p is left pointing to the byte
115941       ** after the list written. No terminator (POS_END or POS_COLUMN) is
115942       ** written to the output.
115943       */
115944       fts3GetDeltaVarint(&p1, &i1);
115945       fts3GetDeltaVarint(&p2, &i2);
115946       do {
115947         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
115948         iPrev -= 2;
115949         if( i1==i2 ){
115950           fts3ReadNextPos(&p1, &i1);
115951           fts3ReadNextPos(&p2, &i2);
115952         }else if( i1<i2 ){
115953           fts3ReadNextPos(&p1, &i1);
115954         }else{
115955           fts3ReadNextPos(&p2, &i2);
115956         }
115957       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
115958     }else if( iCol1<iCol2 ){
115959       p1 += fts3PutColNumber(&p, iCol1);
115960       fts3ColumnlistCopy(&p, &p1);
115961     }else{
115962       p2 += fts3PutColNumber(&p, iCol2);
115963       fts3ColumnlistCopy(&p, &p2);
115964     }
115965   }
115966 
115967   *p++ = POS_END;
115968   *pp = p;
115969   *pp1 = p1 + 1;
115970   *pp2 = p2 + 1;
115971 }
115972 
115973 /*
115974 ** This function is used to merge two position lists into one. When it is
115975 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
115976 ** the part of a doclist that follows each document id. For example, if a row
115977 ** contains:
115978 **
115979 **     'a b c'|'x y z'|'a b b a'
115980 **
115981 ** Then the position list for this row for token 'b' would consist of:
115982 **
115983 **     0x02 0x01 0x02 0x03 0x03 0x00
115984 **
115985 ** When this function returns, both *pp1 and *pp2 are left pointing to the
115986 ** byte following the 0x00 terminator of their respective position lists.
115987 **
115988 ** If isSaveLeft is 0, an entry is added to the output position list for
115989 ** each position in *pp2 for which there exists one or more positions in
115990 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
115991 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
115992 ** slots before it.
115993 **
115994 ** e.g. nToken==1 searches for adjacent positions.
115995 */
115996 static int fts3PoslistPhraseMerge(
115997   char **pp,                      /* IN/OUT: Preallocated output buffer */
115998   int nToken,                     /* Maximum difference in token positions */
115999   int isSaveLeft,                 /* Save the left position */
116000   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
116001   char **pp1,                     /* IN/OUT: Left input list */
116002   char **pp2                      /* IN/OUT: Right input list */
116003 ){
116004   char *p = (pp ? *pp : 0);
116005   char *p1 = *pp1;
116006   char *p2 = *pp2;
116007   int iCol1 = 0;
116008   int iCol2 = 0;
116009 
116010   /* Never set both isSaveLeft and isExact for the same invocation. */
116011   assert( isSaveLeft==0 || isExact==0 );
116012 
116013   assert( *p1!=0 && *p2!=0 );
116014   if( *p1==POS_COLUMN ){
116015     p1++;
116016     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116017   }
116018   if( *p2==POS_COLUMN ){
116019     p2++;
116020     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116021   }
116022 
116023   while( 1 ){
116024     if( iCol1==iCol2 ){
116025       char *pSave = p;
116026       sqlite3_int64 iPrev = 0;
116027       sqlite3_int64 iPos1 = 0;
116028       sqlite3_int64 iPos2 = 0;
116029 
116030       if( pp && iCol1 ){
116031         *p++ = POS_COLUMN;
116032         p += sqlite3Fts3PutVarint(p, iCol1);
116033       }
116034 
116035       assert( *p1!=POS_END && *p1!=POS_COLUMN );
116036       assert( *p2!=POS_END && *p2!=POS_COLUMN );
116037       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
116038       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
116039 
116040       while( 1 ){
116041         if( iPos2==iPos1+nToken
116042          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
116043         ){
116044           sqlite3_int64 iSave;
116045           if( !pp ){
116046             fts3PoslistCopy(0, &p2);
116047             fts3PoslistCopy(0, &p1);
116048             *pp1 = p1;
116049             *pp2 = p2;
116050             return 1;
116051           }
116052           iSave = isSaveLeft ? iPos1 : iPos2;
116053           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
116054           pSave = 0;
116055         }
116056         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
116057           if( (*p2&0xFE)==0 ) break;
116058           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
116059         }else{
116060           if( (*p1&0xFE)==0 ) break;
116061           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
116062         }
116063       }
116064 
116065       if( pSave ){
116066         assert( pp && p );
116067         p = pSave;
116068       }
116069 
116070       fts3ColumnlistCopy(0, &p1);
116071       fts3ColumnlistCopy(0, &p2);
116072       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
116073       if( 0==*p1 || 0==*p2 ) break;
116074 
116075       p1++;
116076       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116077       p2++;
116078       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116079     }
116080 
116081     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
116082     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
116083     ** end of the position list, or the 0x01 that precedes the next
116084     ** column-number in the position list.
116085     */
116086     else if( iCol1<iCol2 ){
116087       fts3ColumnlistCopy(0, &p1);
116088       if( 0==*p1 ) break;
116089       p1++;
116090       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
116091     }else{
116092       fts3ColumnlistCopy(0, &p2);
116093       if( 0==*p2 ) break;
116094       p2++;
116095       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
116096     }
116097   }
116098 
116099   fts3PoslistCopy(0, &p2);
116100   fts3PoslistCopy(0, &p1);
116101   *pp1 = p1;
116102   *pp2 = p2;
116103   if( !pp || *pp==p ){
116104     return 0;
116105   }
116106   *p++ = 0x00;
116107   *pp = p;
116108   return 1;
116109 }
116110 
116111 /*
116112 ** Merge two position-lists as required by the NEAR operator. The argument
116113 ** position lists correspond to the left and right phrases of an expression
116114 ** like:
116115 **
116116 **     "phrase 1" NEAR "phrase number 2"
116117 **
116118 ** Position list *pp1 corresponds to the left-hand side of the NEAR
116119 ** expression and *pp2 to the right. As usual, the indexes in the position
116120 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
116121 ** in the example above).
116122 **
116123 ** The output position list - written to *pp - is a copy of *pp2 with those
116124 ** entries that are not sufficiently NEAR entries in *pp1 removed.
116125 */
116126 static int fts3PoslistNearMerge(
116127   char **pp,                      /* Output buffer */
116128   char *aTmp,                     /* Temporary buffer space */
116129   int nRight,                     /* Maximum difference in token positions */
116130   int nLeft,                      /* Maximum difference in token positions */
116131   char **pp1,                     /* IN/OUT: Left input list */
116132   char **pp2                      /* IN/OUT: Right input list */
116133 ){
116134   char *p1 = *pp1;
116135   char *p2 = *pp2;
116136 
116137   char *pTmp1 = aTmp;
116138   char *pTmp2;
116139   char *aTmp2;
116140   int res = 1;
116141 
116142   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
116143   aTmp2 = pTmp2 = pTmp1;
116144   *pp1 = p1;
116145   *pp2 = p2;
116146   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
116147   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
116148     fts3PoslistMerge(pp, &aTmp, &aTmp2);
116149   }else if( pTmp1!=aTmp ){
116150     fts3PoslistCopy(pp, &aTmp);
116151   }else if( pTmp2!=aTmp2 ){
116152     fts3PoslistCopy(pp, &aTmp2);
116153   }else{
116154     res = 0;
116155   }
116156 
116157   return res;
116158 }
116159 
116160 /*
116161 ** An instance of this function is used to merge together the (potentially
116162 ** large number of) doclists for each term that matches a prefix query.
116163 ** See function fts3TermSelectMerge() for details.
116164 */
116165 typedef struct TermSelect TermSelect;
116166 struct TermSelect {
116167   char *aaOutput[16];             /* Malloc'd output buffers */
116168   int anOutput[16];               /* Size each output buffer in bytes */
116169 };
116170 
116171 /*
116172 ** This function is used to read a single varint from a buffer. Parameter
116173 ** pEnd points 1 byte past the end of the buffer. When this function is
116174 ** called, if *pp points to pEnd or greater, then the end of the buffer
116175 ** has been reached. In this case *pp is set to 0 and the function returns.
116176 **
116177 ** If *pp does not point to or past pEnd, then a single varint is read
116178 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
116179 **
116180 ** If bDescIdx is false, the value read is added to *pVal before returning.
116181 ** If it is true, the value read is subtracted from *pVal before this
116182 ** function returns.
116183 */
116184 static void fts3GetDeltaVarint3(
116185   char **pp,                      /* IN/OUT: Point to read varint from */
116186   char *pEnd,                     /* End of buffer */
116187   int bDescIdx,                   /* True if docids are descending */
116188   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
116189 ){
116190   if( *pp>=pEnd ){
116191     *pp = 0;
116192   }else{
116193     sqlite3_int64 iVal;
116194     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
116195     if( bDescIdx ){
116196       *pVal -= iVal;
116197     }else{
116198       *pVal += iVal;
116199     }
116200   }
116201 }
116202 
116203 /*
116204 ** This function is used to write a single varint to a buffer. The varint
116205 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
116206 ** end of the value written.
116207 **
116208 ** If *pbFirst is zero when this function is called, the value written to
116209 ** the buffer is that of parameter iVal.
116210 **
116211 ** If *pbFirst is non-zero when this function is called, then the value
116212 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
116213 ** (if bDescIdx is non-zero).
116214 **
116215 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
116216 ** to the value of parameter iVal.
116217 */
116218 static void fts3PutDeltaVarint3(
116219   char **pp,                      /* IN/OUT: Output pointer */
116220   int bDescIdx,                   /* True for descending docids */
116221   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
116222   int *pbFirst,                   /* IN/OUT: True after first int written */
116223   sqlite3_int64 iVal              /* Write this value to the list */
116224 ){
116225   sqlite3_int64 iWrite;
116226   if( bDescIdx==0 || *pbFirst==0 ){
116227     iWrite = iVal - *piPrev;
116228   }else{
116229     iWrite = *piPrev - iVal;
116230   }
116231   assert( *pbFirst || *piPrev==0 );
116232   assert( *pbFirst==0 || iWrite>0 );
116233   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
116234   *piPrev = iVal;
116235   *pbFirst = 1;
116236 }
116237 
116238 
116239 /*
116240 ** This macro is used by various functions that merge doclists. The two
116241 ** arguments are 64-bit docid values. If the value of the stack variable
116242 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
116243 ** Otherwise, (i2-i1).
116244 **
116245 ** Using this makes it easier to write code that can merge doclists that are
116246 ** sorted in either ascending or descending order.
116247 */
116248 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
116249 
116250 /*
116251 ** This function does an "OR" merge of two doclists (output contains all
116252 ** positions contained in either argument doclist). If the docids in the
116253 ** input doclists are sorted in ascending order, parameter bDescDoclist
116254 ** should be false. If they are sorted in ascending order, it should be
116255 ** passed a non-zero value.
116256 **
116257 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
116258 ** containing the output doclist and SQLITE_OK is returned. In this case
116259 ** *pnOut is set to the number of bytes in the output doclist.
116260 **
116261 ** If an error occurs, an SQLite error code is returned. The output values
116262 ** are undefined in this case.
116263 */
116264 static int fts3DoclistOrMerge(
116265   int bDescDoclist,               /* True if arguments are desc */
116266   char *a1, int n1,               /* First doclist */
116267   char *a2, int n2,               /* Second doclist */
116268   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
116269 ){
116270   sqlite3_int64 i1 = 0;
116271   sqlite3_int64 i2 = 0;
116272   sqlite3_int64 iPrev = 0;
116273   char *pEnd1 = &a1[n1];
116274   char *pEnd2 = &a2[n2];
116275   char *p1 = a1;
116276   char *p2 = a2;
116277   char *p;
116278   char *aOut;
116279   int bFirstOut = 0;
116280 
116281   *paOut = 0;
116282   *pnOut = 0;
116283 
116284   /* Allocate space for the output. Both the input and output doclists
116285   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
116286   ** then the first docid in each list is simply encoded as a varint. For
116287   ** each subsequent docid, the varint stored is the difference between the
116288   ** current and previous docid (a positive number - since the list is in
116289   ** ascending order).
116290   **
116291   ** The first docid written to the output is therefore encoded using the
116292   ** same number of bytes as it is in whichever of the input lists it is
116293   ** read from. And each subsequent docid read from the same input list
116294   ** consumes either the same or less bytes as it did in the input (since
116295   ** the difference between it and the previous value in the output must
116296   ** be a positive value less than or equal to the delta value read from
116297   ** the input list). The same argument applies to all but the first docid
116298   ** read from the 'other' list. And to the contents of all position lists
116299   ** that will be copied and merged from the input to the output.
116300   **
116301   ** However, if the first docid copied to the output is a negative number,
116302   ** then the encoding of the first docid from the 'other' input list may
116303   ** be larger in the output than it was in the input (since the delta value
116304   ** may be a larger positive integer than the actual docid).
116305   **
116306   ** The space required to store the output is therefore the sum of the
116307   ** sizes of the two inputs, plus enough space for exactly one of the input
116308   ** docids to grow.
116309   **
116310   ** A symetric argument may be made if the doclists are in descending
116311   ** order.
116312   */
116313   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
116314   if( !aOut ) return SQLITE_NOMEM;
116315 
116316   p = aOut;
116317   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
116318   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
116319   while( p1 || p2 ){
116320     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
116321 
116322     if( p2 && p1 && iDiff==0 ){
116323       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116324       fts3PoslistMerge(&p, &p1, &p2);
116325       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116326       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116327     }else if( !p2 || (p1 && iDiff<0) ){
116328       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116329       fts3PoslistCopy(&p, &p1);
116330       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116331     }else{
116332       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
116333       fts3PoslistCopy(&p, &p2);
116334       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116335     }
116336   }
116337 
116338   *paOut = aOut;
116339   *pnOut = (p-aOut);
116340   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
116341   return SQLITE_OK;
116342 }
116343 
116344 /*
116345 ** This function does a "phrase" merge of two doclists. In a phrase merge,
116346 ** the output contains a copy of each position from the right-hand input
116347 ** doclist for which there is a position in the left-hand input doclist
116348 ** exactly nDist tokens before it.
116349 **
116350 ** If the docids in the input doclists are sorted in ascending order,
116351 ** parameter bDescDoclist should be false. If they are sorted in ascending
116352 ** order, it should be passed a non-zero value.
116353 **
116354 ** The right-hand input doclist is overwritten by this function.
116355 */
116356 static void fts3DoclistPhraseMerge(
116357   int bDescDoclist,               /* True if arguments are desc */
116358   int nDist,                      /* Distance from left to right (1=adjacent) */
116359   char *aLeft, int nLeft,         /* Left doclist */
116360   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
116361 ){
116362   sqlite3_int64 i1 = 0;
116363   sqlite3_int64 i2 = 0;
116364   sqlite3_int64 iPrev = 0;
116365   char *pEnd1 = &aLeft[nLeft];
116366   char *pEnd2 = &aRight[*pnRight];
116367   char *p1 = aLeft;
116368   char *p2 = aRight;
116369   char *p;
116370   int bFirstOut = 0;
116371   char *aOut = aRight;
116372 
116373   assert( nDist>0 );
116374 
116375   p = aOut;
116376   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
116377   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
116378 
116379   while( p1 && p2 ){
116380     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
116381     if( iDiff==0 ){
116382       char *pSave = p;
116383       sqlite3_int64 iPrevSave = iPrev;
116384       int bFirstOutSave = bFirstOut;
116385 
116386       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
116387       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
116388         p = pSave;
116389         iPrev = iPrevSave;
116390         bFirstOut = bFirstOutSave;
116391       }
116392       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116393       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116394     }else if( iDiff<0 ){
116395       fts3PoslistCopy(0, &p1);
116396       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
116397     }else{
116398       fts3PoslistCopy(0, &p2);
116399       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
116400     }
116401   }
116402 
116403   *pnRight = p - aOut;
116404 }
116405 
116406 
116407 /*
116408 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
116409 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
116410 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
116411 **
116412 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
116413 ** the responsibility of the caller to free any doclists left in the
116414 ** TermSelect.aaOutput[] array.
116415 */
116416 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
116417   char *aOut = 0;
116418   int nOut = 0;
116419   int i;
116420 
116421   /* Loop through the doclists in the aaOutput[] array. Merge them all
116422   ** into a single doclist.
116423   */
116424   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
116425     if( pTS->aaOutput[i] ){
116426       if( !aOut ){
116427         aOut = pTS->aaOutput[i];
116428         nOut = pTS->anOutput[i];
116429         pTS->aaOutput[i] = 0;
116430       }else{
116431         int nNew;
116432         char *aNew;
116433 
116434         int rc = fts3DoclistOrMerge(p->bDescIdx,
116435             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
116436         );
116437         if( rc!=SQLITE_OK ){
116438           sqlite3_free(aOut);
116439           return rc;
116440         }
116441 
116442         sqlite3_free(pTS->aaOutput[i]);
116443         sqlite3_free(aOut);
116444         pTS->aaOutput[i] = 0;
116445         aOut = aNew;
116446         nOut = nNew;
116447       }
116448     }
116449   }
116450 
116451   pTS->aaOutput[0] = aOut;
116452   pTS->anOutput[0] = nOut;
116453   return SQLITE_OK;
116454 }
116455 
116456 /*
116457 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
116458 ** as the first argument. The merge is an "OR" merge (see function
116459 ** fts3DoclistOrMerge() for details).
116460 **
116461 ** This function is called with the doclist for each term that matches
116462 ** a queried prefix. It merges all these doclists into one, the doclist
116463 ** for the specified prefix. Since there can be a very large number of
116464 ** doclists to merge, the merging is done pair-wise using the TermSelect
116465 ** object.
116466 **
116467 ** This function returns SQLITE_OK if the merge is successful, or an
116468 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
116469 */
116470 static int fts3TermSelectMerge(
116471   Fts3Table *p,                   /* FTS table handle */
116472   TermSelect *pTS,                /* TermSelect object to merge into */
116473   char *aDoclist,                 /* Pointer to doclist */
116474   int nDoclist                    /* Size of aDoclist in bytes */
116475 ){
116476   if( pTS->aaOutput[0]==0 ){
116477     /* If this is the first term selected, copy the doclist to the output
116478     ** buffer using memcpy(). */
116479     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
116480     pTS->anOutput[0] = nDoclist;
116481     if( pTS->aaOutput[0] ){
116482       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
116483     }else{
116484       return SQLITE_NOMEM;
116485     }
116486   }else{
116487     char *aMerge = aDoclist;
116488     int nMerge = nDoclist;
116489     int iOut;
116490 
116491     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
116492       if( pTS->aaOutput[iOut]==0 ){
116493         assert( iOut>0 );
116494         pTS->aaOutput[iOut] = aMerge;
116495         pTS->anOutput[iOut] = nMerge;
116496         break;
116497       }else{
116498         char *aNew;
116499         int nNew;
116500 
116501         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
116502             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
116503         );
116504         if( rc!=SQLITE_OK ){
116505           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
116506           return rc;
116507         }
116508 
116509         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
116510         sqlite3_free(pTS->aaOutput[iOut]);
116511         pTS->aaOutput[iOut] = 0;
116512 
116513         aMerge = aNew;
116514         nMerge = nNew;
116515         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
116516           pTS->aaOutput[iOut] = aMerge;
116517           pTS->anOutput[iOut] = nMerge;
116518         }
116519       }
116520     }
116521   }
116522   return SQLITE_OK;
116523 }
116524 
116525 /*
116526 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
116527 */
116528 static int fts3SegReaderCursorAppend(
116529   Fts3MultiSegReader *pCsr,
116530   Fts3SegReader *pNew
116531 ){
116532   if( (pCsr->nSegment%16)==0 ){
116533     Fts3SegReader **apNew;
116534     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
116535     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
116536     if( !apNew ){
116537       sqlite3Fts3SegReaderFree(pNew);
116538       return SQLITE_NOMEM;
116539     }
116540     pCsr->apSegment = apNew;
116541   }
116542   pCsr->apSegment[pCsr->nSegment++] = pNew;
116543   return SQLITE_OK;
116544 }
116545 
116546 /*
116547 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
116548 ** 8th argument.
116549 **
116550 ** This function returns SQLITE_OK if successful, or an SQLite error code
116551 ** otherwise.
116552 */
116553 static int fts3SegReaderCursor(
116554   Fts3Table *p,                   /* FTS3 table handle */
116555   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
116556   int iLevel,                     /* Level of segments to scan */
116557   const char *zTerm,              /* Term to query for */
116558   int nTerm,                      /* Size of zTerm in bytes */
116559   int isPrefix,                   /* True for a prefix search */
116560   int isScan,                     /* True to scan from zTerm to EOF */
116561   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
116562 ){
116563   int rc = SQLITE_OK;             /* Error code */
116564   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
116565   int rc2;                        /* Result of sqlite3_reset() */
116566 
116567   /* If iLevel is less than 0 and this is not a scan, include a seg-reader
116568   ** for the pending-terms. If this is a scan, then this call must be being
116569   ** made by an fts4aux module, not an FTS table. In this case calling
116570   ** Fts3SegReaderPending might segfault, as the data structures used by
116571   ** fts4aux are not completely populated. So it's easiest to filter these
116572   ** calls out here.  */
116573   if( iLevel<0 && p->aIndex ){
116574     Fts3SegReader *pSeg = 0;
116575     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
116576     if( rc==SQLITE_OK && pSeg ){
116577       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
116578     }
116579   }
116580 
116581   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
116582     if( rc==SQLITE_OK ){
116583       rc = sqlite3Fts3AllSegdirs(p, iIndex, iLevel, &pStmt);
116584     }
116585 
116586     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
116587       Fts3SegReader *pSeg = 0;
116588 
116589       /* Read the values returned by the SELECT into local variables. */
116590       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
116591       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
116592       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
116593       int nRoot = sqlite3_column_bytes(pStmt, 4);
116594       char const *zRoot = sqlite3_column_blob(pStmt, 4);
116595 
116596       /* If zTerm is not NULL, and this segment is not stored entirely on its
116597       ** root node, the range of leaves scanned can be reduced. Do this. */
116598       if( iStartBlock && zTerm ){
116599         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
116600         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
116601         if( rc!=SQLITE_OK ) goto finished;
116602         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
116603       }
116604 
116605       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
116606           iStartBlock, iLeavesEndBlock, iEndBlock, zRoot, nRoot, &pSeg
116607       );
116608       if( rc!=SQLITE_OK ) goto finished;
116609       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
116610     }
116611   }
116612 
116613  finished:
116614   rc2 = sqlite3_reset(pStmt);
116615   if( rc==SQLITE_DONE ) rc = rc2;
116616 
116617   return rc;
116618 }
116619 
116620 /*
116621 ** Set up a cursor object for iterating through a full-text index or a
116622 ** single level therein.
116623 */
116624 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
116625   Fts3Table *p,                   /* FTS3 table handle */
116626   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
116627   int iLevel,                     /* Level of segments to scan */
116628   const char *zTerm,              /* Term to query for */
116629   int nTerm,                      /* Size of zTerm in bytes */
116630   int isPrefix,                   /* True for a prefix search */
116631   int isScan,                     /* True to scan from zTerm to EOF */
116632   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
116633 ){
116634   assert( iIndex>=0 && iIndex<p->nIndex );
116635   assert( iLevel==FTS3_SEGCURSOR_ALL
116636       ||  iLevel==FTS3_SEGCURSOR_PENDING
116637       ||  iLevel>=0
116638   );
116639   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
116640   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
116641   assert( isPrefix==0 || isScan==0 );
116642 
116643   /* "isScan" is only set to true by the ft4aux module, an ordinary
116644   ** full-text tables. */
116645   assert( isScan==0 || p->aIndex==0 );
116646 
116647   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
116648 
116649   return fts3SegReaderCursor(
116650       p, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
116651   );
116652 }
116653 
116654 /*
116655 ** In addition to its current configuration, have the Fts3MultiSegReader
116656 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
116657 **
116658 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
116659 */
116660 static int fts3SegReaderCursorAddZero(
116661   Fts3Table *p,                   /* FTS virtual table handle */
116662   const char *zTerm,              /* Term to scan doclist of */
116663   int nTerm,                      /* Number of bytes in zTerm */
116664   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
116665 ){
116666   return fts3SegReaderCursor(p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr);
116667 }
116668 
116669 /*
116670 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
116671 ** if isPrefix is true, to scan the doclist for all terms for which
116672 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
116673 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
116674 ** an SQLite error code.
116675 **
116676 ** It is the responsibility of the caller to free this object by eventually
116677 ** passing it to fts3SegReaderCursorFree()
116678 **
116679 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
116680 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
116681 */
116682 static int fts3TermSegReaderCursor(
116683   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
116684   const char *zTerm,              /* Term to query for */
116685   int nTerm,                      /* Size of zTerm in bytes */
116686   int isPrefix,                   /* True for a prefix search */
116687   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
116688 ){
116689   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
116690   int rc = SQLITE_NOMEM;          /* Return code */
116691 
116692   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
116693   if( pSegcsr ){
116694     int i;
116695     int bFound = 0;               /* True once an index has been found */
116696     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
116697 
116698     if( isPrefix ){
116699       for(i=1; bFound==0 && i<p->nIndex; i++){
116700         if( p->aIndex[i].nPrefix==nTerm ){
116701           bFound = 1;
116702           rc = sqlite3Fts3SegReaderCursor(
116703               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr);
116704           pSegcsr->bLookup = 1;
116705         }
116706       }
116707 
116708       for(i=1; bFound==0 && i<p->nIndex; i++){
116709         if( p->aIndex[i].nPrefix==nTerm+1 ){
116710           bFound = 1;
116711           rc = sqlite3Fts3SegReaderCursor(
116712               p, i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
116713           );
116714           if( rc==SQLITE_OK ){
116715             rc = fts3SegReaderCursorAddZero(p, zTerm, nTerm, pSegcsr);
116716           }
116717         }
116718       }
116719     }
116720 
116721     if( bFound==0 ){
116722       rc = sqlite3Fts3SegReaderCursor(
116723           p, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
116724       );
116725       pSegcsr->bLookup = !isPrefix;
116726     }
116727   }
116728 
116729   *ppSegcsr = pSegcsr;
116730   return rc;
116731 }
116732 
116733 /*
116734 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
116735 */
116736 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
116737   sqlite3Fts3SegReaderFinish(pSegcsr);
116738   sqlite3_free(pSegcsr);
116739 }
116740 
116741 /*
116742 ** This function retreives the doclist for the specified term (or term
116743 ** prefix) from the database.
116744 */
116745 static int fts3TermSelect(
116746   Fts3Table *p,                   /* Virtual table handle */
116747   Fts3PhraseToken *pTok,          /* Token to query for */
116748   int iColumn,                    /* Column to query (or -ve for all columns) */
116749   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
116750   char **ppOut                    /* OUT: Malloced result buffer */
116751 ){
116752   int rc;                         /* Return code */
116753   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
116754   TermSelect tsc;                 /* Object for pair-wise doclist merging */
116755   Fts3SegFilter filter;           /* Segment term filter configuration */
116756 
116757   pSegcsr = pTok->pSegcsr;
116758   memset(&tsc, 0, sizeof(TermSelect));
116759 
116760   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
116761         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
116762         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
116763   filter.iCol = iColumn;
116764   filter.zTerm = pTok->z;
116765   filter.nTerm = pTok->n;
116766 
116767   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
116768   while( SQLITE_OK==rc
116769       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
116770   ){
116771     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
116772   }
116773 
116774   if( rc==SQLITE_OK ){
116775     rc = fts3TermSelectFinishMerge(p, &tsc);
116776   }
116777   if( rc==SQLITE_OK ){
116778     *ppOut = tsc.aaOutput[0];
116779     *pnOut = tsc.anOutput[0];
116780   }else{
116781     int i;
116782     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
116783       sqlite3_free(tsc.aaOutput[i]);
116784     }
116785   }
116786 
116787   fts3SegReaderCursorFree(pSegcsr);
116788   pTok->pSegcsr = 0;
116789   return rc;
116790 }
116791 
116792 /*
116793 ** This function counts the total number of docids in the doclist stored
116794 ** in buffer aList[], size nList bytes.
116795 **
116796 ** If the isPoslist argument is true, then it is assumed that the doclist
116797 ** contains a position-list following each docid. Otherwise, it is assumed
116798 ** that the doclist is simply a list of docids stored as delta encoded
116799 ** varints.
116800 */
116801 static int fts3DoclistCountDocids(char *aList, int nList){
116802   int nDoc = 0;                   /* Return value */
116803   if( aList ){
116804     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
116805     char *p = aList;              /* Cursor */
116806     while( p<aEnd ){
116807       nDoc++;
116808       while( (*p++)&0x80 );     /* Skip docid varint */
116809       fts3PoslistCopy(0, &p);   /* Skip over position list */
116810     }
116811   }
116812 
116813   return nDoc;
116814 }
116815 
116816 /*
116817 ** Advance the cursor to the next row in the %_content table that
116818 ** matches the search criteria.  For a MATCH search, this will be
116819 ** the next row that matches. For a full-table scan, this will be
116820 ** simply the next row in the %_content table.  For a docid lookup,
116821 ** this routine simply sets the EOF flag.
116822 **
116823 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
116824 ** even if we reach end-of-file.  The fts3EofMethod() will be called
116825 ** subsequently to determine whether or not an EOF was hit.
116826 */
116827 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
116828   int rc;
116829   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116830   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
116831     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
116832       pCsr->isEof = 1;
116833       rc = sqlite3_reset(pCsr->pStmt);
116834     }else{
116835       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
116836       rc = SQLITE_OK;
116837     }
116838   }else{
116839     rc = fts3EvalNext((Fts3Cursor *)pCursor);
116840   }
116841   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
116842   return rc;
116843 }
116844 
116845 /*
116846 ** This is the xFilter interface for the virtual table.  See
116847 ** the virtual table xFilter method documentation for additional
116848 ** information.
116849 **
116850 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
116851 ** the %_content table.
116852 **
116853 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
116854 ** in the %_content table.
116855 **
116856 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
116857 ** column on the left-hand side of the MATCH operator is column
116858 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
116859 ** side of the MATCH operator.
116860 */
116861 static int fts3FilterMethod(
116862   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
116863   int idxNum,                     /* Strategy index */
116864   const char *idxStr,             /* Unused */
116865   int nVal,                       /* Number of elements in apVal */
116866   sqlite3_value **apVal           /* Arguments for the indexing scheme */
116867 ){
116868   int rc;
116869   char *zSql;                     /* SQL statement used to access %_content */
116870   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116871   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
116872 
116873   UNUSED_PARAMETER(idxStr);
116874   UNUSED_PARAMETER(nVal);
116875 
116876   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
116877   assert( nVal==0 || nVal==1 );
116878   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
116879   assert( p->pSegments==0 );
116880 
116881   /* In case the cursor has been used before, clear it now. */
116882   sqlite3_finalize(pCsr->pStmt);
116883   sqlite3_free(pCsr->aDoclist);
116884   sqlite3Fts3ExprFree(pCsr->pExpr);
116885   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
116886 
116887   if( idxStr ){
116888     pCsr->bDesc = (idxStr[0]=='D');
116889   }else{
116890     pCsr->bDesc = p->bDescIdx;
116891   }
116892   pCsr->eSearch = (i16)idxNum;
116893 
116894   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
116895     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
116896     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
116897 
116898     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
116899       return SQLITE_NOMEM;
116900     }
116901 
116902     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
116903         iCol, zQuery, -1, &pCsr->pExpr
116904     );
116905     if( rc!=SQLITE_OK ){
116906       if( rc==SQLITE_ERROR ){
116907         static const char *zErr = "malformed MATCH expression: [%s]";
116908         p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
116909       }
116910       return rc;
116911     }
116912 
116913     rc = sqlite3Fts3ReadLock(p);
116914     if( rc!=SQLITE_OK ) return rc;
116915 
116916     rc = fts3EvalStart(pCsr);
116917 
116918     sqlite3Fts3SegmentsClose(p);
116919     if( rc!=SQLITE_OK ) return rc;
116920     pCsr->pNextId = pCsr->aDoclist;
116921     pCsr->iPrevId = 0;
116922   }
116923 
116924   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
116925   ** statement loops through all rows of the %_content table. For a
116926   ** full-text query or docid lookup, the statement retrieves a single
116927   ** row by docid.
116928   */
116929   if( idxNum==FTS3_FULLSCAN_SEARCH ){
116930     const char *zSort = (pCsr->bDesc ? "DESC" : "ASC");
116931     const char *zTmpl = "SELECT %s FROM %Q.'%q_content' AS x ORDER BY docid %s";
116932     zSql = sqlite3_mprintf(zTmpl, p->zReadExprlist, p->zDb, p->zName, zSort);
116933   }else{
116934     const char *zTmpl = "SELECT %s FROM %Q.'%q_content' AS x WHERE docid = ?";
116935     zSql = sqlite3_mprintf(zTmpl, p->zReadExprlist, p->zDb, p->zName);
116936   }
116937   if( !zSql ) return SQLITE_NOMEM;
116938   rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
116939   sqlite3_free(zSql);
116940   if( rc!=SQLITE_OK ) return rc;
116941 
116942   if( idxNum==FTS3_DOCID_SEARCH ){
116943     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
116944     if( rc!=SQLITE_OK ) return rc;
116945   }
116946 
116947   return fts3NextMethod(pCursor);
116948 }
116949 
116950 /*
116951 ** This is the xEof method of the virtual table. SQLite calls this
116952 ** routine to find out if it has reached the end of a result set.
116953 */
116954 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
116955   return ((Fts3Cursor *)pCursor)->isEof;
116956 }
116957 
116958 /*
116959 ** This is the xRowid method. The SQLite core calls this routine to
116960 ** retrieve the rowid for the current row of the result set. fts3
116961 ** exposes %_content.docid as the rowid for the virtual table. The
116962 ** rowid should be written to *pRowid.
116963 */
116964 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
116965   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116966   *pRowid = pCsr->iPrevId;
116967   return SQLITE_OK;
116968 }
116969 
116970 /*
116971 ** This is the xColumn method, called by SQLite to request a value from
116972 ** the row that the supplied cursor currently points to.
116973 */
116974 static int fts3ColumnMethod(
116975   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
116976   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
116977   int iCol                        /* Index of column to read value from */
116978 ){
116979   int rc = SQLITE_OK;             /* Return Code */
116980   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
116981   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
116982 
116983   /* The column value supplied by SQLite must be in range. */
116984   assert( iCol>=0 && iCol<=p->nColumn+1 );
116985 
116986   if( iCol==p->nColumn+1 ){
116987     /* This call is a request for the "docid" column. Since "docid" is an
116988     ** alias for "rowid", use the xRowid() method to obtain the value.
116989     */
116990     sqlite3_result_int64(pContext, pCsr->iPrevId);
116991   }else if( iCol==p->nColumn ){
116992     /* The extra column whose name is the same as the table.
116993     ** Return a blob which is a pointer to the cursor.
116994     */
116995     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
116996   }else{
116997     rc = fts3CursorSeek(0, pCsr);
116998     if( rc==SQLITE_OK ){
116999       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
117000     }
117001   }
117002 
117003   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
117004   return rc;
117005 }
117006 
117007 /*
117008 ** This function is the implementation of the xUpdate callback used by
117009 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
117010 ** inserted, updated or deleted.
117011 */
117012 static int fts3UpdateMethod(
117013   sqlite3_vtab *pVtab,            /* Virtual table handle */
117014   int nArg,                       /* Size of argument array */
117015   sqlite3_value **apVal,          /* Array of arguments */
117016   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
117017 ){
117018   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
117019 }
117020 
117021 /*
117022 ** Implementation of xSync() method. Flush the contents of the pending-terms
117023 ** hash-table to the database.
117024 */
117025 static int fts3SyncMethod(sqlite3_vtab *pVtab){
117026   int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
117027   sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
117028   return rc;
117029 }
117030 
117031 /*
117032 ** Implementation of xBegin() method. This is a no-op.
117033 */
117034 static int fts3BeginMethod(sqlite3_vtab *pVtab){
117035   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117036   UNUSED_PARAMETER(pVtab);
117037   assert( p->pSegments==0 );
117038   assert( p->nPendingData==0 );
117039   assert( p->inTransaction!=1 );
117040   TESTONLY( p->inTransaction = 1 );
117041   TESTONLY( p->mxSavepoint = -1; );
117042   return SQLITE_OK;
117043 }
117044 
117045 /*
117046 ** Implementation of xCommit() method. This is a no-op. The contents of
117047 ** the pending-terms hash-table have already been flushed into the database
117048 ** by fts3SyncMethod().
117049 */
117050 static int fts3CommitMethod(sqlite3_vtab *pVtab){
117051   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117052   UNUSED_PARAMETER(pVtab);
117053   assert( p->nPendingData==0 );
117054   assert( p->inTransaction!=0 );
117055   assert( p->pSegments==0 );
117056   TESTONLY( p->inTransaction = 0 );
117057   TESTONLY( p->mxSavepoint = -1; );
117058   return SQLITE_OK;
117059 }
117060 
117061 /*
117062 ** Implementation of xRollback(). Discard the contents of the pending-terms
117063 ** hash-table. Any changes made to the database are reverted by SQLite.
117064 */
117065 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
117066   Fts3Table *p = (Fts3Table*)pVtab;
117067   sqlite3Fts3PendingTermsClear(p);
117068   assert( p->inTransaction!=0 );
117069   TESTONLY( p->inTransaction = 0 );
117070   TESTONLY( p->mxSavepoint = -1; );
117071   return SQLITE_OK;
117072 }
117073 
117074 /*
117075 ** When called, *ppPoslist must point to the byte immediately following the
117076 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
117077 ** moves *ppPoslist so that it instead points to the first byte of the
117078 ** same position list.
117079 */
117080 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
117081   char *p = &(*ppPoslist)[-2];
117082   char c;
117083 
117084   while( p>pStart && (c=*p--)==0 );
117085   while( p>pStart && (*p & 0x80) | c ){
117086     c = *p--;
117087   }
117088   if( p>pStart ){ p = &p[2]; }
117089   while( *p++&0x80 );
117090   *ppPoslist = p;
117091 }
117092 
117093 /*
117094 ** Helper function used by the implementation of the overloaded snippet(),
117095 ** offsets() and optimize() SQL functions.
117096 **
117097 ** If the value passed as the third argument is a blob of size
117098 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
117099 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
117100 ** message is written to context pContext and SQLITE_ERROR returned. The
117101 ** string passed via zFunc is used as part of the error message.
117102 */
117103 static int fts3FunctionArg(
117104   sqlite3_context *pContext,      /* SQL function call context */
117105   const char *zFunc,              /* Function name */
117106   sqlite3_value *pVal,            /* argv[0] passed to function */
117107   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
117108 ){
117109   Fts3Cursor *pRet;
117110   if( sqlite3_value_type(pVal)!=SQLITE_BLOB
117111    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
117112   ){
117113     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
117114     sqlite3_result_error(pContext, zErr, -1);
117115     sqlite3_free(zErr);
117116     return SQLITE_ERROR;
117117   }
117118   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
117119   *ppCsr = pRet;
117120   return SQLITE_OK;
117121 }
117122 
117123 /*
117124 ** Implementation of the snippet() function for FTS3
117125 */
117126 static void fts3SnippetFunc(
117127   sqlite3_context *pContext,      /* SQLite function call context */
117128   int nVal,                       /* Size of apVal[] array */
117129   sqlite3_value **apVal           /* Array of arguments */
117130 ){
117131   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
117132   const char *zStart = "<b>";
117133   const char *zEnd = "</b>";
117134   const char *zEllipsis = "<b>...</b>";
117135   int iCol = -1;
117136   int nToken = 15;                /* Default number of tokens in snippet */
117137 
117138   /* There must be at least one argument passed to this function (otherwise
117139   ** the non-overloaded version would have been called instead of this one).
117140   */
117141   assert( nVal>=1 );
117142 
117143   if( nVal>6 ){
117144     sqlite3_result_error(pContext,
117145         "wrong number of arguments to function snippet()", -1);
117146     return;
117147   }
117148   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
117149 
117150   switch( nVal ){
117151     case 6: nToken = sqlite3_value_int(apVal[5]);
117152     case 5: iCol = sqlite3_value_int(apVal[4]);
117153     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
117154     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
117155     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
117156   }
117157   if( !zEllipsis || !zEnd || !zStart ){
117158     sqlite3_result_error_nomem(pContext);
117159   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
117160     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
117161   }
117162 }
117163 
117164 /*
117165 ** Implementation of the offsets() function for FTS3
117166 */
117167 static void fts3OffsetsFunc(
117168   sqlite3_context *pContext,      /* SQLite function call context */
117169   int nVal,                       /* Size of argument array */
117170   sqlite3_value **apVal           /* Array of arguments */
117171 ){
117172   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
117173 
117174   UNUSED_PARAMETER(nVal);
117175 
117176   assert( nVal==1 );
117177   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
117178   assert( pCsr );
117179   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
117180     sqlite3Fts3Offsets(pContext, pCsr);
117181   }
117182 }
117183 
117184 /*
117185 ** Implementation of the special optimize() function for FTS3. This
117186 ** function merges all segments in the database to a single segment.
117187 ** Example usage is:
117188 **
117189 **   SELECT optimize(t) FROM t LIMIT 1;
117190 **
117191 ** where 't' is the name of an FTS3 table.
117192 */
117193 static void fts3OptimizeFunc(
117194   sqlite3_context *pContext,      /* SQLite function call context */
117195   int nVal,                       /* Size of argument array */
117196   sqlite3_value **apVal           /* Array of arguments */
117197 ){
117198   int rc;                         /* Return code */
117199   Fts3Table *p;                   /* Virtual table handle */
117200   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
117201 
117202   UNUSED_PARAMETER(nVal);
117203 
117204   assert( nVal==1 );
117205   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
117206   p = (Fts3Table *)pCursor->base.pVtab;
117207   assert( p );
117208 
117209   rc = sqlite3Fts3Optimize(p);
117210 
117211   switch( rc ){
117212     case SQLITE_OK:
117213       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
117214       break;
117215     case SQLITE_DONE:
117216       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
117217       break;
117218     default:
117219       sqlite3_result_error_code(pContext, rc);
117220       break;
117221   }
117222 }
117223 
117224 /*
117225 ** Implementation of the matchinfo() function for FTS3
117226 */
117227 static void fts3MatchinfoFunc(
117228   sqlite3_context *pContext,      /* SQLite function call context */
117229   int nVal,                       /* Size of argument array */
117230   sqlite3_value **apVal           /* Array of arguments */
117231 ){
117232   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
117233   assert( nVal==1 || nVal==2 );
117234   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
117235     const char *zArg = 0;
117236     if( nVal>1 ){
117237       zArg = (const char *)sqlite3_value_text(apVal[1]);
117238     }
117239     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
117240   }
117241 }
117242 
117243 /*
117244 ** This routine implements the xFindFunction method for the FTS3
117245 ** virtual table.
117246 */
117247 static int fts3FindFunctionMethod(
117248   sqlite3_vtab *pVtab,            /* Virtual table handle */
117249   int nArg,                       /* Number of SQL function arguments */
117250   const char *zName,              /* Name of SQL function */
117251   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
117252   void **ppArg                    /* Unused */
117253 ){
117254   struct Overloaded {
117255     const char *zName;
117256     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
117257   } aOverload[] = {
117258     { "snippet", fts3SnippetFunc },
117259     { "offsets", fts3OffsetsFunc },
117260     { "optimize", fts3OptimizeFunc },
117261     { "matchinfo", fts3MatchinfoFunc },
117262   };
117263   int i;                          /* Iterator variable */
117264 
117265   UNUSED_PARAMETER(pVtab);
117266   UNUSED_PARAMETER(nArg);
117267   UNUSED_PARAMETER(ppArg);
117268 
117269   for(i=0; i<SizeofArray(aOverload); i++){
117270     if( strcmp(zName, aOverload[i].zName)==0 ){
117271       *pxFunc = aOverload[i].xFunc;
117272       return 1;
117273     }
117274   }
117275 
117276   /* No function of the specified name was found. Return 0. */
117277   return 0;
117278 }
117279 
117280 /*
117281 ** Implementation of FTS3 xRename method. Rename an fts3 table.
117282 */
117283 static int fts3RenameMethod(
117284   sqlite3_vtab *pVtab,            /* Virtual table handle */
117285   const char *zName               /* New name of table */
117286 ){
117287   Fts3Table *p = (Fts3Table *)pVtab;
117288   sqlite3 *db = p->db;            /* Database connection */
117289   int rc;                         /* Return Code */
117290 
117291   rc = sqlite3Fts3PendingTermsFlush(p);
117292   if( rc!=SQLITE_OK ){
117293     return rc;
117294   }
117295 
117296   fts3DbExec(&rc, db,
117297     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
117298     p->zDb, p->zName, zName
117299   );
117300   if( p->bHasDocsize ){
117301     fts3DbExec(&rc, db,
117302       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
117303       p->zDb, p->zName, zName
117304     );
117305   }
117306   if( p->bHasStat ){
117307     fts3DbExec(&rc, db,
117308       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
117309       p->zDb, p->zName, zName
117310     );
117311   }
117312   fts3DbExec(&rc, db,
117313     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
117314     p->zDb, p->zName, zName
117315   );
117316   fts3DbExec(&rc, db,
117317     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
117318     p->zDb, p->zName, zName
117319   );
117320   return rc;
117321 }
117322 
117323 /*
117324 ** The xSavepoint() method.
117325 **
117326 ** Flush the contents of the pending-terms table to disk.
117327 */
117328 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
117329   UNUSED_PARAMETER(iSavepoint);
117330   assert( ((Fts3Table *)pVtab)->inTransaction );
117331   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
117332   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
117333   return fts3SyncMethod(pVtab);
117334 }
117335 
117336 /*
117337 ** The xRelease() method.
117338 **
117339 ** This is a no-op.
117340 */
117341 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
117342   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
117343   UNUSED_PARAMETER(iSavepoint);
117344   UNUSED_PARAMETER(pVtab);
117345   assert( p->inTransaction );
117346   assert( p->mxSavepoint >= iSavepoint );
117347   TESTONLY( p->mxSavepoint = iSavepoint-1 );
117348   return SQLITE_OK;
117349 }
117350 
117351 /*
117352 ** The xRollbackTo() method.
117353 **
117354 ** Discard the contents of the pending terms table.
117355 */
117356 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
117357   Fts3Table *p = (Fts3Table*)pVtab;
117358   UNUSED_PARAMETER(iSavepoint);
117359   assert( p->inTransaction );
117360   assert( p->mxSavepoint >= iSavepoint );
117361   TESTONLY( p->mxSavepoint = iSavepoint );
117362   sqlite3Fts3PendingTermsClear(p);
117363   return SQLITE_OK;
117364 }
117365 
117366 static const sqlite3_module fts3Module = {
117367   /* iVersion      */ 2,
117368   /* xCreate       */ fts3CreateMethod,
117369   /* xConnect      */ fts3ConnectMethod,
117370   /* xBestIndex    */ fts3BestIndexMethod,
117371   /* xDisconnect   */ fts3DisconnectMethod,
117372   /* xDestroy      */ fts3DestroyMethod,
117373   /* xOpen         */ fts3OpenMethod,
117374   /* xClose        */ fts3CloseMethod,
117375   /* xFilter       */ fts3FilterMethod,
117376   /* xNext         */ fts3NextMethod,
117377   /* xEof          */ fts3EofMethod,
117378   /* xColumn       */ fts3ColumnMethod,
117379   /* xRowid        */ fts3RowidMethod,
117380   /* xUpdate       */ fts3UpdateMethod,
117381   /* xBegin        */ fts3BeginMethod,
117382   /* xSync         */ fts3SyncMethod,
117383   /* xCommit       */ fts3CommitMethod,
117384   /* xRollback     */ fts3RollbackMethod,
117385   /* xFindFunction */ fts3FindFunctionMethod,
117386   /* xRename */       fts3RenameMethod,
117387   /* xSavepoint    */ fts3SavepointMethod,
117388   /* xRelease      */ fts3ReleaseMethod,
117389   /* xRollbackTo   */ fts3RollbackToMethod,
117390 };
117391 
117392 /*
117393 ** This function is registered as the module destructor (called when an
117394 ** FTS3 enabled database connection is closed). It frees the memory
117395 ** allocated for the tokenizer hash table.
117396 */
117397 static void hashDestroy(void *p){
117398   Fts3Hash *pHash = (Fts3Hash *)p;
117399   sqlite3Fts3HashClear(pHash);
117400   sqlite3_free(pHash);
117401 }
117402 
117403 /*
117404 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
117405 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
117406 ** respectively. The following three forward declarations are for functions
117407 ** declared in these files used to retrieve the respective implementations.
117408 **
117409 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
117410 ** to by the argument to point to the "simple" tokenizer implementation.
117411 ** And so on.
117412 */
117413 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117414 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117415 #ifdef SQLITE_ENABLE_ICU
117416 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
117417 #endif
117418 
117419 /*
117420 ** Initialise the fts3 extension. If this extension is built as part
117421 ** of the sqlite library, then this function is called directly by
117422 ** SQLite. If fts3 is built as a dynamically loadable extension, this
117423 ** function is called by the sqlite3_extension_init() entry point.
117424 */
117425 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
117426   int rc = SQLITE_OK;
117427   Fts3Hash *pHash = 0;
117428   const sqlite3_tokenizer_module *pSimple = 0;
117429   const sqlite3_tokenizer_module *pPorter = 0;
117430 
117431 #ifdef SQLITE_ENABLE_ICU
117432   const sqlite3_tokenizer_module *pIcu = 0;
117433   sqlite3Fts3IcuTokenizerModule(&pIcu);
117434 #endif
117435 
117436 #ifdef SQLITE_TEST
117437   rc = sqlite3Fts3InitTerm(db);
117438   if( rc!=SQLITE_OK ) return rc;
117439 #endif
117440 
117441   rc = sqlite3Fts3InitAux(db);
117442   if( rc!=SQLITE_OK ) return rc;
117443 
117444   sqlite3Fts3SimpleTokenizerModule(&pSimple);
117445   sqlite3Fts3PorterTokenizerModule(&pPorter);
117446 
117447   /* Allocate and initialise the hash-table used to store tokenizers. */
117448   pHash = sqlite3_malloc(sizeof(Fts3Hash));
117449   if( !pHash ){
117450     rc = SQLITE_NOMEM;
117451   }else{
117452     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
117453   }
117454 
117455   /* Load the built-in tokenizers into the hash table */
117456   if( rc==SQLITE_OK ){
117457     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
117458      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
117459 #ifdef SQLITE_ENABLE_ICU
117460      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
117461 #endif
117462     ){
117463       rc = SQLITE_NOMEM;
117464     }
117465   }
117466 
117467 #ifdef SQLITE_TEST
117468   if( rc==SQLITE_OK ){
117469     rc = sqlite3Fts3ExprInitTestInterface(db);
117470   }
117471 #endif
117472 
117473   /* Create the virtual table wrapper around the hash-table and overload
117474   ** the two scalar functions. If this is successful, register the
117475   ** module with sqlite.
117476   */
117477   if( SQLITE_OK==rc
117478    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
117479    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
117480    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
117481    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
117482    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
117483    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
117484   ){
117485     rc = sqlite3_create_module_v2(
117486         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
117487     );
117488     if( rc==SQLITE_OK ){
117489       rc = sqlite3_create_module_v2(
117490           db, "fts4", &fts3Module, (void *)pHash, 0
117491       );
117492     }
117493     return rc;
117494   }
117495 
117496   /* An error has occurred. Delete the hash table and return the error code. */
117497   assert( rc!=SQLITE_OK );
117498   if( pHash ){
117499     sqlite3Fts3HashClear(pHash);
117500     sqlite3_free(pHash);
117501   }
117502   return rc;
117503 }
117504 
117505 /*
117506 ** Allocate an Fts3MultiSegReader for each token in the expression headed
117507 ** by pExpr.
117508 **
117509 ** An Fts3SegReader object is a cursor that can seek or scan a range of
117510 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
117511 ** Fts3SegReader objects internally to provide an interface to seek or scan
117512 ** within the union of all segments of a b-tree. Hence the name.
117513 **
117514 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
117515 ** segment b-tree (if the term is not a prefix or it is a prefix for which
117516 ** there exists prefix b-tree of the right length) then it may be traversed
117517 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
117518 ** doclist and then traversed.
117519 */
117520 static void fts3EvalAllocateReaders(
117521   Fts3Cursor *pCsr,               /* FTS cursor handle */
117522   Fts3Expr *pExpr,                /* Allocate readers for this expression */
117523   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
117524   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
117525   int *pRc                        /* IN/OUT: Error code */
117526 ){
117527   if( pExpr && SQLITE_OK==*pRc ){
117528     if( pExpr->eType==FTSQUERY_PHRASE ){
117529       int i;
117530       int nToken = pExpr->pPhrase->nToken;
117531       *pnToken += nToken;
117532       for(i=0; i<nToken; i++){
117533         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
117534         int rc = fts3TermSegReaderCursor(pCsr,
117535             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
117536         );
117537         if( rc!=SQLITE_OK ){
117538           *pRc = rc;
117539           return;
117540         }
117541       }
117542       assert( pExpr->pPhrase->iDoclistToken==0 );
117543       pExpr->pPhrase->iDoclistToken = -1;
117544     }else{
117545       *pnOr += (pExpr->eType==FTSQUERY_OR);
117546       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
117547       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
117548     }
117549   }
117550 }
117551 
117552 /*
117553 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
117554 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
117555 **
117556 ** This function assumes that pList points to a buffer allocated using
117557 ** sqlite3_malloc(). This function takes responsibility for eventually
117558 ** freeing the buffer.
117559 */
117560 static void fts3EvalPhraseMergeToken(
117561   Fts3Table *pTab,                /* FTS Table pointer */
117562   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
117563   int iToken,                     /* Token pList/nList corresponds to */
117564   char *pList,                    /* Pointer to doclist */
117565   int nList                       /* Number of bytes in pList */
117566 ){
117567   assert( iToken!=p->iDoclistToken );
117568 
117569   if( pList==0 ){
117570     sqlite3_free(p->doclist.aAll);
117571     p->doclist.aAll = 0;
117572     p->doclist.nAll = 0;
117573   }
117574 
117575   else if( p->iDoclistToken<0 ){
117576     p->doclist.aAll = pList;
117577     p->doclist.nAll = nList;
117578   }
117579 
117580   else if( p->doclist.aAll==0 ){
117581     sqlite3_free(pList);
117582   }
117583 
117584   else {
117585     char *pLeft;
117586     char *pRight;
117587     int nLeft;
117588     int nRight;
117589     int nDiff;
117590 
117591     if( p->iDoclistToken<iToken ){
117592       pLeft = p->doclist.aAll;
117593       nLeft = p->doclist.nAll;
117594       pRight = pList;
117595       nRight = nList;
117596       nDiff = iToken - p->iDoclistToken;
117597     }else{
117598       pRight = p->doclist.aAll;
117599       nRight = p->doclist.nAll;
117600       pLeft = pList;
117601       nLeft = nList;
117602       nDiff = p->iDoclistToken - iToken;
117603     }
117604 
117605     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
117606     sqlite3_free(pLeft);
117607     p->doclist.aAll = pRight;
117608     p->doclist.nAll = nRight;
117609   }
117610 
117611   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
117612 }
117613 
117614 /*
117615 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
117616 ** does not take deferred tokens into account.
117617 **
117618 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
117619 */
117620 static int fts3EvalPhraseLoad(
117621   Fts3Cursor *pCsr,               /* FTS Cursor handle */
117622   Fts3Phrase *p                   /* Phrase object */
117623 ){
117624   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
117625   int iToken;
117626   int rc = SQLITE_OK;
117627 
117628   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
117629     Fts3PhraseToken *pToken = &p->aToken[iToken];
117630     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
117631 
117632     if( pToken->pSegcsr ){
117633       int nThis = 0;
117634       char *pThis = 0;
117635       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
117636       if( rc==SQLITE_OK ){
117637         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
117638       }
117639     }
117640     assert( pToken->pSegcsr==0 );
117641   }
117642 
117643   return rc;
117644 }
117645 
117646 /*
117647 ** This function is called on each phrase after the position lists for
117648 ** any deferred tokens have been loaded into memory. It updates the phrases
117649 ** current position list to include only those positions that are really
117650 ** instances of the phrase (after considering deferred tokens). If this
117651 ** means that the phrase does not appear in the current row, doclist.pList
117652 ** and doclist.nList are both zeroed.
117653 **
117654 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
117655 */
117656 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
117657   int iToken;                     /* Used to iterate through phrase tokens */
117658   int rc = SQLITE_OK;             /* Return code */
117659   char *aPoslist = 0;             /* Position list for deferred tokens */
117660   int nPoslist = 0;               /* Number of bytes in aPoslist */
117661   int iPrev = -1;                 /* Token number of previous deferred token */
117662 
117663   assert( pPhrase->doclist.bFreeList==0 );
117664 
117665   for(iToken=0; rc==SQLITE_OK && iToken<pPhrase->nToken; iToken++){
117666     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
117667     Fts3DeferredToken *pDeferred = pToken->pDeferred;
117668 
117669     if( pDeferred ){
117670       char *pList;
117671       int nList;
117672       rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
117673       if( rc!=SQLITE_OK ) return rc;
117674 
117675       if( pList==0 ){
117676         sqlite3_free(aPoslist);
117677         pPhrase->doclist.pList = 0;
117678         pPhrase->doclist.nList = 0;
117679         return SQLITE_OK;
117680 
117681       }else if( aPoslist==0 ){
117682         aPoslist = pList;
117683         nPoslist = nList;
117684 
117685       }else{
117686         char *aOut = pList;
117687         char *p1 = aPoslist;
117688         char *p2 = aOut;
117689 
117690         assert( iPrev>=0 );
117691         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
117692         sqlite3_free(aPoslist);
117693         aPoslist = pList;
117694         nPoslist = aOut - aPoslist;
117695         if( nPoslist==0 ){
117696           sqlite3_free(aPoslist);
117697           pPhrase->doclist.pList = 0;
117698           pPhrase->doclist.nList = 0;
117699           return SQLITE_OK;
117700         }
117701       }
117702       iPrev = iToken;
117703     }
117704   }
117705 
117706   if( iPrev>=0 ){
117707     int nMaxUndeferred = pPhrase->iDoclistToken;
117708     if( nMaxUndeferred<0 ){
117709       pPhrase->doclist.pList = aPoslist;
117710       pPhrase->doclist.nList = nPoslist;
117711       pPhrase->doclist.iDocid = pCsr->iPrevId;
117712       pPhrase->doclist.bFreeList = 1;
117713     }else{
117714       int nDistance;
117715       char *p1;
117716       char *p2;
117717       char *aOut;
117718 
117719       if( nMaxUndeferred>iPrev ){
117720         p1 = aPoslist;
117721         p2 = pPhrase->doclist.pList;
117722         nDistance = nMaxUndeferred - iPrev;
117723       }else{
117724         p1 = pPhrase->doclist.pList;
117725         p2 = aPoslist;
117726         nDistance = iPrev - nMaxUndeferred;
117727       }
117728 
117729       aOut = (char *)sqlite3_malloc(nPoslist+8);
117730       if( !aOut ){
117731         sqlite3_free(aPoslist);
117732         return SQLITE_NOMEM;
117733       }
117734 
117735       pPhrase->doclist.pList = aOut;
117736       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
117737         pPhrase->doclist.bFreeList = 1;
117738         pPhrase->doclist.nList = (aOut - pPhrase->doclist.pList);
117739       }else{
117740         sqlite3_free(aOut);
117741         pPhrase->doclist.pList = 0;
117742         pPhrase->doclist.nList = 0;
117743       }
117744       sqlite3_free(aPoslist);
117745     }
117746   }
117747 
117748   return SQLITE_OK;
117749 }
117750 
117751 /*
117752 ** This function is called for each Fts3Phrase in a full-text query
117753 ** expression to initialize the mechanism for returning rows. Once this
117754 ** function has been called successfully on an Fts3Phrase, it may be
117755 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
117756 **
117757 ** If parameter bOptOk is true, then the phrase may (or may not) use the
117758 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
117759 ** memory within this call.
117760 **
117761 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
117762 */
117763 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
117764   int rc;                         /* Error code */
117765   Fts3PhraseToken *pFirst = &p->aToken[0];
117766   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
117767 
117768   if( pCsr->bDesc==pTab->bDescIdx
117769    && bOptOk==1
117770    && p->nToken==1
117771    && pFirst->pSegcsr
117772    && pFirst->pSegcsr->bLookup
117773   ){
117774     /* Use the incremental approach. */
117775     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
117776     rc = sqlite3Fts3MsrIncrStart(
117777         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
117778     p->bIncr = 1;
117779 
117780   }else{
117781     /* Load the full doclist for the phrase into memory. */
117782     rc = fts3EvalPhraseLoad(pCsr, p);
117783     p->bIncr = 0;
117784   }
117785 
117786   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
117787   return rc;
117788 }
117789 
117790 /*
117791 ** This function is used to iterate backwards (from the end to start)
117792 ** through doclists. It is used by this module to iterate through phrase
117793 ** doclists in reverse and by the fts3_write.c module to iterate through
117794 ** pending-terms lists when writing to databases with "order=desc".
117795 **
117796 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
117797 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
117798 ** function iterates from the end of the doclist to the beginning.
117799 */
117800 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
117801   int bDescIdx,                   /* True if the doclist is desc */
117802   char *aDoclist,                 /* Pointer to entire doclist */
117803   int nDoclist,                   /* Length of aDoclist in bytes */
117804   char **ppIter,                  /* IN/OUT: Iterator pointer */
117805   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
117806   int *pnList,                    /* IN/OUT: List length pointer */
117807   u8 *pbEof                       /* OUT: End-of-file flag */
117808 ){
117809   char *p = *ppIter;
117810 
117811   assert( nDoclist>0 );
117812   assert( *pbEof==0 );
117813   assert( p || *piDocid==0 );
117814   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
117815 
117816   if( p==0 ){
117817     sqlite3_int64 iDocid = 0;
117818     char *pNext = 0;
117819     char *pDocid = aDoclist;
117820     char *pEnd = &aDoclist[nDoclist];
117821     int iMul = 1;
117822 
117823     while( pDocid<pEnd ){
117824       sqlite3_int64 iDelta;
117825       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
117826       iDocid += (iMul * iDelta);
117827       pNext = pDocid;
117828       fts3PoslistCopy(0, &pDocid);
117829       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
117830       iMul = (bDescIdx ? -1 : 1);
117831     }
117832 
117833     *pnList = pEnd - pNext;
117834     *ppIter = pNext;
117835     *piDocid = iDocid;
117836   }else{
117837     int iMul = (bDescIdx ? -1 : 1);
117838     sqlite3_int64 iDelta;
117839     fts3GetReverseVarint(&p, aDoclist, &iDelta);
117840     *piDocid -= (iMul * iDelta);
117841 
117842     if( p==aDoclist ){
117843       *pbEof = 1;
117844     }else{
117845       char *pSave = p;
117846       fts3ReversePoslist(aDoclist, &p);
117847       *pnList = (pSave - p);
117848     }
117849     *ppIter = p;
117850   }
117851 }
117852 
117853 /*
117854 ** Attempt to move the phrase iterator to point to the next matching docid.
117855 ** If an error occurs, return an SQLite error code. Otherwise, return
117856 ** SQLITE_OK.
117857 **
117858 ** If there is no "next" entry and no error occurs, then *pbEof is set to
117859 ** 1 before returning. Otherwise, if no error occurs and the iterator is
117860 ** successfully advanced, *pbEof is set to 0.
117861 */
117862 static int fts3EvalPhraseNext(
117863   Fts3Cursor *pCsr,               /* FTS Cursor handle */
117864   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
117865   u8 *pbEof                       /* OUT: Set to 1 if EOF */
117866 ){
117867   int rc = SQLITE_OK;
117868   Fts3Doclist *pDL = &p->doclist;
117869   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
117870 
117871   if( p->bIncr ){
117872     assert( p->nToken==1 );
117873     assert( pDL->pNextDocid==0 );
117874     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
117875         &pDL->iDocid, &pDL->pList, &pDL->nList
117876     );
117877     if( rc==SQLITE_OK && !pDL->pList ){
117878       *pbEof = 1;
117879     }
117880   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
117881     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
117882         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
117883     );
117884     pDL->pList = pDL->pNextDocid;
117885   }else{
117886     char *pIter;                            /* Used to iterate through aAll */
117887     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
117888     if( pDL->pNextDocid ){
117889       pIter = pDL->pNextDocid;
117890     }else{
117891       pIter = pDL->aAll;
117892     }
117893 
117894     if( pIter>=pEnd ){
117895       /* We have already reached the end of this doclist. EOF. */
117896       *pbEof = 1;
117897     }else{
117898       sqlite3_int64 iDelta;
117899       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
117900       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
117901         pDL->iDocid += iDelta;
117902       }else{
117903         pDL->iDocid -= iDelta;
117904       }
117905       pDL->pList = pIter;
117906       fts3PoslistCopy(0, &pIter);
117907       pDL->nList = (pIter - pDL->pList);
117908 
117909       /* pIter now points just past the 0x00 that terminates the position-
117910       ** list for document pDL->iDocid. However, if this position-list was
117911       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
117912       ** point to the start of the next docid value. The following line deals
117913       ** with this case by advancing pIter past the zero-padding added by
117914       ** fts3EvalNearTrim().  */
117915       while( pIter<pEnd && *pIter==0 ) pIter++;
117916 
117917       pDL->pNextDocid = pIter;
117918       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
117919       *pbEof = 0;
117920     }
117921   }
117922 
117923   return rc;
117924 }
117925 
117926 /*
117927 **
117928 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
117929 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
117930 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
117931 ** expressions for which all descendent tokens are deferred.
117932 **
117933 ** If parameter bOptOk is zero, then it is guaranteed that the
117934 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
117935 ** each phrase in the expression (subject to deferred token processing).
117936 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
117937 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
117938 **
117939 ** If an error occurs within this function, *pRc is set to an SQLite error
117940 ** code before returning.
117941 */
117942 static void fts3EvalStartReaders(
117943   Fts3Cursor *pCsr,               /* FTS Cursor handle */
117944   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
117945   int bOptOk,                     /* True to enable incremental loading */
117946   int *pRc                        /* IN/OUT: Error code */
117947 ){
117948   if( pExpr && SQLITE_OK==*pRc ){
117949     if( pExpr->eType==FTSQUERY_PHRASE ){
117950       int i;
117951       int nToken = pExpr->pPhrase->nToken;
117952       for(i=0; i<nToken; i++){
117953         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
117954       }
117955       pExpr->bDeferred = (i==nToken);
117956       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
117957     }else{
117958       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
117959       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
117960       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
117961     }
117962   }
117963 }
117964 
117965 /*
117966 ** An array of the following structures is assembled as part of the process
117967 ** of selecting tokens to defer before the query starts executing (as part
117968 ** of the xFilter() method). There is one element in the array for each
117969 ** token in the FTS expression.
117970 **
117971 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
117972 ** to phrases that are connected only by AND and NEAR operators (not OR or
117973 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
117974 ** separately. The root of a tokens AND/NEAR cluster is stored in
117975 ** Fts3TokenAndCost.pRoot.
117976 */
117977 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
117978 struct Fts3TokenAndCost {
117979   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
117980   int iToken;                     /* Position of token in phrase */
117981   Fts3PhraseToken *pToken;        /* The token itself */
117982   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
117983   int nOvfl;                      /* Number of overflow pages to load doclist */
117984   int iCol;                       /* The column the token must match */
117985 };
117986 
117987 /*
117988 ** This function is used to populate an allocated Fts3TokenAndCost array.
117989 **
117990 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
117991 ** Otherwise, if an error occurs during execution, *pRc is set to an
117992 ** SQLite error code.
117993 */
117994 static void fts3EvalTokenCosts(
117995   Fts3Cursor *pCsr,               /* FTS Cursor handle */
117996   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
117997   Fts3Expr *pExpr,                /* Expression to consider */
117998   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
117999   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
118000   int *pRc                        /* IN/OUT: Error code */
118001 ){
118002   if( *pRc==SQLITE_OK && pExpr ){
118003     if( pExpr->eType==FTSQUERY_PHRASE ){
118004       Fts3Phrase *pPhrase = pExpr->pPhrase;
118005       int i;
118006       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
118007         Fts3TokenAndCost *pTC = (*ppTC)++;
118008         pTC->pPhrase = pPhrase;
118009         pTC->iToken = i;
118010         pTC->pRoot = pRoot;
118011         pTC->pToken = &pPhrase->aToken[i];
118012         pTC->iCol = pPhrase->iColumn;
118013         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
118014       }
118015     }else if( pExpr->eType!=FTSQUERY_NOT ){
118016       if( pExpr->eType==FTSQUERY_OR ){
118017         pRoot = pExpr->pLeft;
118018         **ppOr = pRoot;
118019         (*ppOr)++;
118020       }
118021       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
118022       if( pExpr->eType==FTSQUERY_OR ){
118023         pRoot = pExpr->pRight;
118024         **ppOr = pRoot;
118025         (*ppOr)++;
118026       }
118027       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
118028     }
118029   }
118030 }
118031 
118032 /*
118033 ** Determine the average document (row) size in pages. If successful,
118034 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
118035 ** an SQLite error code.
118036 **
118037 ** The average document size in pages is calculated by first calculating
118038 ** determining the average size in bytes, B. If B is less than the amount
118039 ** of data that will fit on a single leaf page of an intkey table in
118040 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
118041 ** the number of overflow pages consumed by a record B bytes in size.
118042 */
118043 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
118044   if( pCsr->nRowAvg==0 ){
118045     /* The average document size, which is required to calculate the cost
118046     ** of each doclist, has not yet been determined. Read the required
118047     ** data from the %_stat table to calculate it.
118048     **
118049     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
118050     ** varints, where nCol is the number of columns in the FTS3 table.
118051     ** The first varint is the number of documents currently stored in
118052     ** the table. The following nCol varints contain the total amount of
118053     ** data stored in all rows of each column of the table, from left
118054     ** to right.
118055     */
118056     int rc;
118057     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
118058     sqlite3_stmt *pStmt;
118059     sqlite3_int64 nDoc = 0;
118060     sqlite3_int64 nByte = 0;
118061     const char *pEnd;
118062     const char *a;
118063 
118064     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
118065     if( rc!=SQLITE_OK ) return rc;
118066     a = sqlite3_column_blob(pStmt, 0);
118067     assert( a );
118068 
118069     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
118070     a += sqlite3Fts3GetVarint(a, &nDoc);
118071     while( a<pEnd ){
118072       a += sqlite3Fts3GetVarint(a, &nByte);
118073     }
118074     if( nDoc==0 || nByte==0 ){
118075       sqlite3_reset(pStmt);
118076       return SQLITE_CORRUPT_VTAB;
118077     }
118078 
118079     pCsr->nDoc = nDoc;
118080     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
118081     assert( pCsr->nRowAvg>0 );
118082     rc = sqlite3_reset(pStmt);
118083     if( rc!=SQLITE_OK ) return rc;
118084   }
118085 
118086   *pnPage = pCsr->nRowAvg;
118087   return SQLITE_OK;
118088 }
118089 
118090 /*
118091 ** This function is called to select the tokens (if any) that will be
118092 ** deferred. The array aTC[] has already been populated when this is
118093 ** called.
118094 **
118095 ** This function is called once for each AND/NEAR cluster in the
118096 ** expression. Each invocation determines which tokens to defer within
118097 ** the cluster with root node pRoot. See comments above the definition
118098 ** of struct Fts3TokenAndCost for more details.
118099 **
118100 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
118101 ** called on each token to defer. Otherwise, an SQLite error code is
118102 ** returned.
118103 */
118104 static int fts3EvalSelectDeferred(
118105   Fts3Cursor *pCsr,               /* FTS Cursor handle */
118106   Fts3Expr *pRoot,                /* Consider tokens with this root node */
118107   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
118108   int nTC                         /* Number of entries in aTC[] */
118109 ){
118110   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118111   int nDocSize = 0;               /* Number of pages per doc loaded */
118112   int rc = SQLITE_OK;             /* Return code */
118113   int ii;                         /* Iterator variable for various purposes */
118114   int nOvfl = 0;                  /* Total overflow pages used by doclists */
118115   int nToken = 0;                 /* Total number of tokens in cluster */
118116 
118117   int nMinEst = 0;                /* The minimum count for any phrase so far. */
118118   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
118119 
118120   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
118121   ** associated with the tokens spill onto overflow pages, or if there is
118122   ** only 1 token, exit early. No tokens to defer in this case. */
118123   for(ii=0; ii<nTC; ii++){
118124     if( aTC[ii].pRoot==pRoot ){
118125       nOvfl += aTC[ii].nOvfl;
118126       nToken++;
118127     }
118128   }
118129   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
118130 
118131   /* Obtain the average docsize (in pages). */
118132   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
118133   assert( rc!=SQLITE_OK || nDocSize>0 );
118134 
118135 
118136   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
118137   ** of the number of overflow pages that will be loaded by the pager layer
118138   ** to retrieve the entire doclist for the token from the full-text index.
118139   ** Load the doclists for tokens that are either:
118140   **
118141   **   a. The cheapest token in the entire query (i.e. the one visited by the
118142   **      first iteration of this loop), or
118143   **
118144   **   b. Part of a multi-token phrase.
118145   **
118146   ** After each token doclist is loaded, merge it with the others from the
118147   ** same phrase and count the number of documents that the merged doclist
118148   ** contains. Set variable "nMinEst" to the smallest number of documents in
118149   ** any phrase doclist for which 1 or more token doclists have been loaded.
118150   ** Let nOther be the number of other phrases for which it is certain that
118151   ** one or more tokens will not be deferred.
118152   **
118153   ** Then, for each token, defer it if loading the doclist would result in
118154   ** loading N or more overflow pages into memory, where N is computed as:
118155   **
118156   **    (nMinEst + 4^nOther - 1) / (4^nOther)
118157   */
118158   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
118159     int iTC;                      /* Used to iterate through aTC[] array. */
118160     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
118161 
118162     /* Set pTC to point to the cheapest remaining token. */
118163     for(iTC=0; iTC<nTC; iTC++){
118164       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
118165        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
118166       ){
118167         pTC = &aTC[iTC];
118168       }
118169     }
118170     assert( pTC );
118171 
118172     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
118173       /* The number of overflow pages to load for this (and therefore all
118174       ** subsequent) tokens is greater than the estimated number of pages
118175       ** that will be loaded if all subsequent tokens are deferred.
118176       */
118177       Fts3PhraseToken *pToken = pTC->pToken;
118178       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
118179       fts3SegReaderCursorFree(pToken->pSegcsr);
118180       pToken->pSegcsr = 0;
118181     }else{
118182       nLoad4 = nLoad4*4;
118183       if( ii==0 || pTC->pPhrase->nToken>1 ){
118184         /* Either this is the cheapest token in the entire query, or it is
118185         ** part of a multi-token phrase. Either way, the entire doclist will
118186         ** (eventually) be loaded into memory. It may as well be now. */
118187         Fts3PhraseToken *pToken = pTC->pToken;
118188         int nList = 0;
118189         char *pList = 0;
118190         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
118191         assert( rc==SQLITE_OK || pList==0 );
118192         if( rc==SQLITE_OK ){
118193           int nCount;
118194           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
118195           nCount = fts3DoclistCountDocids(
118196               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
118197           );
118198           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
118199         }
118200       }
118201     }
118202     pTC->pToken = 0;
118203   }
118204 
118205   return rc;
118206 }
118207 
118208 /*
118209 ** This function is called from within the xFilter method. It initializes
118210 ** the full-text query currently stored in pCsr->pExpr. To iterate through
118211 ** the results of a query, the caller does:
118212 **
118213 **    fts3EvalStart(pCsr);
118214 **    while( 1 ){
118215 **      fts3EvalNext(pCsr);
118216 **      if( pCsr->bEof ) break;
118217 **      ... return row pCsr->iPrevId to the caller ...
118218 **    }
118219 */
118220 static int fts3EvalStart(Fts3Cursor *pCsr){
118221   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118222   int rc = SQLITE_OK;
118223   int nToken = 0;
118224   int nOr = 0;
118225 
118226   /* Allocate a MultiSegReader for each token in the expression. */
118227   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
118228 
118229   /* Determine which, if any, tokens in the expression should be deferred. */
118230   if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
118231     Fts3TokenAndCost *aTC;
118232     Fts3Expr **apOr;
118233     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
118234         sizeof(Fts3TokenAndCost) * nToken
118235       + sizeof(Fts3Expr *) * nOr * 2
118236     );
118237     apOr = (Fts3Expr **)&aTC[nToken];
118238 
118239     if( !aTC ){
118240       rc = SQLITE_NOMEM;
118241     }else{
118242       int ii;
118243       Fts3TokenAndCost *pTC = aTC;
118244       Fts3Expr **ppOr = apOr;
118245 
118246       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
118247       nToken = pTC-aTC;
118248       nOr = ppOr-apOr;
118249 
118250       if( rc==SQLITE_OK ){
118251         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
118252         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
118253           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
118254         }
118255       }
118256 
118257       sqlite3_free(aTC);
118258     }
118259   }
118260 
118261   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
118262   return rc;
118263 }
118264 
118265 /*
118266 ** Invalidate the current position list for phrase pPhrase.
118267 */
118268 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
118269   if( pPhrase->doclist.bFreeList ){
118270     sqlite3_free(pPhrase->doclist.pList);
118271   }
118272   pPhrase->doclist.pList = 0;
118273   pPhrase->doclist.nList = 0;
118274   pPhrase->doclist.bFreeList = 0;
118275 }
118276 
118277 /*
118278 ** This function is called to edit the position list associated with
118279 ** the phrase object passed as the fifth argument according to a NEAR
118280 ** condition. For example:
118281 **
118282 **     abc NEAR/5 "def ghi"
118283 **
118284 ** Parameter nNear is passed the NEAR distance of the expression (5 in
118285 ** the example above). When this function is called, *paPoslist points to
118286 ** the position list, and *pnToken is the number of phrase tokens in, the
118287 ** phrase on the other side of the NEAR operator to pPhrase. For example,
118288 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
118289 ** the position list associated with phrase "abc".
118290 **
118291 ** All positions in the pPhrase position list that are not sufficiently
118292 ** close to a position in the *paPoslist position list are removed. If this
118293 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
118294 **
118295 ** Before returning, *paPoslist is set to point to the position lsit
118296 ** associated with pPhrase. And *pnToken is set to the number of tokens in
118297 ** pPhrase.
118298 */
118299 static int fts3EvalNearTrim(
118300   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
118301   char *aTmp,                     /* Temporary space to use */
118302   char **paPoslist,               /* IN/OUT: Position list */
118303   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
118304   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
118305 ){
118306   int nParam1 = nNear + pPhrase->nToken;
118307   int nParam2 = nNear + *pnToken;
118308   int nNew;
118309   char *p2;
118310   char *pOut;
118311   int res;
118312 
118313   assert( pPhrase->doclist.pList );
118314 
118315   p2 = pOut = pPhrase->doclist.pList;
118316   res = fts3PoslistNearMerge(
118317     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
118318   );
118319   if( res ){
118320     nNew = (pOut - pPhrase->doclist.pList) - 1;
118321     assert( pPhrase->doclist.pList[nNew]=='\0' );
118322     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
118323     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
118324     pPhrase->doclist.nList = nNew;
118325     *paPoslist = pPhrase->doclist.pList;
118326     *pnToken = pPhrase->nToken;
118327   }
118328 
118329   return res;
118330 }
118331 
118332 /*
118333 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
118334 ** Otherwise, it advances the expression passed as the second argument to
118335 ** point to the next matching row in the database. Expressions iterate through
118336 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
118337 ** or descending if it is non-zero.
118338 **
118339 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
118340 ** successful, the following variables in pExpr are set:
118341 **
118342 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
118343 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
118344 **
118345 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
118346 ** at EOF, then the following variables are populated with the position list
118347 ** for the phrase for the visited row:
118348 **
118349 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
118350 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
118351 **
118352 ** It says above that this function advances the expression to the next
118353 ** matching row. This is usually true, but there are the following exceptions:
118354 **
118355 **   1. Deferred tokens are not taken into account. If a phrase consists
118356 **      entirely of deferred tokens, it is assumed to match every row in
118357 **      the db. In this case the position-list is not populated at all.
118358 **
118359 **      Or, if a phrase contains one or more deferred tokens and one or
118360 **      more non-deferred tokens, then the expression is advanced to the
118361 **      next possible match, considering only non-deferred tokens. In other
118362 **      words, if the phrase is "A B C", and "B" is deferred, the expression
118363 **      is advanced to the next row that contains an instance of "A * C",
118364 **      where "*" may match any single token. The position list in this case
118365 **      is populated as for "A * C" before returning.
118366 **
118367 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
118368 **      advanced to point to the next row that matches "x AND y".
118369 **
118370 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
118371 ** really a match, taking into account deferred tokens and NEAR operators.
118372 */
118373 static void fts3EvalNextRow(
118374   Fts3Cursor *pCsr,               /* FTS Cursor handle */
118375   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
118376   int *pRc                        /* IN/OUT: Error code */
118377 ){
118378   if( *pRc==SQLITE_OK ){
118379     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
118380     assert( pExpr->bEof==0 );
118381     pExpr->bStart = 1;
118382 
118383     switch( pExpr->eType ){
118384       case FTSQUERY_NEAR:
118385       case FTSQUERY_AND: {
118386         Fts3Expr *pLeft = pExpr->pLeft;
118387         Fts3Expr *pRight = pExpr->pRight;
118388         assert( !pLeft->bDeferred || !pRight->bDeferred );
118389 
118390         if( pLeft->bDeferred ){
118391           /* LHS is entirely deferred. So we assume it matches every row.
118392           ** Advance the RHS iterator to find the next row visited. */
118393           fts3EvalNextRow(pCsr, pRight, pRc);
118394           pExpr->iDocid = pRight->iDocid;
118395           pExpr->bEof = pRight->bEof;
118396         }else if( pRight->bDeferred ){
118397           /* RHS is entirely deferred. So we assume it matches every row.
118398           ** Advance the LHS iterator to find the next row visited. */
118399           fts3EvalNextRow(pCsr, pLeft, pRc);
118400           pExpr->iDocid = pLeft->iDocid;
118401           pExpr->bEof = pLeft->bEof;
118402         }else{
118403           /* Neither the RHS or LHS are deferred. */
118404           fts3EvalNextRow(pCsr, pLeft, pRc);
118405           fts3EvalNextRow(pCsr, pRight, pRc);
118406           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
118407             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
118408             if( iDiff==0 ) break;
118409             if( iDiff<0 ){
118410               fts3EvalNextRow(pCsr, pLeft, pRc);
118411             }else{
118412               fts3EvalNextRow(pCsr, pRight, pRc);
118413             }
118414           }
118415           pExpr->iDocid = pLeft->iDocid;
118416           pExpr->bEof = (pLeft->bEof || pRight->bEof);
118417         }
118418         break;
118419       }
118420 
118421       case FTSQUERY_OR: {
118422         Fts3Expr *pLeft = pExpr->pLeft;
118423         Fts3Expr *pRight = pExpr->pRight;
118424         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
118425 
118426         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
118427         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
118428 
118429         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
118430           fts3EvalNextRow(pCsr, pLeft, pRc);
118431         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
118432           fts3EvalNextRow(pCsr, pRight, pRc);
118433         }else{
118434           fts3EvalNextRow(pCsr, pLeft, pRc);
118435           fts3EvalNextRow(pCsr, pRight, pRc);
118436         }
118437 
118438         pExpr->bEof = (pLeft->bEof && pRight->bEof);
118439         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
118440         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
118441           pExpr->iDocid = pLeft->iDocid;
118442         }else{
118443           pExpr->iDocid = pRight->iDocid;
118444         }
118445 
118446         break;
118447       }
118448 
118449       case FTSQUERY_NOT: {
118450         Fts3Expr *pLeft = pExpr->pLeft;
118451         Fts3Expr *pRight = pExpr->pRight;
118452 
118453         if( pRight->bStart==0 ){
118454           fts3EvalNextRow(pCsr, pRight, pRc);
118455           assert( *pRc!=SQLITE_OK || pRight->bStart );
118456         }
118457 
118458         fts3EvalNextRow(pCsr, pLeft, pRc);
118459         if( pLeft->bEof==0 ){
118460           while( !*pRc
118461               && !pRight->bEof
118462               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
118463           ){
118464             fts3EvalNextRow(pCsr, pRight, pRc);
118465           }
118466         }
118467         pExpr->iDocid = pLeft->iDocid;
118468         pExpr->bEof = pLeft->bEof;
118469         break;
118470       }
118471 
118472       default: {
118473         Fts3Phrase *pPhrase = pExpr->pPhrase;
118474         fts3EvalInvalidatePoslist(pPhrase);
118475         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
118476         pExpr->iDocid = pPhrase->doclist.iDocid;
118477         break;
118478       }
118479     }
118480   }
118481 }
118482 
118483 /*
118484 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
118485 ** cluster, then this function returns 1 immediately.
118486 **
118487 ** Otherwise, it checks if the current row really does match the NEAR
118488 ** expression, using the data currently stored in the position lists
118489 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
118490 **
118491 ** If the current row is a match, the position list associated with each
118492 ** phrase in the NEAR expression is edited in place to contain only those
118493 ** phrase instances sufficiently close to their peers to satisfy all NEAR
118494 ** constraints. In this case it returns 1. If the NEAR expression does not
118495 ** match the current row, 0 is returned. The position lists may or may not
118496 ** be edited if 0 is returned.
118497 */
118498 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
118499   int res = 1;
118500 
118501   /* The following block runs if pExpr is the root of a NEAR query.
118502   ** For example, the query:
118503   **
118504   **         "w" NEAR "x" NEAR "y" NEAR "z"
118505   **
118506   ** which is represented in tree form as:
118507   **
118508   **                               |
118509   **                          +--NEAR--+      <-- root of NEAR query
118510   **                          |        |
118511   **                     +--NEAR--+   "z"
118512   **                     |        |
118513   **                +--NEAR--+   "y"
118514   **                |        |
118515   **               "w"      "x"
118516   **
118517   ** The right-hand child of a NEAR node is always a phrase. The
118518   ** left-hand child may be either a phrase or a NEAR node. There are
118519   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
118520   */
118521   if( *pRc==SQLITE_OK
118522    && pExpr->eType==FTSQUERY_NEAR
118523    && pExpr->bEof==0
118524    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
118525   ){
118526     Fts3Expr *p;
118527     int nTmp = 0;                 /* Bytes of temp space */
118528     char *aTmp;                   /* Temp space for PoslistNearMerge() */
118529 
118530     /* Allocate temporary working space. */
118531     for(p=pExpr; p->pLeft; p=p->pLeft){
118532       nTmp += p->pRight->pPhrase->doclist.nList;
118533     }
118534     nTmp += p->pPhrase->doclist.nList;
118535     aTmp = sqlite3_malloc(nTmp*2);
118536     if( !aTmp ){
118537       *pRc = SQLITE_NOMEM;
118538       res = 0;
118539     }else{
118540       char *aPoslist = p->pPhrase->doclist.pList;
118541       int nToken = p->pPhrase->nToken;
118542 
118543       for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
118544         Fts3Phrase *pPhrase = p->pRight->pPhrase;
118545         int nNear = p->nNear;
118546         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
118547       }
118548 
118549       aPoslist = pExpr->pRight->pPhrase->doclist.pList;
118550       nToken = pExpr->pRight->pPhrase->nToken;
118551       for(p=pExpr->pLeft; p && res; p=p->pLeft){
118552         int nNear = p->pParent->nNear;
118553         Fts3Phrase *pPhrase = (
118554             p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
118555         );
118556         res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
118557       }
118558     }
118559 
118560     sqlite3_free(aTmp);
118561   }
118562 
118563   return res;
118564 }
118565 
118566 /*
118567 ** This function is a helper function for fts3EvalTestDeferredAndNear().
118568 ** Assuming no error occurs or has occurred, It returns non-zero if the
118569 ** expression passed as the second argument matches the row that pCsr
118570 ** currently points to, or zero if it does not.
118571 **
118572 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
118573 ** If an error occurs during execution of this function, *pRc is set to
118574 ** the appropriate SQLite error code. In this case the returned value is
118575 ** undefined.
118576 */
118577 static int fts3EvalTestExpr(
118578   Fts3Cursor *pCsr,               /* FTS cursor handle */
118579   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
118580   int *pRc                        /* IN/OUT: Error code */
118581 ){
118582   int bHit = 1;                   /* Return value */
118583   if( *pRc==SQLITE_OK ){
118584     switch( pExpr->eType ){
118585       case FTSQUERY_NEAR:
118586       case FTSQUERY_AND:
118587         bHit = (
118588             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
118589          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
118590          && fts3EvalNearTest(pExpr, pRc)
118591         );
118592 
118593         /* If the NEAR expression does not match any rows, zero the doclist for
118594         ** all phrases involved in the NEAR. This is because the snippet(),
118595         ** offsets() and matchinfo() functions are not supposed to recognize
118596         ** any instances of phrases that are part of unmatched NEAR queries.
118597         ** For example if this expression:
118598         **
118599         **    ... MATCH 'a OR (b NEAR c)'
118600         **
118601         ** is matched against a row containing:
118602         **
118603         **        'a b d e'
118604         **
118605         ** then any snippet() should ony highlight the "a" term, not the "b"
118606         ** (as "b" is part of a non-matching NEAR clause).
118607         */
118608         if( bHit==0
118609          && pExpr->eType==FTSQUERY_NEAR
118610          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
118611         ){
118612           Fts3Expr *p;
118613           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
118614             if( p->pRight->iDocid==pCsr->iPrevId ){
118615               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
118616             }
118617           }
118618           if( p->iDocid==pCsr->iPrevId ){
118619             fts3EvalInvalidatePoslist(p->pPhrase);
118620           }
118621         }
118622 
118623         break;
118624 
118625       case FTSQUERY_OR: {
118626         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
118627         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
118628         bHit = bHit1 || bHit2;
118629         break;
118630       }
118631 
118632       case FTSQUERY_NOT:
118633         bHit = (
118634             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
118635          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
118636         );
118637         break;
118638 
118639       default: {
118640         if( pCsr->pDeferred
118641          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
118642         ){
118643           Fts3Phrase *pPhrase = pExpr->pPhrase;
118644           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
118645           if( pExpr->bDeferred ){
118646             fts3EvalInvalidatePoslist(pPhrase);
118647           }
118648           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
118649           bHit = (pPhrase->doclist.pList!=0);
118650           pExpr->iDocid = pCsr->iPrevId;
118651         }else{
118652           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
118653         }
118654         break;
118655       }
118656     }
118657   }
118658   return bHit;
118659 }
118660 
118661 /*
118662 ** This function is called as the second part of each xNext operation when
118663 ** iterating through the results of a full-text query. At this point the
118664 ** cursor points to a row that matches the query expression, with the
118665 ** following caveats:
118666 **
118667 **   * Up until this point, "NEAR" operators in the expression have been
118668 **     treated as "AND".
118669 **
118670 **   * Deferred tokens have not yet been considered.
118671 **
118672 ** If *pRc is not SQLITE_OK when this function is called, it immediately
118673 ** returns 0. Otherwise, it tests whether or not after considering NEAR
118674 ** operators and deferred tokens the current row is still a match for the
118675 ** expression. It returns 1 if both of the following are true:
118676 **
118677 **   1. *pRc is SQLITE_OK when this function returns, and
118678 **
118679 **   2. After scanning the current FTS table row for the deferred tokens,
118680 **      it is determined that the row does *not* match the query.
118681 **
118682 ** Or, if no error occurs and it seems the current row does match the FTS
118683 ** query, return 0.
118684 */
118685 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
118686   int rc = *pRc;
118687   int bMiss = 0;
118688   if( rc==SQLITE_OK ){
118689 
118690     /* If there are one or more deferred tokens, load the current row into
118691     ** memory and scan it to determine the position list for each deferred
118692     ** token. Then, see if this row is really a match, considering deferred
118693     ** tokens and NEAR operators (neither of which were taken into account
118694     ** earlier, by fts3EvalNextRow()).
118695     */
118696     if( pCsr->pDeferred ){
118697       rc = fts3CursorSeek(0, pCsr);
118698       if( rc==SQLITE_OK ){
118699         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
118700       }
118701     }
118702     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
118703 
118704     /* Free the position-lists accumulated for each deferred token above. */
118705     sqlite3Fts3FreeDeferredDoclists(pCsr);
118706     *pRc = rc;
118707   }
118708   return (rc==SQLITE_OK && bMiss);
118709 }
118710 
118711 /*
118712 ** Advance to the next document that matches the FTS expression in
118713 ** Fts3Cursor.pExpr.
118714 */
118715 static int fts3EvalNext(Fts3Cursor *pCsr){
118716   int rc = SQLITE_OK;             /* Return Code */
118717   Fts3Expr *pExpr = pCsr->pExpr;
118718   assert( pCsr->isEof==0 );
118719   if( pExpr==0 ){
118720     pCsr->isEof = 1;
118721   }else{
118722     do {
118723       if( pCsr->isRequireSeek==0 ){
118724         sqlite3_reset(pCsr->pStmt);
118725       }
118726       assert( sqlite3_data_count(pCsr->pStmt)==0 );
118727       fts3EvalNextRow(pCsr, pExpr, &rc);
118728       pCsr->isEof = pExpr->bEof;
118729       pCsr->isRequireSeek = 1;
118730       pCsr->isMatchinfoNeeded = 1;
118731       pCsr->iPrevId = pExpr->iDocid;
118732     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
118733   }
118734   return rc;
118735 }
118736 
118737 /*
118738 ** Restart interation for expression pExpr so that the next call to
118739 ** fts3EvalNext() visits the first row. Do not allow incremental
118740 ** loading or merging of phrase doclists for this iteration.
118741 **
118742 ** If *pRc is other than SQLITE_OK when this function is called, it is
118743 ** a no-op. If an error occurs within this function, *pRc is set to an
118744 ** SQLite error code before returning.
118745 */
118746 static void fts3EvalRestart(
118747   Fts3Cursor *pCsr,
118748   Fts3Expr *pExpr,
118749   int *pRc
118750 ){
118751   if( pExpr && *pRc==SQLITE_OK ){
118752     Fts3Phrase *pPhrase = pExpr->pPhrase;
118753 
118754     if( pPhrase ){
118755       fts3EvalInvalidatePoslist(pPhrase);
118756       if( pPhrase->bIncr ){
118757         assert( pPhrase->nToken==1 );
118758         assert( pPhrase->aToken[0].pSegcsr );
118759         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
118760         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
118761       }
118762 
118763       pPhrase->doclist.pNextDocid = 0;
118764       pPhrase->doclist.iDocid = 0;
118765     }
118766 
118767     pExpr->iDocid = 0;
118768     pExpr->bEof = 0;
118769     pExpr->bStart = 0;
118770 
118771     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
118772     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
118773   }
118774 }
118775 
118776 /*
118777 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
118778 ** expression rooted at pExpr, the cursor iterates through all rows matched
118779 ** by pExpr, calling this function for each row. This function increments
118780 ** the values in Fts3Expr.aMI[] according to the position-list currently
118781 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
118782 ** expression nodes.
118783 */
118784 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
118785   if( pExpr ){
118786     Fts3Phrase *pPhrase = pExpr->pPhrase;
118787     if( pPhrase && pPhrase->doclist.pList ){
118788       int iCol = 0;
118789       char *p = pPhrase->doclist.pList;
118790 
118791       assert( *p );
118792       while( 1 ){
118793         u8 c = 0;
118794         int iCnt = 0;
118795         while( 0xFE & (*p | c) ){
118796           if( (c&0x80)==0 ) iCnt++;
118797           c = *p++ & 0x80;
118798         }
118799 
118800         /* aMI[iCol*3 + 1] = Number of occurrences
118801         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
118802         */
118803         pExpr->aMI[iCol*3 + 1] += iCnt;
118804         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
118805         if( *p==0x00 ) break;
118806         p++;
118807         p += sqlite3Fts3GetVarint32(p, &iCol);
118808       }
118809     }
118810 
118811     fts3EvalUpdateCounts(pExpr->pLeft);
118812     fts3EvalUpdateCounts(pExpr->pRight);
118813   }
118814 }
118815 
118816 /*
118817 ** Expression pExpr must be of type FTSQUERY_PHRASE.
118818 **
118819 ** If it is not already allocated and populated, this function allocates and
118820 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
118821 ** of a NEAR expression, then it also allocates and populates the same array
118822 ** for all other phrases that are part of the NEAR expression.
118823 **
118824 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
118825 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
118826 */
118827 static int fts3EvalGatherStats(
118828   Fts3Cursor *pCsr,               /* Cursor object */
118829   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
118830 ){
118831   int rc = SQLITE_OK;             /* Return code */
118832 
118833   assert( pExpr->eType==FTSQUERY_PHRASE );
118834   if( pExpr->aMI==0 ){
118835     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118836     Fts3Expr *pRoot;                /* Root of NEAR expression */
118837     Fts3Expr *p;                    /* Iterator used for several purposes */
118838 
118839     sqlite3_int64 iPrevId = pCsr->iPrevId;
118840     sqlite3_int64 iDocid;
118841     u8 bEof;
118842 
118843     /* Find the root of the NEAR expression */
118844     pRoot = pExpr;
118845     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
118846       pRoot = pRoot->pParent;
118847     }
118848     iDocid = pRoot->iDocid;
118849     bEof = pRoot->bEof;
118850     assert( pRoot->bStart );
118851 
118852     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
118853     for(p=pRoot; p; p=p->pLeft){
118854       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
118855       assert( pE->aMI==0 );
118856       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
118857       if( !pE->aMI ) return SQLITE_NOMEM;
118858       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
118859     }
118860 
118861     fts3EvalRestart(pCsr, pRoot, &rc);
118862 
118863     while( pCsr->isEof==0 && rc==SQLITE_OK ){
118864 
118865       do {
118866         /* Ensure the %_content statement is reset. */
118867         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
118868         assert( sqlite3_data_count(pCsr->pStmt)==0 );
118869 
118870         /* Advance to the next document */
118871         fts3EvalNextRow(pCsr, pRoot, &rc);
118872         pCsr->isEof = pRoot->bEof;
118873         pCsr->isRequireSeek = 1;
118874         pCsr->isMatchinfoNeeded = 1;
118875         pCsr->iPrevId = pRoot->iDocid;
118876       }while( pCsr->isEof==0
118877            && pRoot->eType==FTSQUERY_NEAR
118878            && fts3EvalTestDeferredAndNear(pCsr, &rc)
118879       );
118880 
118881       if( rc==SQLITE_OK && pCsr->isEof==0 ){
118882         fts3EvalUpdateCounts(pRoot);
118883       }
118884     }
118885 
118886     pCsr->isEof = 0;
118887     pCsr->iPrevId = iPrevId;
118888 
118889     if( bEof ){
118890       pRoot->bEof = bEof;
118891     }else{
118892       /* Caution: pRoot may iterate through docids in ascending or descending
118893       ** order. For this reason, even though it seems more defensive, the
118894       ** do loop can not be written:
118895       **
118896       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
118897       */
118898       fts3EvalRestart(pCsr, pRoot, &rc);
118899       do {
118900         fts3EvalNextRow(pCsr, pRoot, &rc);
118901         assert( pRoot->bEof==0 );
118902       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
118903       fts3EvalTestDeferredAndNear(pCsr, &rc);
118904     }
118905   }
118906   return rc;
118907 }
118908 
118909 /*
118910 ** This function is used by the matchinfo() module to query a phrase
118911 ** expression node for the following information:
118912 **
118913 **   1. The total number of occurrences of the phrase in each column of
118914 **      the FTS table (considering all rows), and
118915 **
118916 **   2. For each column, the number of rows in the table for which the
118917 **      column contains at least one instance of the phrase.
118918 **
118919 ** If no error occurs, SQLITE_OK is returned and the values for each column
118920 ** written into the array aiOut as follows:
118921 **
118922 **   aiOut[iCol*3 + 1] = Number of occurrences
118923 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
118924 **
118925 ** Caveats:
118926 **
118927 **   * If a phrase consists entirely of deferred tokens, then all output
118928 **     values are set to the number of documents in the table. In other
118929 **     words we assume that very common tokens occur exactly once in each
118930 **     column of each row of the table.
118931 **
118932 **   * If a phrase contains some deferred tokens (and some non-deferred
118933 **     tokens), count the potential occurrence identified by considering
118934 **     the non-deferred tokens instead of actual phrase occurrences.
118935 **
118936 **   * If the phrase is part of a NEAR expression, then only phrase instances
118937 **     that meet the NEAR constraint are included in the counts.
118938 */
118939 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
118940   Fts3Cursor *pCsr,               /* FTS cursor handle */
118941   Fts3Expr *pExpr,                /* Phrase expression */
118942   u32 *aiOut                      /* Array to write results into (see above) */
118943 ){
118944   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118945   int rc = SQLITE_OK;
118946   int iCol;
118947 
118948   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
118949     assert( pCsr->nDoc>0 );
118950     for(iCol=0; iCol<pTab->nColumn; iCol++){
118951       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
118952       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
118953     }
118954   }else{
118955     rc = fts3EvalGatherStats(pCsr, pExpr);
118956     if( rc==SQLITE_OK ){
118957       assert( pExpr->aMI );
118958       for(iCol=0; iCol<pTab->nColumn; iCol++){
118959         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
118960         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
118961       }
118962     }
118963   }
118964 
118965   return rc;
118966 }
118967 
118968 /*
118969 ** The expression pExpr passed as the second argument to this function
118970 ** must be of type FTSQUERY_PHRASE.
118971 **
118972 ** The returned value is either NULL or a pointer to a buffer containing
118973 ** a position-list indicating the occurrences of the phrase in column iCol
118974 ** of the current row.
118975 **
118976 ** More specifically, the returned buffer contains 1 varint for each
118977 ** occurence of the phrase in the column, stored using the normal (delta+2)
118978 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
118979 ** if the requested column contains "a b X c d X X" and the position-list
118980 ** for 'X' is requested, the buffer returned may contain:
118981 **
118982 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
118983 **
118984 ** This function works regardless of whether or not the phrase is deferred,
118985 ** incremental, or neither.
118986 */
118987 SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
118988   Fts3Cursor *pCsr,               /* FTS3 cursor object */
118989   Fts3Expr *pExpr,                /* Phrase to return doclist for */
118990   int iCol                        /* Column to return position list for */
118991 ){
118992   Fts3Phrase *pPhrase = pExpr->pPhrase;
118993   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
118994   char *pIter = pPhrase->doclist.pList;
118995   int iThis;
118996 
118997   assert( iCol>=0 && iCol<pTab->nColumn );
118998   if( !pIter
118999    || pExpr->bEof
119000    || pExpr->iDocid!=pCsr->iPrevId
119001    || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
119002   ){
119003     return 0;
119004   }
119005 
119006   assert( pPhrase->doclist.nList>0 );
119007   if( *pIter==0x01 ){
119008     pIter++;
119009     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
119010   }else{
119011     iThis = 0;
119012   }
119013   while( iThis<iCol ){
119014     fts3ColumnlistCopy(0, &pIter);
119015     if( *pIter==0x00 ) return 0;
119016     pIter++;
119017     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
119018   }
119019 
119020   return ((iCol==iThis)?pIter:0);
119021 }
119022 
119023 /*
119024 ** Free all components of the Fts3Phrase structure that were allocated by
119025 ** the eval module. Specifically, this means to free:
119026 **
119027 **   * the contents of pPhrase->doclist, and
119028 **   * any Fts3MultiSegReader objects held by phrase tokens.
119029 */
119030 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
119031   if( pPhrase ){
119032     int i;
119033     sqlite3_free(pPhrase->doclist.aAll);
119034     fts3EvalInvalidatePoslist(pPhrase);
119035     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
119036     for(i=0; i<pPhrase->nToken; i++){
119037       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
119038       pPhrase->aToken[i].pSegcsr = 0;
119039     }
119040   }
119041 }
119042 
119043 #if !SQLITE_CORE
119044 /*
119045 ** Initialize API pointer table, if required.
119046 */
119047 SQLITE_API int sqlite3_extension_init(
119048   sqlite3 *db,
119049   char **pzErrMsg,
119050   const sqlite3_api_routines *pApi
119051 ){
119052   SQLITE_EXTENSION_INIT2(pApi)
119053   return sqlite3Fts3Init(db);
119054 }
119055 #endif
119056 
119057 #endif
119058 
119059 /************** End of fts3.c ************************************************/
119060 /************** Begin file fts3_aux.c ****************************************/
119061 /*
119062 ** 2011 Jan 27
119063 **
119064 ** The author disclaims copyright to this source code.  In place of
119065 ** a legal notice, here is a blessing:
119066 **
119067 **    May you do good and not evil.
119068 **    May you find forgiveness for yourself and forgive others.
119069 **    May you share freely, never taking more than you give.
119070 **
119071 ******************************************************************************
119072 **
119073 */
119074 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119075 
119076 /* #include <string.h> */
119077 /* #include <assert.h> */
119078 
119079 typedef struct Fts3auxTable Fts3auxTable;
119080 typedef struct Fts3auxCursor Fts3auxCursor;
119081 
119082 struct Fts3auxTable {
119083   sqlite3_vtab base;              /* Base class used by SQLite core */
119084   Fts3Table *pFts3Tab;
119085 };
119086 
119087 struct Fts3auxCursor {
119088   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
119089   Fts3MultiSegReader csr;        /* Must be right after "base" */
119090   Fts3SegFilter filter;
119091   char *zStop;
119092   int nStop;                      /* Byte-length of string zStop */
119093   int isEof;                      /* True if cursor is at EOF */
119094   sqlite3_int64 iRowid;           /* Current rowid */
119095 
119096   int iCol;                       /* Current value of 'col' column */
119097   int nStat;                      /* Size of aStat[] array */
119098   struct Fts3auxColstats {
119099     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
119100     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
119101   } *aStat;
119102 };
119103 
119104 /*
119105 ** Schema of the terms table.
119106 */
119107 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
119108 
119109 /*
119110 ** This function does all the work for both the xConnect and xCreate methods.
119111 ** These tables have no persistent representation of their own, so xConnect
119112 ** and xCreate are identical operations.
119113 */
119114 static int fts3auxConnectMethod(
119115   sqlite3 *db,                    /* Database connection */
119116   void *pUnused,                  /* Unused */
119117   int argc,                       /* Number of elements in argv array */
119118   const char * const *argv,       /* xCreate/xConnect argument array */
119119   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
119120   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
119121 ){
119122   char const *zDb;                /* Name of database (e.g. "main") */
119123   char const *zFts3;              /* Name of fts3 table */
119124   int nDb;                        /* Result of strlen(zDb) */
119125   int nFts3;                      /* Result of strlen(zFts3) */
119126   int nByte;                      /* Bytes of space to allocate here */
119127   int rc;                         /* value returned by declare_vtab() */
119128   Fts3auxTable *p;                /* Virtual table object to return */
119129 
119130   UNUSED_PARAMETER(pUnused);
119131 
119132   /* The user should specify a single argument - the name of an fts3 table. */
119133   if( argc!=4 ){
119134     *pzErr = sqlite3_mprintf(
119135         "wrong number of arguments to fts4aux constructor"
119136     );
119137     return SQLITE_ERROR;
119138   }
119139 
119140   zDb = argv[1];
119141   nDb = strlen(zDb);
119142   zFts3 = argv[3];
119143   nFts3 = strlen(zFts3);
119144 
119145   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
119146   if( rc!=SQLITE_OK ) return rc;
119147 
119148   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
119149   p = (Fts3auxTable *)sqlite3_malloc(nByte);
119150   if( !p ) return SQLITE_NOMEM;
119151   memset(p, 0, nByte);
119152 
119153   p->pFts3Tab = (Fts3Table *)&p[1];
119154   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
119155   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
119156   p->pFts3Tab->db = db;
119157   p->pFts3Tab->nIndex = 1;
119158 
119159   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
119160   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
119161   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
119162 
119163   *ppVtab = (sqlite3_vtab *)p;
119164   return SQLITE_OK;
119165 }
119166 
119167 /*
119168 ** This function does the work for both the xDisconnect and xDestroy methods.
119169 ** These tables have no persistent representation of their own, so xDisconnect
119170 ** and xDestroy are identical operations.
119171 */
119172 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
119173   Fts3auxTable *p = (Fts3auxTable *)pVtab;
119174   Fts3Table *pFts3 = p->pFts3Tab;
119175   int i;
119176 
119177   /* Free any prepared statements held */
119178   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
119179     sqlite3_finalize(pFts3->aStmt[i]);
119180   }
119181   sqlite3_free(pFts3->zSegmentsTbl);
119182   sqlite3_free(p);
119183   return SQLITE_OK;
119184 }
119185 
119186 #define FTS4AUX_EQ_CONSTRAINT 1
119187 #define FTS4AUX_GE_CONSTRAINT 2
119188 #define FTS4AUX_LE_CONSTRAINT 4
119189 
119190 /*
119191 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
119192 */
119193 static int fts3auxBestIndexMethod(
119194   sqlite3_vtab *pVTab,
119195   sqlite3_index_info *pInfo
119196 ){
119197   int i;
119198   int iEq = -1;
119199   int iGe = -1;
119200   int iLe = -1;
119201 
119202   UNUSED_PARAMETER(pVTab);
119203 
119204   /* This vtab delivers always results in "ORDER BY term ASC" order. */
119205   if( pInfo->nOrderBy==1
119206    && pInfo->aOrderBy[0].iColumn==0
119207    && pInfo->aOrderBy[0].desc==0
119208   ){
119209     pInfo->orderByConsumed = 1;
119210   }
119211 
119212   /* Search for equality and range constraints on the "term" column. */
119213   for(i=0; i<pInfo->nConstraint; i++){
119214     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
119215       int op = pInfo->aConstraint[i].op;
119216       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
119217       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
119218       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
119219       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
119220       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
119221     }
119222   }
119223 
119224   if( iEq>=0 ){
119225     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
119226     pInfo->aConstraintUsage[iEq].argvIndex = 1;
119227     pInfo->estimatedCost = 5;
119228   }else{
119229     pInfo->idxNum = 0;
119230     pInfo->estimatedCost = 20000;
119231     if( iGe>=0 ){
119232       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
119233       pInfo->aConstraintUsage[iGe].argvIndex = 1;
119234       pInfo->estimatedCost /= 2;
119235     }
119236     if( iLe>=0 ){
119237       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
119238       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
119239       pInfo->estimatedCost /= 2;
119240     }
119241   }
119242 
119243   return SQLITE_OK;
119244 }
119245 
119246 /*
119247 ** xOpen - Open a cursor.
119248 */
119249 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
119250   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
119251 
119252   UNUSED_PARAMETER(pVTab);
119253 
119254   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
119255   if( !pCsr ) return SQLITE_NOMEM;
119256   memset(pCsr, 0, sizeof(Fts3auxCursor));
119257 
119258   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
119259   return SQLITE_OK;
119260 }
119261 
119262 /*
119263 ** xClose - Close a cursor.
119264 */
119265 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
119266   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
119267   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119268 
119269   sqlite3Fts3SegmentsClose(pFts3);
119270   sqlite3Fts3SegReaderFinish(&pCsr->csr);
119271   sqlite3_free((void *)pCsr->filter.zTerm);
119272   sqlite3_free(pCsr->zStop);
119273   sqlite3_free(pCsr->aStat);
119274   sqlite3_free(pCsr);
119275   return SQLITE_OK;
119276 }
119277 
119278 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
119279   if( nSize>pCsr->nStat ){
119280     struct Fts3auxColstats *aNew;
119281     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
119282         sizeof(struct Fts3auxColstats) * nSize
119283     );
119284     if( aNew==0 ) return SQLITE_NOMEM;
119285     memset(&aNew[pCsr->nStat], 0,
119286         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
119287     );
119288     pCsr->aStat = aNew;
119289     pCsr->nStat = nSize;
119290   }
119291   return SQLITE_OK;
119292 }
119293 
119294 /*
119295 ** xNext - Advance the cursor to the next row, if any.
119296 */
119297 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
119298   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119299   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
119300   int rc;
119301 
119302   /* Increment our pretend rowid value. */
119303   pCsr->iRowid++;
119304 
119305   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
119306     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
119307   }
119308 
119309   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
119310   if( rc==SQLITE_ROW ){
119311     int i = 0;
119312     int nDoclist = pCsr->csr.nDoclist;
119313     char *aDoclist = pCsr->csr.aDoclist;
119314     int iCol;
119315 
119316     int eState = 0;
119317 
119318     if( pCsr->zStop ){
119319       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
119320       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
119321       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
119322         pCsr->isEof = 1;
119323         return SQLITE_OK;
119324       }
119325     }
119326 
119327     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
119328     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
119329     iCol = 0;
119330 
119331     while( i<nDoclist ){
119332       sqlite3_int64 v = 0;
119333 
119334       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
119335       switch( eState ){
119336         /* State 0. In this state the integer just read was a docid. */
119337         case 0:
119338           pCsr->aStat[0].nDoc++;
119339           eState = 1;
119340           iCol = 0;
119341           break;
119342 
119343         /* State 1. In this state we are expecting either a 1, indicating
119344         ** that the following integer will be a column number, or the
119345         ** start of a position list for column 0.
119346         **
119347         ** The only difference between state 1 and state 2 is that if the
119348         ** integer encountered in state 1 is not 0 or 1, then we need to
119349         ** increment the column 0 "nDoc" count for this term.
119350         */
119351         case 1:
119352           assert( iCol==0 );
119353           if( v>1 ){
119354             pCsr->aStat[1].nDoc++;
119355           }
119356           eState = 2;
119357           /* fall through */
119358 
119359         case 2:
119360           if( v==0 ){       /* 0x00. Next integer will be a docid. */
119361             eState = 0;
119362           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
119363             eState = 3;
119364           }else{            /* 2 or greater. A position. */
119365             pCsr->aStat[iCol+1].nOcc++;
119366             pCsr->aStat[0].nOcc++;
119367           }
119368           break;
119369 
119370         /* State 3. The integer just read is a column number. */
119371         default: assert( eState==3 );
119372           iCol = (int)v;
119373           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
119374           pCsr->aStat[iCol+1].nDoc++;
119375           eState = 2;
119376           break;
119377       }
119378     }
119379 
119380     pCsr->iCol = 0;
119381     rc = SQLITE_OK;
119382   }else{
119383     pCsr->isEof = 1;
119384   }
119385   return rc;
119386 }
119387 
119388 /*
119389 ** xFilter - Initialize a cursor to point at the start of its data.
119390 */
119391 static int fts3auxFilterMethod(
119392   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
119393   int idxNum,                     /* Strategy index */
119394   const char *idxStr,             /* Unused */
119395   int nVal,                       /* Number of elements in apVal */
119396   sqlite3_value **apVal           /* Arguments for the indexing scheme */
119397 ){
119398   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119399   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
119400   int rc;
119401   int isScan;
119402 
119403   UNUSED_PARAMETER(nVal);
119404   UNUSED_PARAMETER(idxStr);
119405 
119406   assert( idxStr==0 );
119407   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
119408        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
119409        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
119410   );
119411   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
119412 
119413   /* In case this cursor is being reused, close and zero it. */
119414   testcase(pCsr->filter.zTerm);
119415   sqlite3Fts3SegReaderFinish(&pCsr->csr);
119416   sqlite3_free((void *)pCsr->filter.zTerm);
119417   sqlite3_free(pCsr->aStat);
119418   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
119419 
119420   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
119421   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
119422 
119423   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
119424     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
119425     if( zStr ){
119426       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
119427       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
119428       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
119429     }
119430   }
119431   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
119432     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
119433     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
119434     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
119435     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
119436   }
119437 
119438   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, FTS3_SEGCURSOR_ALL,
119439       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
119440   );
119441   if( rc==SQLITE_OK ){
119442     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
119443   }
119444 
119445   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
119446   return rc;
119447 }
119448 
119449 /*
119450 ** xEof - Return true if the cursor is at EOF, or false otherwise.
119451 */
119452 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
119453   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119454   return pCsr->isEof;
119455 }
119456 
119457 /*
119458 ** xColumn - Return a column value.
119459 */
119460 static int fts3auxColumnMethod(
119461   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119462   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
119463   int iCol                        /* Index of column to read value from */
119464 ){
119465   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
119466 
119467   assert( p->isEof==0 );
119468   if( iCol==0 ){        /* Column "term" */
119469     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
119470   }else if( iCol==1 ){  /* Column "col" */
119471     if( p->iCol ){
119472       sqlite3_result_int(pContext, p->iCol-1);
119473     }else{
119474       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
119475     }
119476   }else if( iCol==2 ){  /* Column "documents" */
119477     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
119478   }else{                /* Column "occurrences" */
119479     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
119480   }
119481 
119482   return SQLITE_OK;
119483 }
119484 
119485 /*
119486 ** xRowid - Return the current rowid for the cursor.
119487 */
119488 static int fts3auxRowidMethod(
119489   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119490   sqlite_int64 *pRowid            /* OUT: Rowid value */
119491 ){
119492   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
119493   *pRowid = pCsr->iRowid;
119494   return SQLITE_OK;
119495 }
119496 
119497 /*
119498 ** Register the fts3aux module with database connection db. Return SQLITE_OK
119499 ** if successful or an error code if sqlite3_create_module() fails.
119500 */
119501 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
119502   static const sqlite3_module fts3aux_module = {
119503      0,                           /* iVersion      */
119504      fts3auxConnectMethod,        /* xCreate       */
119505      fts3auxConnectMethod,        /* xConnect      */
119506      fts3auxBestIndexMethod,      /* xBestIndex    */
119507      fts3auxDisconnectMethod,     /* xDisconnect   */
119508      fts3auxDisconnectMethod,     /* xDestroy      */
119509      fts3auxOpenMethod,           /* xOpen         */
119510      fts3auxCloseMethod,          /* xClose        */
119511      fts3auxFilterMethod,         /* xFilter       */
119512      fts3auxNextMethod,           /* xNext         */
119513      fts3auxEofMethod,            /* xEof          */
119514      fts3auxColumnMethod,         /* xColumn       */
119515      fts3auxRowidMethod,          /* xRowid        */
119516      0,                           /* xUpdate       */
119517      0,                           /* xBegin        */
119518      0,                           /* xSync         */
119519      0,                           /* xCommit       */
119520      0,                           /* xRollback     */
119521      0,                           /* xFindFunction */
119522      0,                           /* xRename       */
119523      0,                           /* xSavepoint    */
119524      0,                           /* xRelease      */
119525      0                            /* xRollbackTo   */
119526   };
119527   int rc;                         /* Return code */
119528 
119529   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
119530   return rc;
119531 }
119532 
119533 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
119534 
119535 /************** End of fts3_aux.c ********************************************/
119536 /************** Begin file fts3_expr.c ***************************************/
119537 /*
119538 ** 2008 Nov 28
119539 **
119540 ** The author disclaims copyright to this source code.  In place of
119541 ** a legal notice, here is a blessing:
119542 **
119543 **    May you do good and not evil.
119544 **    May you find forgiveness for yourself and forgive others.
119545 **    May you share freely, never taking more than you give.
119546 **
119547 ******************************************************************************
119548 **
119549 ** This module contains code that implements a parser for fts3 query strings
119550 ** (the right-hand argument to the MATCH operator). Because the supported
119551 ** syntax is relatively simple, the whole tokenizer/parser system is
119552 ** hand-coded.
119553 */
119554 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119555 
119556 /*
119557 ** By default, this module parses the legacy syntax that has been
119558 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
119559 ** is defined, then it uses the new syntax. The differences between
119560 ** the new and the old syntaxes are:
119561 **
119562 **  a) The new syntax supports parenthesis. The old does not.
119563 **
119564 **  b) The new syntax supports the AND and NOT operators. The old does not.
119565 **
119566 **  c) The old syntax supports the "-" token qualifier. This is not
119567 **     supported by the new syntax (it is replaced by the NOT operator).
119568 **
119569 **  d) When using the old syntax, the OR operator has a greater precedence
119570 **     than an implicit AND. When using the new, both implicity and explicit
119571 **     AND operators have a higher precedence than OR.
119572 **
119573 ** If compiled with SQLITE_TEST defined, then this module exports the
119574 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
119575 ** to zero causes the module to use the old syntax. If it is set to
119576 ** non-zero the new syntax is activated. This is so both syntaxes can
119577 ** be tested using a single build of testfixture.
119578 **
119579 ** The following describes the syntax supported by the fts3 MATCH
119580 ** operator in a similar format to that used by the lemon parser
119581 ** generator. This module does not use actually lemon, it uses a
119582 ** custom parser.
119583 **
119584 **   query ::= andexpr (OR andexpr)*.
119585 **
119586 **   andexpr ::= notexpr (AND? notexpr)*.
119587 **
119588 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
119589 **   notexpr ::= LP query RP.
119590 **
119591 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
119592 **
119593 **   distance_opt ::= .
119594 **   distance_opt ::= / INTEGER.
119595 **
119596 **   phrase ::= TOKEN.
119597 **   phrase ::= COLUMN:TOKEN.
119598 **   phrase ::= "TOKEN TOKEN TOKEN...".
119599 */
119600 
119601 #ifdef SQLITE_TEST
119602 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
119603 #else
119604 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
119605 #  define sqlite3_fts3_enable_parentheses 1
119606 # else
119607 #  define sqlite3_fts3_enable_parentheses 0
119608 # endif
119609 #endif
119610 
119611 /*
119612 ** Default span for NEAR operators.
119613 */
119614 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
119615 
119616 /* #include <string.h> */
119617 /* #include <assert.h> */
119618 
119619 /*
119620 ** isNot:
119621 **   This variable is used by function getNextNode(). When getNextNode() is
119622 **   called, it sets ParseContext.isNot to true if the 'next node' is a
119623 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
119624 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
119625 **   zero.
119626 */
119627 typedef struct ParseContext ParseContext;
119628 struct ParseContext {
119629   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
119630   const char **azCol;                 /* Array of column names for fts3 table */
119631   int nCol;                           /* Number of entries in azCol[] */
119632   int iDefaultCol;                    /* Default column to query */
119633   int isNot;                          /* True if getNextNode() sees a unary - */
119634   sqlite3_context *pCtx;              /* Write error message here */
119635   int nNest;                          /* Number of nested brackets */
119636 };
119637 
119638 /*
119639 ** This function is equivalent to the standard isspace() function.
119640 **
119641 ** The standard isspace() can be awkward to use safely, because although it
119642 ** is defined to accept an argument of type int, its behaviour when passed
119643 ** an integer that falls outside of the range of the unsigned char type
119644 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
119645 ** is defined to accept an argument of type char, and always returns 0 for
119646 ** any values that fall outside of the range of the unsigned char type (i.e.
119647 ** negative values).
119648 */
119649 static int fts3isspace(char c){
119650   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
119651 }
119652 
119653 /*
119654 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
119655 ** zero the memory before returning a pointer to it. If unsuccessful,
119656 ** return NULL.
119657 */
119658 static void *fts3MallocZero(int nByte){
119659   void *pRet = sqlite3_malloc(nByte);
119660   if( pRet ) memset(pRet, 0, nByte);
119661   return pRet;
119662 }
119663 
119664 
119665 /*
119666 ** Extract the next token from buffer z (length n) using the tokenizer
119667 ** and other information (column names etc.) in pParse. Create an Fts3Expr
119668 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
119669 ** single token and set *ppExpr to point to it. If the end of the buffer is
119670 ** reached before a token is found, set *ppExpr to zero. It is the
119671 ** responsibility of the caller to eventually deallocate the allocated
119672 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
119673 **
119674 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
119675 ** fails.
119676 */
119677 static int getNextToken(
119678   ParseContext *pParse,                   /* fts3 query parse context */
119679   int iCol,                               /* Value for Fts3Phrase.iColumn */
119680   const char *z, int n,                   /* Input string */
119681   Fts3Expr **ppExpr,                      /* OUT: expression */
119682   int *pnConsumed                         /* OUT: Number of bytes consumed */
119683 ){
119684   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
119685   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
119686   int rc;
119687   sqlite3_tokenizer_cursor *pCursor;
119688   Fts3Expr *pRet = 0;
119689   int nConsumed = 0;
119690 
119691   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
119692   if( rc==SQLITE_OK ){
119693     const char *zToken;
119694     int nToken, iStart, iEnd, iPosition;
119695     int nByte;                               /* total space to allocate */
119696 
119697     pCursor->pTokenizer = pTokenizer;
119698     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
119699 
119700     if( rc==SQLITE_OK ){
119701       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
119702       pRet = (Fts3Expr *)fts3MallocZero(nByte);
119703       if( !pRet ){
119704         rc = SQLITE_NOMEM;
119705       }else{
119706         pRet->eType = FTSQUERY_PHRASE;
119707         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
119708         pRet->pPhrase->nToken = 1;
119709         pRet->pPhrase->iColumn = iCol;
119710         pRet->pPhrase->aToken[0].n = nToken;
119711         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
119712         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
119713 
119714         if( iEnd<n && z[iEnd]=='*' ){
119715           pRet->pPhrase->aToken[0].isPrefix = 1;
119716           iEnd++;
119717         }
119718         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
119719           pParse->isNot = 1;
119720         }
119721       }
119722       nConsumed = iEnd;
119723     }
119724 
119725     pModule->xClose(pCursor);
119726   }
119727 
119728   *pnConsumed = nConsumed;
119729   *ppExpr = pRet;
119730   return rc;
119731 }
119732 
119733 
119734 /*
119735 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
119736 ** then free the old allocation.
119737 */
119738 static void *fts3ReallocOrFree(void *pOrig, int nNew){
119739   void *pRet = sqlite3_realloc(pOrig, nNew);
119740   if( !pRet ){
119741     sqlite3_free(pOrig);
119742   }
119743   return pRet;
119744 }
119745 
119746 /*
119747 ** Buffer zInput, length nInput, contains the contents of a quoted string
119748 ** that appeared as part of an fts3 query expression. Neither quote character
119749 ** is included in the buffer. This function attempts to tokenize the entire
119750 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
119751 ** containing the results.
119752 **
119753 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
119754 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
119755 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
119756 ** to 0.
119757 */
119758 static int getNextString(
119759   ParseContext *pParse,                   /* fts3 query parse context */
119760   const char *zInput, int nInput,         /* Input string */
119761   Fts3Expr **ppExpr                       /* OUT: expression */
119762 ){
119763   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
119764   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
119765   int rc;
119766   Fts3Expr *p = 0;
119767   sqlite3_tokenizer_cursor *pCursor = 0;
119768   char *zTemp = 0;
119769   int nTemp = 0;
119770 
119771   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
119772   int nToken = 0;
119773 
119774   /* The final Fts3Expr data structure, including the Fts3Phrase,
119775   ** Fts3PhraseToken structures token buffers are all stored as a single
119776   ** allocation so that the expression can be freed with a single call to
119777   ** sqlite3_free(). Setting this up requires a two pass approach.
119778   **
119779   ** The first pass, in the block below, uses a tokenizer cursor to iterate
119780   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
119781   ** to assemble data in two dynamic buffers:
119782   **
119783   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
119784   **             structure, followed by the array of Fts3PhraseToken
119785   **             structures. This pass only populates the Fts3PhraseToken array.
119786   **
119787   **   Buffer zTemp: Contains copies of all tokens.
119788   **
119789   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
119790   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
119791   ** structures.
119792   */
119793   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
119794   if( rc==SQLITE_OK ){
119795     int ii;
119796     pCursor->pTokenizer = pTokenizer;
119797     for(ii=0; rc==SQLITE_OK; ii++){
119798       const char *zByte;
119799       int nByte, iBegin, iEnd, iPos;
119800       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
119801       if( rc==SQLITE_OK ){
119802         Fts3PhraseToken *pToken;
119803 
119804         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
119805         if( !p ) goto no_mem;
119806 
119807         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
119808         if( !zTemp ) goto no_mem;
119809 
119810         assert( nToken==ii );
119811         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
119812         memset(pToken, 0, sizeof(Fts3PhraseToken));
119813 
119814         memcpy(&zTemp[nTemp], zByte, nByte);
119815         nTemp += nByte;
119816 
119817         pToken->n = nByte;
119818         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
119819         nToken = ii+1;
119820       }
119821     }
119822 
119823     pModule->xClose(pCursor);
119824     pCursor = 0;
119825   }
119826 
119827   if( rc==SQLITE_DONE ){
119828     int jj;
119829     char *zBuf = 0;
119830 
119831     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
119832     if( !p ) goto no_mem;
119833     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
119834     p->eType = FTSQUERY_PHRASE;
119835     p->pPhrase = (Fts3Phrase *)&p[1];
119836     p->pPhrase->iColumn = pParse->iDefaultCol;
119837     p->pPhrase->nToken = nToken;
119838 
119839     zBuf = (char *)&p->pPhrase->aToken[nToken];
119840     memcpy(zBuf, zTemp, nTemp);
119841     sqlite3_free(zTemp);
119842 
119843     for(jj=0; jj<p->pPhrase->nToken; jj++){
119844       p->pPhrase->aToken[jj].z = zBuf;
119845       zBuf += p->pPhrase->aToken[jj].n;
119846     }
119847     rc = SQLITE_OK;
119848   }
119849 
119850   *ppExpr = p;
119851   return rc;
119852 no_mem:
119853 
119854   if( pCursor ){
119855     pModule->xClose(pCursor);
119856   }
119857   sqlite3_free(zTemp);
119858   sqlite3_free(p);
119859   *ppExpr = 0;
119860   return SQLITE_NOMEM;
119861 }
119862 
119863 /*
119864 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
119865 ** call fts3ExprParse(). So this forward declaration is required.
119866 */
119867 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
119868 
119869 /*
119870 ** The output variable *ppExpr is populated with an allocated Fts3Expr
119871 ** structure, or set to 0 if the end of the input buffer is reached.
119872 **
119873 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
119874 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
119875 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
119876 */
119877 static int getNextNode(
119878   ParseContext *pParse,                   /* fts3 query parse context */
119879   const char *z, int n,                   /* Input string */
119880   Fts3Expr **ppExpr,                      /* OUT: expression */
119881   int *pnConsumed                         /* OUT: Number of bytes consumed */
119882 ){
119883   static const struct Fts3Keyword {
119884     char *z;                              /* Keyword text */
119885     unsigned char n;                      /* Length of the keyword */
119886     unsigned char parenOnly;              /* Only valid in paren mode */
119887     unsigned char eType;                  /* Keyword code */
119888   } aKeyword[] = {
119889     { "OR" ,  2, 0, FTSQUERY_OR   },
119890     { "AND",  3, 1, FTSQUERY_AND  },
119891     { "NOT",  3, 1, FTSQUERY_NOT  },
119892     { "NEAR", 4, 0, FTSQUERY_NEAR }
119893   };
119894   int ii;
119895   int iCol;
119896   int iColLen;
119897   int rc;
119898   Fts3Expr *pRet = 0;
119899 
119900   const char *zInput = z;
119901   int nInput = n;
119902 
119903   pParse->isNot = 0;
119904 
119905   /* Skip over any whitespace before checking for a keyword, an open or
119906   ** close bracket, or a quoted string.
119907   */
119908   while( nInput>0 && fts3isspace(*zInput) ){
119909     nInput--;
119910     zInput++;
119911   }
119912   if( nInput==0 ){
119913     return SQLITE_DONE;
119914   }
119915 
119916   /* See if we are dealing with a keyword. */
119917   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
119918     const struct Fts3Keyword *pKey = &aKeyword[ii];
119919 
119920     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
119921       continue;
119922     }
119923 
119924     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
119925       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
119926       int nKey = pKey->n;
119927       char cNext;
119928 
119929       /* If this is a "NEAR" keyword, check for an explicit nearness. */
119930       if( pKey->eType==FTSQUERY_NEAR ){
119931         assert( nKey==4 );
119932         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
119933           nNear = 0;
119934           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
119935             nNear = nNear * 10 + (zInput[nKey] - '0');
119936           }
119937         }
119938       }
119939 
119940       /* At this point this is probably a keyword. But for that to be true,
119941       ** the next byte must contain either whitespace, an open or close
119942       ** parenthesis, a quote character, or EOF.
119943       */
119944       cNext = zInput[nKey];
119945       if( fts3isspace(cNext)
119946        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
119947       ){
119948         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
119949         if( !pRet ){
119950           return SQLITE_NOMEM;
119951         }
119952         pRet->eType = pKey->eType;
119953         pRet->nNear = nNear;
119954         *ppExpr = pRet;
119955         *pnConsumed = (int)((zInput - z) + nKey);
119956         return SQLITE_OK;
119957       }
119958 
119959       /* Turns out that wasn't a keyword after all. This happens if the
119960       ** user has supplied a token such as "ORacle". Continue.
119961       */
119962     }
119963   }
119964 
119965   /* Check for an open bracket. */
119966   if( sqlite3_fts3_enable_parentheses ){
119967     if( *zInput=='(' ){
119968       int nConsumed;
119969       pParse->nNest++;
119970       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
119971       if( rc==SQLITE_OK && !*ppExpr ){
119972         rc = SQLITE_DONE;
119973       }
119974       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
119975       return rc;
119976     }
119977 
119978     /* Check for a close bracket. */
119979     if( *zInput==')' ){
119980       pParse->nNest--;
119981       *pnConsumed = (int)((zInput - z) + 1);
119982       return SQLITE_DONE;
119983     }
119984   }
119985 
119986   /* See if we are dealing with a quoted phrase. If this is the case, then
119987   ** search for the closing quote and pass the whole string to getNextString()
119988   ** for processing. This is easy to do, as fts3 has no syntax for escaping
119989   ** a quote character embedded in a string.
119990   */
119991   if( *zInput=='"' ){
119992     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
119993     *pnConsumed = (int)((zInput - z) + ii + 1);
119994     if( ii==nInput ){
119995       return SQLITE_ERROR;
119996     }
119997     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
119998   }
119999 
120000 
120001   /* If control flows to this point, this must be a regular token, or
120002   ** the end of the input. Read a regular token using the sqlite3_tokenizer
120003   ** interface. Before doing so, figure out if there is an explicit
120004   ** column specifier for the token.
120005   **
120006   ** TODO: Strangely, it is not possible to associate a column specifier
120007   ** with a quoted phrase, only with a single token. Not sure if this was
120008   ** an implementation artifact or an intentional decision when fts3 was
120009   ** first implemented. Whichever it was, this module duplicates the
120010   ** limitation.
120011   */
120012   iCol = pParse->iDefaultCol;
120013   iColLen = 0;
120014   for(ii=0; ii<pParse->nCol; ii++){
120015     const char *zStr = pParse->azCol[ii];
120016     int nStr = (int)strlen(zStr);
120017     if( nInput>nStr && zInput[nStr]==':'
120018      && sqlite3_strnicmp(zStr, zInput, nStr)==0
120019     ){
120020       iCol = ii;
120021       iColLen = (int)((zInput - z) + nStr + 1);
120022       break;
120023     }
120024   }
120025   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
120026   *pnConsumed += iColLen;
120027   return rc;
120028 }
120029 
120030 /*
120031 ** The argument is an Fts3Expr structure for a binary operator (any type
120032 ** except an FTSQUERY_PHRASE). Return an integer value representing the
120033 ** precedence of the operator. Lower values have a higher precedence (i.e.
120034 ** group more tightly). For example, in the C language, the == operator
120035 ** groups more tightly than ||, and would therefore have a higher precedence.
120036 **
120037 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
120038 ** is defined), the order of the operators in precedence from highest to
120039 ** lowest is:
120040 **
120041 **   NEAR
120042 **   NOT
120043 **   AND (including implicit ANDs)
120044 **   OR
120045 **
120046 ** Note that when using the old query syntax, the OR operator has a higher
120047 ** precedence than the AND operator.
120048 */
120049 static int opPrecedence(Fts3Expr *p){
120050   assert( p->eType!=FTSQUERY_PHRASE );
120051   if( sqlite3_fts3_enable_parentheses ){
120052     return p->eType;
120053   }else if( p->eType==FTSQUERY_NEAR ){
120054     return 1;
120055   }else if( p->eType==FTSQUERY_OR ){
120056     return 2;
120057   }
120058   assert( p->eType==FTSQUERY_AND );
120059   return 3;
120060 }
120061 
120062 /*
120063 ** Argument ppHead contains a pointer to the current head of a query
120064 ** expression tree being parsed. pPrev is the expression node most recently
120065 ** inserted into the tree. This function adds pNew, which is always a binary
120066 ** operator node, into the expression tree based on the relative precedence
120067 ** of pNew and the existing nodes of the tree. This may result in the head
120068 ** of the tree changing, in which case *ppHead is set to the new root node.
120069 */
120070 static void insertBinaryOperator(
120071   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
120072   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
120073   Fts3Expr *pNew           /* New binary node to insert into expression tree */
120074 ){
120075   Fts3Expr *pSplit = pPrev;
120076   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
120077     pSplit = pSplit->pParent;
120078   }
120079 
120080   if( pSplit->pParent ){
120081     assert( pSplit->pParent->pRight==pSplit );
120082     pSplit->pParent->pRight = pNew;
120083     pNew->pParent = pSplit->pParent;
120084   }else{
120085     *ppHead = pNew;
120086   }
120087   pNew->pLeft = pSplit;
120088   pSplit->pParent = pNew;
120089 }
120090 
120091 /*
120092 ** Parse the fts3 query expression found in buffer z, length n. This function
120093 ** returns either when the end of the buffer is reached or an unmatched
120094 ** closing bracket - ')' - is encountered.
120095 **
120096 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
120097 ** parsed form of the expression and *pnConsumed is set to the number of
120098 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
120099 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
120100 */
120101 static int fts3ExprParse(
120102   ParseContext *pParse,                   /* fts3 query parse context */
120103   const char *z, int n,                   /* Text of MATCH query */
120104   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
120105   int *pnConsumed                         /* OUT: Number of bytes consumed */
120106 ){
120107   Fts3Expr *pRet = 0;
120108   Fts3Expr *pPrev = 0;
120109   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
120110   int nIn = n;
120111   const char *zIn = z;
120112   int rc = SQLITE_OK;
120113   int isRequirePhrase = 1;
120114 
120115   while( rc==SQLITE_OK ){
120116     Fts3Expr *p = 0;
120117     int nByte = 0;
120118     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
120119     if( rc==SQLITE_OK ){
120120       int isPhrase;
120121 
120122       if( !sqlite3_fts3_enable_parentheses
120123        && p->eType==FTSQUERY_PHRASE && pParse->isNot
120124       ){
120125         /* Create an implicit NOT operator. */
120126         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
120127         if( !pNot ){
120128           sqlite3Fts3ExprFree(p);
120129           rc = SQLITE_NOMEM;
120130           goto exprparse_out;
120131         }
120132         pNot->eType = FTSQUERY_NOT;
120133         pNot->pRight = p;
120134         if( pNotBranch ){
120135           pNot->pLeft = pNotBranch;
120136         }
120137         pNotBranch = pNot;
120138         p = pPrev;
120139       }else{
120140         int eType = p->eType;
120141         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
120142 
120143         /* The isRequirePhrase variable is set to true if a phrase or
120144         ** an expression contained in parenthesis is required. If a
120145         ** binary operator (AND, OR, NOT or NEAR) is encounted when
120146         ** isRequirePhrase is set, this is a syntax error.
120147         */
120148         if( !isPhrase && isRequirePhrase ){
120149           sqlite3Fts3ExprFree(p);
120150           rc = SQLITE_ERROR;
120151           goto exprparse_out;
120152         }
120153 
120154         if( isPhrase && !isRequirePhrase ){
120155           /* Insert an implicit AND operator. */
120156           Fts3Expr *pAnd;
120157           assert( pRet && pPrev );
120158           pAnd = fts3MallocZero(sizeof(Fts3Expr));
120159           if( !pAnd ){
120160             sqlite3Fts3ExprFree(p);
120161             rc = SQLITE_NOMEM;
120162             goto exprparse_out;
120163           }
120164           pAnd->eType = FTSQUERY_AND;
120165           insertBinaryOperator(&pRet, pPrev, pAnd);
120166           pPrev = pAnd;
120167         }
120168 
120169         /* This test catches attempts to make either operand of a NEAR
120170         ** operator something other than a phrase. For example, either of
120171         ** the following:
120172         **
120173         **    (bracketed expression) NEAR phrase
120174         **    phrase NEAR (bracketed expression)
120175         **
120176         ** Return an error in either case.
120177         */
120178         if( pPrev && (
120179             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
120180          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
120181         )){
120182           sqlite3Fts3ExprFree(p);
120183           rc = SQLITE_ERROR;
120184           goto exprparse_out;
120185         }
120186 
120187         if( isPhrase ){
120188           if( pRet ){
120189             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
120190             pPrev->pRight = p;
120191             p->pParent = pPrev;
120192           }else{
120193             pRet = p;
120194           }
120195         }else{
120196           insertBinaryOperator(&pRet, pPrev, p);
120197         }
120198         isRequirePhrase = !isPhrase;
120199       }
120200       assert( nByte>0 );
120201     }
120202     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
120203     nIn -= nByte;
120204     zIn += nByte;
120205     pPrev = p;
120206   }
120207 
120208   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
120209     rc = SQLITE_ERROR;
120210   }
120211 
120212   if( rc==SQLITE_DONE ){
120213     rc = SQLITE_OK;
120214     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
120215       if( !pRet ){
120216         rc = SQLITE_ERROR;
120217       }else{
120218         Fts3Expr *pIter = pNotBranch;
120219         while( pIter->pLeft ){
120220           pIter = pIter->pLeft;
120221         }
120222         pIter->pLeft = pRet;
120223         pRet = pNotBranch;
120224       }
120225     }
120226   }
120227   *pnConsumed = n - nIn;
120228 
120229 exprparse_out:
120230   if( rc!=SQLITE_OK ){
120231     sqlite3Fts3ExprFree(pRet);
120232     sqlite3Fts3ExprFree(pNotBranch);
120233     pRet = 0;
120234   }
120235   *ppExpr = pRet;
120236   return rc;
120237 }
120238 
120239 /*
120240 ** Parameters z and n contain a pointer to and length of a buffer containing
120241 ** an fts3 query expression, respectively. This function attempts to parse the
120242 ** query expression and create a tree of Fts3Expr structures representing the
120243 ** parsed expression. If successful, *ppExpr is set to point to the head
120244 ** of the parsed expression tree and SQLITE_OK is returned. If an error
120245 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
120246 ** error) is returned and *ppExpr is set to 0.
120247 **
120248 ** If parameter n is a negative number, then z is assumed to point to a
120249 ** nul-terminated string and the length is determined using strlen().
120250 **
120251 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
120252 ** use to normalize query tokens while parsing the expression. The azCol[]
120253 ** array, which is assumed to contain nCol entries, should contain the names
120254 ** of each column in the target fts3 table, in order from left to right.
120255 ** Column names must be nul-terminated strings.
120256 **
120257 ** The iDefaultCol parameter should be passed the index of the table column
120258 ** that appears on the left-hand-side of the MATCH operator (the default
120259 ** column to match against for tokens for which a column name is not explicitly
120260 ** specified as part of the query string), or -1 if tokens may by default
120261 ** match any table column.
120262 */
120263 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
120264   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
120265   char **azCol,                       /* Array of column names for fts3 table */
120266   int nCol,                           /* Number of entries in azCol[] */
120267   int iDefaultCol,                    /* Default column to query */
120268   const char *z, int n,               /* Text of MATCH query */
120269   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
120270 ){
120271   int nParsed;
120272   int rc;
120273   ParseContext sParse;
120274   sParse.pTokenizer = pTokenizer;
120275   sParse.azCol = (const char **)azCol;
120276   sParse.nCol = nCol;
120277   sParse.iDefaultCol = iDefaultCol;
120278   sParse.nNest = 0;
120279   if( z==0 ){
120280     *ppExpr = 0;
120281     return SQLITE_OK;
120282   }
120283   if( n<0 ){
120284     n = (int)strlen(z);
120285   }
120286   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
120287 
120288   /* Check for mismatched parenthesis */
120289   if( rc==SQLITE_OK && sParse.nNest ){
120290     rc = SQLITE_ERROR;
120291     sqlite3Fts3ExprFree(*ppExpr);
120292     *ppExpr = 0;
120293   }
120294 
120295   return rc;
120296 }
120297 
120298 /*
120299 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
120300 */
120301 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
120302   if( p ){
120303     assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
120304     sqlite3Fts3ExprFree(p->pLeft);
120305     sqlite3Fts3ExprFree(p->pRight);
120306     sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
120307     sqlite3_free(p->aMI);
120308     sqlite3_free(p);
120309   }
120310 }
120311 
120312 /****************************************************************************
120313 *****************************************************************************
120314 ** Everything after this point is just test code.
120315 */
120316 
120317 #ifdef SQLITE_TEST
120318 
120319 /* #include <stdio.h> */
120320 
120321 /*
120322 ** Function to query the hash-table of tokenizers (see README.tokenizers).
120323 */
120324 static int queryTestTokenizer(
120325   sqlite3 *db,
120326   const char *zName,
120327   const sqlite3_tokenizer_module **pp
120328 ){
120329   int rc;
120330   sqlite3_stmt *pStmt;
120331   const char zSql[] = "SELECT fts3_tokenizer(?)";
120332 
120333   *pp = 0;
120334   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
120335   if( rc!=SQLITE_OK ){
120336     return rc;
120337   }
120338 
120339   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
120340   if( SQLITE_ROW==sqlite3_step(pStmt) ){
120341     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
120342       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
120343     }
120344   }
120345 
120346   return sqlite3_finalize(pStmt);
120347 }
120348 
120349 /*
120350 ** Return a pointer to a buffer containing a text representation of the
120351 ** expression passed as the first argument. The buffer is obtained from
120352 ** sqlite3_malloc(). It is the responsibility of the caller to use
120353 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
120354 ** NULL is returned.
120355 **
120356 ** If the second argument is not NULL, then its contents are prepended to
120357 ** the returned expression text and then freed using sqlite3_free().
120358 */
120359 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
120360   switch( pExpr->eType ){
120361     case FTSQUERY_PHRASE: {
120362       Fts3Phrase *pPhrase = pExpr->pPhrase;
120363       int i;
120364       zBuf = sqlite3_mprintf(
120365           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
120366       for(i=0; zBuf && i<pPhrase->nToken; i++){
120367         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
120368             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
120369             (pPhrase->aToken[i].isPrefix?"+":"")
120370         );
120371       }
120372       return zBuf;
120373     }
120374 
120375     case FTSQUERY_NEAR:
120376       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
120377       break;
120378     case FTSQUERY_NOT:
120379       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
120380       break;
120381     case FTSQUERY_AND:
120382       zBuf = sqlite3_mprintf("%zAND ", zBuf);
120383       break;
120384     case FTSQUERY_OR:
120385       zBuf = sqlite3_mprintf("%zOR ", zBuf);
120386       break;
120387   }
120388 
120389   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
120390   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
120391   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
120392 
120393   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
120394   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
120395 
120396   return zBuf;
120397 }
120398 
120399 /*
120400 ** This is the implementation of a scalar SQL function used to test the
120401 ** expression parser. It should be called as follows:
120402 **
120403 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
120404 **
120405 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
120406 ** to parse the query expression (see README.tokenizers). The second argument
120407 ** is the query expression to parse. Each subsequent argument is the name
120408 ** of a column of the fts3 table that the query expression may refer to.
120409 ** For example:
120410 **
120411 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
120412 */
120413 static void fts3ExprTest(
120414   sqlite3_context *context,
120415   int argc,
120416   sqlite3_value **argv
120417 ){
120418   sqlite3_tokenizer_module const *pModule = 0;
120419   sqlite3_tokenizer *pTokenizer = 0;
120420   int rc;
120421   char **azCol = 0;
120422   const char *zExpr;
120423   int nExpr;
120424   int nCol;
120425   int ii;
120426   Fts3Expr *pExpr;
120427   char *zBuf = 0;
120428   sqlite3 *db = sqlite3_context_db_handle(context);
120429 
120430   if( argc<3 ){
120431     sqlite3_result_error(context,
120432         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
120433     );
120434     return;
120435   }
120436 
120437   rc = queryTestTokenizer(db,
120438                           (const char *)sqlite3_value_text(argv[0]), &pModule);
120439   if( rc==SQLITE_NOMEM ){
120440     sqlite3_result_error_nomem(context);
120441     goto exprtest_out;
120442   }else if( !pModule ){
120443     sqlite3_result_error(context, "No such tokenizer module", -1);
120444     goto exprtest_out;
120445   }
120446 
120447   rc = pModule->xCreate(0, 0, &pTokenizer);
120448   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
120449   if( rc==SQLITE_NOMEM ){
120450     sqlite3_result_error_nomem(context);
120451     goto exprtest_out;
120452   }
120453   pTokenizer->pModule = pModule;
120454 
120455   zExpr = (const char *)sqlite3_value_text(argv[1]);
120456   nExpr = sqlite3_value_bytes(argv[1]);
120457   nCol = argc-2;
120458   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
120459   if( !azCol ){
120460     sqlite3_result_error_nomem(context);
120461     goto exprtest_out;
120462   }
120463   for(ii=0; ii<nCol; ii++){
120464     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
120465   }
120466 
120467   rc = sqlite3Fts3ExprParse(
120468       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
120469   );
120470   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
120471     sqlite3_result_error(context, "Error parsing expression", -1);
120472   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
120473     sqlite3_result_error_nomem(context);
120474   }else{
120475     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
120476     sqlite3_free(zBuf);
120477   }
120478 
120479   sqlite3Fts3ExprFree(pExpr);
120480 
120481 exprtest_out:
120482   if( pModule && pTokenizer ){
120483     rc = pModule->xDestroy(pTokenizer);
120484   }
120485   sqlite3_free(azCol);
120486 }
120487 
120488 /*
120489 ** Register the query expression parser test function fts3_exprtest()
120490 ** with database connection db.
120491 */
120492 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
120493   return sqlite3_create_function(
120494       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
120495   );
120496 }
120497 
120498 #endif
120499 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
120500 
120501 /************** End of fts3_expr.c *******************************************/
120502 /************** Begin file fts3_hash.c ***************************************/
120503 /*
120504 ** 2001 September 22
120505 **
120506 ** The author disclaims copyright to this source code.  In place of
120507 ** a legal notice, here is a blessing:
120508 **
120509 **    May you do good and not evil.
120510 **    May you find forgiveness for yourself and forgive others.
120511 **    May you share freely, never taking more than you give.
120512 **
120513 *************************************************************************
120514 ** This is the implementation of generic hash-tables used in SQLite.
120515 ** We've modified it slightly to serve as a standalone hash table
120516 ** implementation for the full-text indexing module.
120517 */
120518 
120519 /*
120520 ** The code in this file is only compiled if:
120521 **
120522 **     * The FTS3 module is being built as an extension
120523 **       (in which case SQLITE_CORE is not defined), or
120524 **
120525 **     * The FTS3 module is being built into the core of
120526 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
120527 */
120528 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120529 
120530 /* #include <assert.h> */
120531 /* #include <stdlib.h> */
120532 /* #include <string.h> */
120533 
120534 
120535 /*
120536 ** Malloc and Free functions
120537 */
120538 static void *fts3HashMalloc(int n){
120539   void *p = sqlite3_malloc(n);
120540   if( p ){
120541     memset(p, 0, n);
120542   }
120543   return p;
120544 }
120545 static void fts3HashFree(void *p){
120546   sqlite3_free(p);
120547 }
120548 
120549 /* Turn bulk memory into a hash table object by initializing the
120550 ** fields of the Hash structure.
120551 **
120552 ** "pNew" is a pointer to the hash table that is to be initialized.
120553 ** keyClass is one of the constants
120554 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
120555 ** determines what kind of key the hash table will use.  "copyKey" is
120556 ** true if the hash table should make its own private copy of keys and
120557 ** false if it should just use the supplied pointer.
120558 */
120559 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
120560   assert( pNew!=0 );
120561   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
120562   pNew->keyClass = keyClass;
120563   pNew->copyKey = copyKey;
120564   pNew->first = 0;
120565   pNew->count = 0;
120566   pNew->htsize = 0;
120567   pNew->ht = 0;
120568 }
120569 
120570 /* Remove all entries from a hash table.  Reclaim all memory.
120571 ** Call this routine to delete a hash table or to reset a hash table
120572 ** to the empty state.
120573 */
120574 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
120575   Fts3HashElem *elem;         /* For looping over all elements of the table */
120576 
120577   assert( pH!=0 );
120578   elem = pH->first;
120579   pH->first = 0;
120580   fts3HashFree(pH->ht);
120581   pH->ht = 0;
120582   pH->htsize = 0;
120583   while( elem ){
120584     Fts3HashElem *next_elem = elem->next;
120585     if( pH->copyKey && elem->pKey ){
120586       fts3HashFree(elem->pKey);
120587     }
120588     fts3HashFree(elem);
120589     elem = next_elem;
120590   }
120591   pH->count = 0;
120592 }
120593 
120594 /*
120595 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
120596 */
120597 static int fts3StrHash(const void *pKey, int nKey){
120598   const char *z = (const char *)pKey;
120599   int h = 0;
120600   if( nKey<=0 ) nKey = (int) strlen(z);
120601   while( nKey > 0  ){
120602     h = (h<<3) ^ h ^ *z++;
120603     nKey--;
120604   }
120605   return h & 0x7fffffff;
120606 }
120607 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
120608   if( n1!=n2 ) return 1;
120609   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
120610 }
120611 
120612 /*
120613 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
120614 */
120615 static int fts3BinHash(const void *pKey, int nKey){
120616   int h = 0;
120617   const char *z = (const char *)pKey;
120618   while( nKey-- > 0 ){
120619     h = (h<<3) ^ h ^ *(z++);
120620   }
120621   return h & 0x7fffffff;
120622 }
120623 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
120624   if( n1!=n2 ) return 1;
120625   return memcmp(pKey1,pKey2,n1);
120626 }
120627 
120628 /*
120629 ** Return a pointer to the appropriate hash function given the key class.
120630 **
120631 ** The C syntax in this function definition may be unfamilar to some
120632 ** programmers, so we provide the following additional explanation:
120633 **
120634 ** The name of the function is "ftsHashFunction".  The function takes a
120635 ** single parameter "keyClass".  The return value of ftsHashFunction()
120636 ** is a pointer to another function.  Specifically, the return value
120637 ** of ftsHashFunction() is a pointer to a function that takes two parameters
120638 ** with types "const void*" and "int" and returns an "int".
120639 */
120640 static int (*ftsHashFunction(int keyClass))(const void*,int){
120641   if( keyClass==FTS3_HASH_STRING ){
120642     return &fts3StrHash;
120643   }else{
120644     assert( keyClass==FTS3_HASH_BINARY );
120645     return &fts3BinHash;
120646   }
120647 }
120648 
120649 /*
120650 ** Return a pointer to the appropriate hash function given the key class.
120651 **
120652 ** For help in interpreted the obscure C code in the function definition,
120653 ** see the header comment on the previous function.
120654 */
120655 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
120656   if( keyClass==FTS3_HASH_STRING ){
120657     return &fts3StrCompare;
120658   }else{
120659     assert( keyClass==FTS3_HASH_BINARY );
120660     return &fts3BinCompare;
120661   }
120662 }
120663 
120664 /* Link an element into the hash table
120665 */
120666 static void fts3HashInsertElement(
120667   Fts3Hash *pH,            /* The complete hash table */
120668   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
120669   Fts3HashElem *pNew       /* The element to be inserted */
120670 ){
120671   Fts3HashElem *pHead;     /* First element already in pEntry */
120672   pHead = pEntry->chain;
120673   if( pHead ){
120674     pNew->next = pHead;
120675     pNew->prev = pHead->prev;
120676     if( pHead->prev ){ pHead->prev->next = pNew; }
120677     else             { pH->first = pNew; }
120678     pHead->prev = pNew;
120679   }else{
120680     pNew->next = pH->first;
120681     if( pH->first ){ pH->first->prev = pNew; }
120682     pNew->prev = 0;
120683     pH->first = pNew;
120684   }
120685   pEntry->count++;
120686   pEntry->chain = pNew;
120687 }
120688 
120689 
120690 /* Resize the hash table so that it cantains "new_size" buckets.
120691 ** "new_size" must be a power of 2.  The hash table might fail
120692 ** to resize if sqliteMalloc() fails.
120693 **
120694 ** Return non-zero if a memory allocation error occurs.
120695 */
120696 static int fts3Rehash(Fts3Hash *pH, int new_size){
120697   struct _fts3ht *new_ht;          /* The new hash table */
120698   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
120699   int (*xHash)(const void*,int);   /* The hash function */
120700 
120701   assert( (new_size & (new_size-1))==0 );
120702   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
120703   if( new_ht==0 ) return 1;
120704   fts3HashFree(pH->ht);
120705   pH->ht = new_ht;
120706   pH->htsize = new_size;
120707   xHash = ftsHashFunction(pH->keyClass);
120708   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
120709     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
120710     next_elem = elem->next;
120711     fts3HashInsertElement(pH, &new_ht[h], elem);
120712   }
120713   return 0;
120714 }
120715 
120716 /* This function (for internal use only) locates an element in an
120717 ** hash table that matches the given key.  The hash for this key has
120718 ** already been computed and is passed as the 4th parameter.
120719 */
120720 static Fts3HashElem *fts3FindElementByHash(
120721   const Fts3Hash *pH, /* The pH to be searched */
120722   const void *pKey,   /* The key we are searching for */
120723   int nKey,
120724   int h               /* The hash for this key. */
120725 ){
120726   Fts3HashElem *elem;            /* Used to loop thru the element list */
120727   int count;                     /* Number of elements left to test */
120728   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
120729 
120730   if( pH->ht ){
120731     struct _fts3ht *pEntry = &pH->ht[h];
120732     elem = pEntry->chain;
120733     count = pEntry->count;
120734     xCompare = ftsCompareFunction(pH->keyClass);
120735     while( count-- && elem ){
120736       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
120737         return elem;
120738       }
120739       elem = elem->next;
120740     }
120741   }
120742   return 0;
120743 }
120744 
120745 /* Remove a single entry from the hash table given a pointer to that
120746 ** element and a hash on the element's key.
120747 */
120748 static void fts3RemoveElementByHash(
120749   Fts3Hash *pH,         /* The pH containing "elem" */
120750   Fts3HashElem* elem,   /* The element to be removed from the pH */
120751   int h                 /* Hash value for the element */
120752 ){
120753   struct _fts3ht *pEntry;
120754   if( elem->prev ){
120755     elem->prev->next = elem->next;
120756   }else{
120757     pH->first = elem->next;
120758   }
120759   if( elem->next ){
120760     elem->next->prev = elem->prev;
120761   }
120762   pEntry = &pH->ht[h];
120763   if( pEntry->chain==elem ){
120764     pEntry->chain = elem->next;
120765   }
120766   pEntry->count--;
120767   if( pEntry->count<=0 ){
120768     pEntry->chain = 0;
120769   }
120770   if( pH->copyKey && elem->pKey ){
120771     fts3HashFree(elem->pKey);
120772   }
120773   fts3HashFree( elem );
120774   pH->count--;
120775   if( pH->count<=0 ){
120776     assert( pH->first==0 );
120777     assert( pH->count==0 );
120778     fts3HashClear(pH);
120779   }
120780 }
120781 
120782 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
120783   const Fts3Hash *pH,
120784   const void *pKey,
120785   int nKey
120786 ){
120787   int h;                          /* A hash on key */
120788   int (*xHash)(const void*,int);  /* The hash function */
120789 
120790   if( pH==0 || pH->ht==0 ) return 0;
120791   xHash = ftsHashFunction(pH->keyClass);
120792   assert( xHash!=0 );
120793   h = (*xHash)(pKey,nKey);
120794   assert( (pH->htsize & (pH->htsize-1))==0 );
120795   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
120796 }
120797 
120798 /*
120799 ** Attempt to locate an element of the hash table pH with a key
120800 ** that matches pKey,nKey.  Return the data for this element if it is
120801 ** found, or NULL if there is no match.
120802 */
120803 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
120804   Fts3HashElem *pElem;            /* The element that matches key (if any) */
120805 
120806   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
120807   return pElem ? pElem->data : 0;
120808 }
120809 
120810 /* Insert an element into the hash table pH.  The key is pKey,nKey
120811 ** and the data is "data".
120812 **
120813 ** If no element exists with a matching key, then a new
120814 ** element is created.  A copy of the key is made if the copyKey
120815 ** flag is set.  NULL is returned.
120816 **
120817 ** If another element already exists with the same key, then the
120818 ** new data replaces the old data and the old data is returned.
120819 ** The key is not copied in this instance.  If a malloc fails, then
120820 ** the new data is returned and the hash table is unchanged.
120821 **
120822 ** If the "data" parameter to this function is NULL, then the
120823 ** element corresponding to "key" is removed from the hash table.
120824 */
120825 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
120826   Fts3Hash *pH,        /* The hash table to insert into */
120827   const void *pKey,    /* The key */
120828   int nKey,            /* Number of bytes in the key */
120829   void *data           /* The data */
120830 ){
120831   int hraw;                 /* Raw hash value of the key */
120832   int h;                    /* the hash of the key modulo hash table size */
120833   Fts3HashElem *elem;       /* Used to loop thru the element list */
120834   Fts3HashElem *new_elem;   /* New element added to the pH */
120835   int (*xHash)(const void*,int);  /* The hash function */
120836 
120837   assert( pH!=0 );
120838   xHash = ftsHashFunction(pH->keyClass);
120839   assert( xHash!=0 );
120840   hraw = (*xHash)(pKey, nKey);
120841   assert( (pH->htsize & (pH->htsize-1))==0 );
120842   h = hraw & (pH->htsize-1);
120843   elem = fts3FindElementByHash(pH,pKey,nKey,h);
120844   if( elem ){
120845     void *old_data = elem->data;
120846     if( data==0 ){
120847       fts3RemoveElementByHash(pH,elem,h);
120848     }else{
120849       elem->data = data;
120850     }
120851     return old_data;
120852   }
120853   if( data==0 ) return 0;
120854   if( (pH->htsize==0 && fts3Rehash(pH,8))
120855    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
120856   ){
120857     pH->count = 0;
120858     return data;
120859   }
120860   assert( pH->htsize>0 );
120861   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
120862   if( new_elem==0 ) return data;
120863   if( pH->copyKey && pKey!=0 ){
120864     new_elem->pKey = fts3HashMalloc( nKey );
120865     if( new_elem->pKey==0 ){
120866       fts3HashFree(new_elem);
120867       return data;
120868     }
120869     memcpy((void*)new_elem->pKey, pKey, nKey);
120870   }else{
120871     new_elem->pKey = (void*)pKey;
120872   }
120873   new_elem->nKey = nKey;
120874   pH->count++;
120875   assert( pH->htsize>0 );
120876   assert( (pH->htsize & (pH->htsize-1))==0 );
120877   h = hraw & (pH->htsize-1);
120878   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
120879   new_elem->data = data;
120880   return 0;
120881 }
120882 
120883 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
120884 
120885 /************** End of fts3_hash.c *******************************************/
120886 /************** Begin file fts3_porter.c *************************************/
120887 /*
120888 ** 2006 September 30
120889 **
120890 ** The author disclaims copyright to this source code.  In place of
120891 ** a legal notice, here is a blessing:
120892 **
120893 **    May you do good and not evil.
120894 **    May you find forgiveness for yourself and forgive others.
120895 **    May you share freely, never taking more than you give.
120896 **
120897 *************************************************************************
120898 ** Implementation of the full-text-search tokenizer that implements
120899 ** a Porter stemmer.
120900 */
120901 
120902 /*
120903 ** The code in this file is only compiled if:
120904 **
120905 **     * The FTS3 module is being built as an extension
120906 **       (in which case SQLITE_CORE is not defined), or
120907 **
120908 **     * The FTS3 module is being built into the core of
120909 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
120910 */
120911 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
120912 
120913 /* #include <assert.h> */
120914 /* #include <stdlib.h> */
120915 /* #include <stdio.h> */
120916 /* #include <string.h> */
120917 
120918 
120919 /*
120920 ** Class derived from sqlite3_tokenizer
120921 */
120922 typedef struct porter_tokenizer {
120923   sqlite3_tokenizer base;      /* Base class */
120924 } porter_tokenizer;
120925 
120926 /*
120927 ** Class derived from sqlit3_tokenizer_cursor
120928 */
120929 typedef struct porter_tokenizer_cursor {
120930   sqlite3_tokenizer_cursor base;
120931   const char *zInput;          /* input we are tokenizing */
120932   int nInput;                  /* size of the input */
120933   int iOffset;                 /* current position in zInput */
120934   int iToken;                  /* index of next token to be returned */
120935   char *zToken;                /* storage for current token */
120936   int nAllocated;              /* space allocated to zToken buffer */
120937 } porter_tokenizer_cursor;
120938 
120939 
120940 /*
120941 ** Create a new tokenizer instance.
120942 */
120943 static int porterCreate(
120944   int argc, const char * const *argv,
120945   sqlite3_tokenizer **ppTokenizer
120946 ){
120947   porter_tokenizer *t;
120948 
120949   UNUSED_PARAMETER(argc);
120950   UNUSED_PARAMETER(argv);
120951 
120952   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
120953   if( t==NULL ) return SQLITE_NOMEM;
120954   memset(t, 0, sizeof(*t));
120955   *ppTokenizer = &t->base;
120956   return SQLITE_OK;
120957 }
120958 
120959 /*
120960 ** Destroy a tokenizer
120961 */
120962 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
120963   sqlite3_free(pTokenizer);
120964   return SQLITE_OK;
120965 }
120966 
120967 /*
120968 ** Prepare to begin tokenizing a particular string.  The input
120969 ** string to be tokenized is zInput[0..nInput-1].  A cursor
120970 ** used to incrementally tokenize this string is returned in
120971 ** *ppCursor.
120972 */
120973 static int porterOpen(
120974   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
120975   const char *zInput, int nInput,        /* String to be tokenized */
120976   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
120977 ){
120978   porter_tokenizer_cursor *c;
120979 
120980   UNUSED_PARAMETER(pTokenizer);
120981 
120982   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
120983   if( c==NULL ) return SQLITE_NOMEM;
120984 
120985   c->zInput = zInput;
120986   if( zInput==0 ){
120987     c->nInput = 0;
120988   }else if( nInput<0 ){
120989     c->nInput = (int)strlen(zInput);
120990   }else{
120991     c->nInput = nInput;
120992   }
120993   c->iOffset = 0;                 /* start tokenizing at the beginning */
120994   c->iToken = 0;
120995   c->zToken = NULL;               /* no space allocated, yet. */
120996   c->nAllocated = 0;
120997 
120998   *ppCursor = &c->base;
120999   return SQLITE_OK;
121000 }
121001 
121002 /*
121003 ** Close a tokenization cursor previously opened by a call to
121004 ** porterOpen() above.
121005 */
121006 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
121007   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
121008   sqlite3_free(c->zToken);
121009   sqlite3_free(c);
121010   return SQLITE_OK;
121011 }
121012 /*
121013 ** Vowel or consonant
121014 */
121015 static const char cType[] = {
121016    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
121017    1, 1, 1, 2, 1
121018 };
121019 
121020 /*
121021 ** isConsonant() and isVowel() determine if their first character in
121022 ** the string they point to is a consonant or a vowel, according
121023 ** to Porter ruls.
121024 **
121025 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
121026 ** 'Y' is a consonant unless it follows another consonant,
121027 ** in which case it is a vowel.
121028 **
121029 ** In these routine, the letters are in reverse order.  So the 'y' rule
121030 ** is that 'y' is a consonant unless it is followed by another
121031 ** consonent.
121032 */
121033 static int isVowel(const char*);
121034 static int isConsonant(const char *z){
121035   int j;
121036   char x = *z;
121037   if( x==0 ) return 0;
121038   assert( x>='a' && x<='z' );
121039   j = cType[x-'a'];
121040   if( j<2 ) return j;
121041   return z[1]==0 || isVowel(z + 1);
121042 }
121043 static int isVowel(const char *z){
121044   int j;
121045   char x = *z;
121046   if( x==0 ) return 0;
121047   assert( x>='a' && x<='z' );
121048   j = cType[x-'a'];
121049   if( j<2 ) return 1-j;
121050   return isConsonant(z + 1);
121051 }
121052 
121053 /*
121054 ** Let any sequence of one or more vowels be represented by V and let
121055 ** C be sequence of one or more consonants.  Then every word can be
121056 ** represented as:
121057 **
121058 **           [C] (VC){m} [V]
121059 **
121060 ** In prose:  A word is an optional consonant followed by zero or
121061 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
121062 ** number of vowel consonant pairs.  This routine computes the value
121063 ** of m for the first i bytes of a word.
121064 **
121065 ** Return true if the m-value for z is 1 or more.  In other words,
121066 ** return true if z contains at least one vowel that is followed
121067 ** by a consonant.
121068 **
121069 ** In this routine z[] is in reverse order.  So we are really looking
121070 ** for an instance of of a consonant followed by a vowel.
121071 */
121072 static int m_gt_0(const char *z){
121073   while( isVowel(z) ){ z++; }
121074   if( *z==0 ) return 0;
121075   while( isConsonant(z) ){ z++; }
121076   return *z!=0;
121077 }
121078 
121079 /* Like mgt0 above except we are looking for a value of m which is
121080 ** exactly 1
121081 */
121082 static int m_eq_1(const char *z){
121083   while( isVowel(z) ){ z++; }
121084   if( *z==0 ) return 0;
121085   while( isConsonant(z) ){ z++; }
121086   if( *z==0 ) return 0;
121087   while( isVowel(z) ){ z++; }
121088   if( *z==0 ) return 1;
121089   while( isConsonant(z) ){ z++; }
121090   return *z==0;
121091 }
121092 
121093 /* Like mgt0 above except we are looking for a value of m>1 instead
121094 ** or m>0
121095 */
121096 static int m_gt_1(const char *z){
121097   while( isVowel(z) ){ z++; }
121098   if( *z==0 ) return 0;
121099   while( isConsonant(z) ){ z++; }
121100   if( *z==0 ) return 0;
121101   while( isVowel(z) ){ z++; }
121102   if( *z==0 ) return 0;
121103   while( isConsonant(z) ){ z++; }
121104   return *z!=0;
121105 }
121106 
121107 /*
121108 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
121109 */
121110 static int hasVowel(const char *z){
121111   while( isConsonant(z) ){ z++; }
121112   return *z!=0;
121113 }
121114 
121115 /*
121116 ** Return TRUE if the word ends in a double consonant.
121117 **
121118 ** The text is reversed here. So we are really looking at
121119 ** the first two characters of z[].
121120 */
121121 static int doubleConsonant(const char *z){
121122   return isConsonant(z) && z[0]==z[1];
121123 }
121124 
121125 /*
121126 ** Return TRUE if the word ends with three letters which
121127 ** are consonant-vowel-consonent and where the final consonant
121128 ** is not 'w', 'x', or 'y'.
121129 **
121130 ** The word is reversed here.  So we are really checking the
121131 ** first three letters and the first one cannot be in [wxy].
121132 */
121133 static int star_oh(const char *z){
121134   return
121135     isConsonant(z) &&
121136     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
121137     isVowel(z+1) &&
121138     isConsonant(z+2);
121139 }
121140 
121141 /*
121142 ** If the word ends with zFrom and xCond() is true for the stem
121143 ** of the word that preceeds the zFrom ending, then change the
121144 ** ending to zTo.
121145 **
121146 ** The input word *pz and zFrom are both in reverse order.  zTo
121147 ** is in normal order.
121148 **
121149 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
121150 ** match.  Not that TRUE is returned even if xCond() fails and
121151 ** no substitution occurs.
121152 */
121153 static int stem(
121154   char **pz,             /* The word being stemmed (Reversed) */
121155   const char *zFrom,     /* If the ending matches this... (Reversed) */
121156   const char *zTo,       /* ... change the ending to this (not reversed) */
121157   int (*xCond)(const char*)   /* Condition that must be true */
121158 ){
121159   char *z = *pz;
121160   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
121161   if( *zFrom!=0 ) return 0;
121162   if( xCond && !xCond(z) ) return 1;
121163   while( *zTo ){
121164     *(--z) = *(zTo++);
121165   }
121166   *pz = z;
121167   return 1;
121168 }
121169 
121170 /*
121171 ** This is the fallback stemmer used when the porter stemmer is
121172 ** inappropriate.  The input word is copied into the output with
121173 ** US-ASCII case folding.  If the input word is too long (more
121174 ** than 20 bytes if it contains no digits or more than 6 bytes if
121175 ** it contains digits) then word is truncated to 20 or 6 bytes
121176 ** by taking 10 or 3 bytes from the beginning and end.
121177 */
121178 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
121179   int i, mx, j;
121180   int hasDigit = 0;
121181   for(i=0; i<nIn; i++){
121182     char c = zIn[i];
121183     if( c>='A' && c<='Z' ){
121184       zOut[i] = c - 'A' + 'a';
121185     }else{
121186       if( c>='0' && c<='9' ) hasDigit = 1;
121187       zOut[i] = c;
121188     }
121189   }
121190   mx = hasDigit ? 3 : 10;
121191   if( nIn>mx*2 ){
121192     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
121193       zOut[j] = zOut[i];
121194     }
121195     i = j;
121196   }
121197   zOut[i] = 0;
121198   *pnOut = i;
121199 }
121200 
121201 
121202 /*
121203 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
121204 ** zOut is at least big enough to hold nIn bytes.  Write the actual
121205 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
121206 **
121207 ** Any upper-case characters in the US-ASCII character set ([A-Z])
121208 ** are converted to lower case.  Upper-case UTF characters are
121209 ** unchanged.
121210 **
121211 ** Words that are longer than about 20 bytes are stemmed by retaining
121212 ** a few bytes from the beginning and the end of the word.  If the
121213 ** word contains digits, 3 bytes are taken from the beginning and
121214 ** 3 bytes from the end.  For long words without digits, 10 bytes
121215 ** are taken from each end.  US-ASCII case folding still applies.
121216 **
121217 ** If the input word contains not digits but does characters not
121218 ** in [a-zA-Z] then no stemming is attempted and this routine just
121219 ** copies the input into the input into the output with US-ASCII
121220 ** case folding.
121221 **
121222 ** Stemming never increases the length of the word.  So there is
121223 ** no chance of overflowing the zOut buffer.
121224 */
121225 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
121226   int i, j;
121227   char zReverse[28];
121228   char *z, *z2;
121229   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
121230     /* The word is too big or too small for the porter stemmer.
121231     ** Fallback to the copy stemmer */
121232     copy_stemmer(zIn, nIn, zOut, pnOut);
121233     return;
121234   }
121235   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
121236     char c = zIn[i];
121237     if( c>='A' && c<='Z' ){
121238       zReverse[j] = c + 'a' - 'A';
121239     }else if( c>='a' && c<='z' ){
121240       zReverse[j] = c;
121241     }else{
121242       /* The use of a character not in [a-zA-Z] means that we fallback
121243       ** to the copy stemmer */
121244       copy_stemmer(zIn, nIn, zOut, pnOut);
121245       return;
121246     }
121247   }
121248   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
121249   z = &zReverse[j+1];
121250 
121251 
121252   /* Step 1a */
121253   if( z[0]=='s' ){
121254     if(
121255      !stem(&z, "sess", "ss", 0) &&
121256      !stem(&z, "sei", "i", 0)  &&
121257      !stem(&z, "ss", "ss", 0)
121258     ){
121259       z++;
121260     }
121261   }
121262 
121263   /* Step 1b */
121264   z2 = z;
121265   if( stem(&z, "dee", "ee", m_gt_0) ){
121266     /* Do nothing.  The work was all in the test */
121267   }else if(
121268      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
121269       && z!=z2
121270   ){
121271      if( stem(&z, "ta", "ate", 0) ||
121272          stem(&z, "lb", "ble", 0) ||
121273          stem(&z, "zi", "ize", 0) ){
121274        /* Do nothing.  The work was all in the test */
121275      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
121276        z++;
121277      }else if( m_eq_1(z) && star_oh(z) ){
121278        *(--z) = 'e';
121279      }
121280   }
121281 
121282   /* Step 1c */
121283   if( z[0]=='y' && hasVowel(z+1) ){
121284     z[0] = 'i';
121285   }
121286 
121287   /* Step 2 */
121288   switch( z[1] ){
121289    case 'a':
121290      stem(&z, "lanoita", "ate", m_gt_0) ||
121291      stem(&z, "lanoit", "tion", m_gt_0);
121292      break;
121293    case 'c':
121294      stem(&z, "icne", "ence", m_gt_0) ||
121295      stem(&z, "icna", "ance", m_gt_0);
121296      break;
121297    case 'e':
121298      stem(&z, "rezi", "ize", m_gt_0);
121299      break;
121300    case 'g':
121301      stem(&z, "igol", "log", m_gt_0);
121302      break;
121303    case 'l':
121304      stem(&z, "ilb", "ble", m_gt_0) ||
121305      stem(&z, "illa", "al", m_gt_0) ||
121306      stem(&z, "iltne", "ent", m_gt_0) ||
121307      stem(&z, "ile", "e", m_gt_0) ||
121308      stem(&z, "ilsuo", "ous", m_gt_0);
121309      break;
121310    case 'o':
121311      stem(&z, "noitazi", "ize", m_gt_0) ||
121312      stem(&z, "noita", "ate", m_gt_0) ||
121313      stem(&z, "rota", "ate", m_gt_0);
121314      break;
121315    case 's':
121316      stem(&z, "msila", "al", m_gt_0) ||
121317      stem(&z, "ssenevi", "ive", m_gt_0) ||
121318      stem(&z, "ssenluf", "ful", m_gt_0) ||
121319      stem(&z, "ssensuo", "ous", m_gt_0);
121320      break;
121321    case 't':
121322      stem(&z, "itila", "al", m_gt_0) ||
121323      stem(&z, "itivi", "ive", m_gt_0) ||
121324      stem(&z, "itilib", "ble", m_gt_0);
121325      break;
121326   }
121327 
121328   /* Step 3 */
121329   switch( z[0] ){
121330    case 'e':
121331      stem(&z, "etaci", "ic", m_gt_0) ||
121332      stem(&z, "evita", "", m_gt_0)   ||
121333      stem(&z, "ezila", "al", m_gt_0);
121334      break;
121335    case 'i':
121336      stem(&z, "itici", "ic", m_gt_0);
121337      break;
121338    case 'l':
121339      stem(&z, "laci", "ic", m_gt_0) ||
121340      stem(&z, "luf", "", m_gt_0);
121341      break;
121342    case 's':
121343      stem(&z, "ssen", "", m_gt_0);
121344      break;
121345   }
121346 
121347   /* Step 4 */
121348   switch( z[1] ){
121349    case 'a':
121350      if( z[0]=='l' && m_gt_1(z+2) ){
121351        z += 2;
121352      }
121353      break;
121354    case 'c':
121355      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
121356        z += 4;
121357      }
121358      break;
121359    case 'e':
121360      if( z[0]=='r' && m_gt_1(z+2) ){
121361        z += 2;
121362      }
121363      break;
121364    case 'i':
121365      if( z[0]=='c' && m_gt_1(z+2) ){
121366        z += 2;
121367      }
121368      break;
121369    case 'l':
121370      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
121371        z += 4;
121372      }
121373      break;
121374    case 'n':
121375      if( z[0]=='t' ){
121376        if( z[2]=='a' ){
121377          if( m_gt_1(z+3) ){
121378            z += 3;
121379          }
121380        }else if( z[2]=='e' ){
121381          stem(&z, "tneme", "", m_gt_1) ||
121382          stem(&z, "tnem", "", m_gt_1) ||
121383          stem(&z, "tne", "", m_gt_1);
121384        }
121385      }
121386      break;
121387    case 'o':
121388      if( z[0]=='u' ){
121389        if( m_gt_1(z+2) ){
121390          z += 2;
121391        }
121392      }else if( z[3]=='s' || z[3]=='t' ){
121393        stem(&z, "noi", "", m_gt_1);
121394      }
121395      break;
121396    case 's':
121397      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
121398        z += 3;
121399      }
121400      break;
121401    case 't':
121402      stem(&z, "eta", "", m_gt_1) ||
121403      stem(&z, "iti", "", m_gt_1);
121404      break;
121405    case 'u':
121406      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
121407        z += 3;
121408      }
121409      break;
121410    case 'v':
121411    case 'z':
121412      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
121413        z += 3;
121414      }
121415      break;
121416   }
121417 
121418   /* Step 5a */
121419   if( z[0]=='e' ){
121420     if( m_gt_1(z+1) ){
121421       z++;
121422     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
121423       z++;
121424     }
121425   }
121426 
121427   /* Step 5b */
121428   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
121429     z++;
121430   }
121431 
121432   /* z[] is now the stemmed word in reverse order.  Flip it back
121433   ** around into forward order and return.
121434   */
121435   *pnOut = i = (int)strlen(z);
121436   zOut[i] = 0;
121437   while( *z ){
121438     zOut[--i] = *(z++);
121439   }
121440 }
121441 
121442 /*
121443 ** Characters that can be part of a token.  We assume any character
121444 ** whose value is greater than 0x80 (any UTF character) can be
121445 ** part of a token.  In other words, delimiters all must have
121446 ** values of 0x7f or lower.
121447 */
121448 static const char porterIdChar[] = {
121449 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
121450     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
121451     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
121452     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
121453     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
121454     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
121455 };
121456 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
121457 
121458 /*
121459 ** Extract the next token from a tokenization cursor.  The cursor must
121460 ** have been opened by a prior call to porterOpen().
121461 */
121462 static int porterNext(
121463   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
121464   const char **pzToken,               /* OUT: *pzToken is the token text */
121465   int *pnBytes,                       /* OUT: Number of bytes in token */
121466   int *piStartOffset,                 /* OUT: Starting offset of token */
121467   int *piEndOffset,                   /* OUT: Ending offset of token */
121468   int *piPosition                     /* OUT: Position integer of token */
121469 ){
121470   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
121471   const char *z = c->zInput;
121472 
121473   while( c->iOffset<c->nInput ){
121474     int iStartOffset, ch;
121475 
121476     /* Scan past delimiter characters */
121477     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
121478       c->iOffset++;
121479     }
121480 
121481     /* Count non-delimiter characters. */
121482     iStartOffset = c->iOffset;
121483     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
121484       c->iOffset++;
121485     }
121486 
121487     if( c->iOffset>iStartOffset ){
121488       int n = c->iOffset-iStartOffset;
121489       if( n>c->nAllocated ){
121490         char *pNew;
121491         c->nAllocated = n+20;
121492         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
121493         if( !pNew ) return SQLITE_NOMEM;
121494         c->zToken = pNew;
121495       }
121496       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
121497       *pzToken = c->zToken;
121498       *piStartOffset = iStartOffset;
121499       *piEndOffset = c->iOffset;
121500       *piPosition = c->iToken++;
121501       return SQLITE_OK;
121502     }
121503   }
121504   return SQLITE_DONE;
121505 }
121506 
121507 /*
121508 ** The set of routines that implement the porter-stemmer tokenizer
121509 */
121510 static const sqlite3_tokenizer_module porterTokenizerModule = {
121511   0,
121512   porterCreate,
121513   porterDestroy,
121514   porterOpen,
121515   porterClose,
121516   porterNext,
121517 };
121518 
121519 /*
121520 ** Allocate a new porter tokenizer.  Return a pointer to the new
121521 ** tokenizer in *ppModule
121522 */
121523 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
121524   sqlite3_tokenizer_module const**ppModule
121525 ){
121526   *ppModule = &porterTokenizerModule;
121527 }
121528 
121529 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
121530 
121531 /************** End of fts3_porter.c *****************************************/
121532 /************** Begin file fts3_tokenizer.c **********************************/
121533 /*
121534 ** 2007 June 22
121535 **
121536 ** The author disclaims copyright to this source code.  In place of
121537 ** a legal notice, here is a blessing:
121538 **
121539 **    May you do good and not evil.
121540 **    May you find forgiveness for yourself and forgive others.
121541 **    May you share freely, never taking more than you give.
121542 **
121543 ******************************************************************************
121544 **
121545 ** This is part of an SQLite module implementing full-text search.
121546 ** This particular file implements the generic tokenizer interface.
121547 */
121548 
121549 /*
121550 ** The code in this file is only compiled if:
121551 **
121552 **     * The FTS3 module is being built as an extension
121553 **       (in which case SQLITE_CORE is not defined), or
121554 **
121555 **     * The FTS3 module is being built into the core of
121556 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
121557 */
121558 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121559 
121560 /* #include <assert.h> */
121561 /* #include <string.h> */
121562 
121563 /*
121564 ** Implementation of the SQL scalar function for accessing the underlying
121565 ** hash table. This function may be called as follows:
121566 **
121567 **   SELECT <function-name>(<key-name>);
121568 **   SELECT <function-name>(<key-name>, <pointer>);
121569 **
121570 ** where <function-name> is the name passed as the second argument
121571 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
121572 **
121573 ** If the <pointer> argument is specified, it must be a blob value
121574 ** containing a pointer to be stored as the hash data corresponding
121575 ** to the string <key-name>. If <pointer> is not specified, then
121576 ** the string <key-name> must already exist in the has table. Otherwise,
121577 ** an error is returned.
121578 **
121579 ** Whether or not the <pointer> argument is specified, the value returned
121580 ** is a blob containing the pointer stored as the hash data corresponding
121581 ** to string <key-name> (after the hash-table is updated, if applicable).
121582 */
121583 static void scalarFunc(
121584   sqlite3_context *context,
121585   int argc,
121586   sqlite3_value **argv
121587 ){
121588   Fts3Hash *pHash;
121589   void *pPtr = 0;
121590   const unsigned char *zName;
121591   int nName;
121592 
121593   assert( argc==1 || argc==2 );
121594 
121595   pHash = (Fts3Hash *)sqlite3_user_data(context);
121596 
121597   zName = sqlite3_value_text(argv[0]);
121598   nName = sqlite3_value_bytes(argv[0])+1;
121599 
121600   if( argc==2 ){
121601     void *pOld;
121602     int n = sqlite3_value_bytes(argv[1]);
121603     if( n!=sizeof(pPtr) ){
121604       sqlite3_result_error(context, "argument type mismatch", -1);
121605       return;
121606     }
121607     pPtr = *(void **)sqlite3_value_blob(argv[1]);
121608     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
121609     if( pOld==pPtr ){
121610       sqlite3_result_error(context, "out of memory", -1);
121611       return;
121612     }
121613   }else{
121614     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
121615     if( !pPtr ){
121616       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
121617       sqlite3_result_error(context, zErr, -1);
121618       sqlite3_free(zErr);
121619       return;
121620     }
121621   }
121622 
121623   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
121624 }
121625 
121626 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
121627   static const char isFtsIdChar[] = {
121628       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
121629       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
121630       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
121631       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
121632       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
121633       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
121634       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
121635       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
121636   };
121637   return (c&0x80 || isFtsIdChar[(int)(c)]);
121638 }
121639 
121640 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
121641   const char *z1;
121642   const char *z2 = 0;
121643 
121644   /* Find the start of the next token. */
121645   z1 = zStr;
121646   while( z2==0 ){
121647     char c = *z1;
121648     switch( c ){
121649       case '\0': return 0;        /* No more tokens here */
121650       case '\'':
121651       case '"':
121652       case '`': {
121653         z2 = z1;
121654         while( *++z2 && (*z2!=c || *++z2==c) );
121655         break;
121656       }
121657       case '[':
121658         z2 = &z1[1];
121659         while( *z2 && z2[0]!=']' ) z2++;
121660         if( *z2 ) z2++;
121661         break;
121662 
121663       default:
121664         if( sqlite3Fts3IsIdChar(*z1) ){
121665           z2 = &z1[1];
121666           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
121667         }else{
121668           z1++;
121669         }
121670     }
121671   }
121672 
121673   *pn = (int)(z2-z1);
121674   return z1;
121675 }
121676 
121677 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
121678   Fts3Hash *pHash,                /* Tokenizer hash table */
121679   const char *zArg,               /* Tokenizer name */
121680   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
121681   char **pzErr                    /* OUT: Set to malloced error message */
121682 ){
121683   int rc;
121684   char *z = (char *)zArg;
121685   int n = 0;
121686   char *zCopy;
121687   char *zEnd;                     /* Pointer to nul-term of zCopy */
121688   sqlite3_tokenizer_module *m;
121689 
121690   zCopy = sqlite3_mprintf("%s", zArg);
121691   if( !zCopy ) return SQLITE_NOMEM;
121692   zEnd = &zCopy[strlen(zCopy)];
121693 
121694   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
121695   z[n] = '\0';
121696   sqlite3Fts3Dequote(z);
121697 
121698   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
121699   if( !m ){
121700     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
121701     rc = SQLITE_ERROR;
121702   }else{
121703     char const **aArg = 0;
121704     int iArg = 0;
121705     z = &z[n+1];
121706     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
121707       int nNew = sizeof(char *)*(iArg+1);
121708       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
121709       if( !aNew ){
121710         sqlite3_free(zCopy);
121711         sqlite3_free((void *)aArg);
121712         return SQLITE_NOMEM;
121713       }
121714       aArg = aNew;
121715       aArg[iArg++] = z;
121716       z[n] = '\0';
121717       sqlite3Fts3Dequote(z);
121718       z = &z[n+1];
121719     }
121720     rc = m->xCreate(iArg, aArg, ppTok);
121721     assert( rc!=SQLITE_OK || *ppTok );
121722     if( rc!=SQLITE_OK ){
121723       *pzErr = sqlite3_mprintf("unknown tokenizer");
121724     }else{
121725       (*ppTok)->pModule = m;
121726     }
121727     sqlite3_free((void *)aArg);
121728   }
121729 
121730   sqlite3_free(zCopy);
121731   return rc;
121732 }
121733 
121734 
121735 #ifdef SQLITE_TEST
121736 
121737 /* #include <tcl.h> */
121738 /* #include <string.h> */
121739 
121740 /*
121741 ** Implementation of a special SQL scalar function for testing tokenizers
121742 ** designed to be used in concert with the Tcl testing framework. This
121743 ** function must be called with two arguments:
121744 **
121745 **   SELECT <function-name>(<key-name>, <input-string>);
121746 **   SELECT <function-name>(<key-name>, <pointer>);
121747 **
121748 ** where <function-name> is the name passed as the second argument
121749 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
121750 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
121751 **
121752 ** The return value is a string that may be interpreted as a Tcl
121753 ** list. For each token in the <input-string>, three elements are
121754 ** added to the returned list. The first is the token position, the
121755 ** second is the token text (folded, stemmed, etc.) and the third is the
121756 ** substring of <input-string> associated with the token. For example,
121757 ** using the built-in "simple" tokenizer:
121758 **
121759 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
121760 **
121761 ** will return the string:
121762 **
121763 **   "{0 i I 1 dont don't 2 see see 3 how how}"
121764 **
121765 */
121766 static void testFunc(
121767   sqlite3_context *context,
121768   int argc,
121769   sqlite3_value **argv
121770 ){
121771   Fts3Hash *pHash;
121772   sqlite3_tokenizer_module *p;
121773   sqlite3_tokenizer *pTokenizer = 0;
121774   sqlite3_tokenizer_cursor *pCsr = 0;
121775 
121776   const char *zErr = 0;
121777 
121778   const char *zName;
121779   int nName;
121780   const char *zInput;
121781   int nInput;
121782 
121783   const char *zArg = 0;
121784 
121785   const char *zToken;
121786   int nToken;
121787   int iStart;
121788   int iEnd;
121789   int iPos;
121790 
121791   Tcl_Obj *pRet;
121792 
121793   assert( argc==2 || argc==3 );
121794 
121795   nName = sqlite3_value_bytes(argv[0]);
121796   zName = (const char *)sqlite3_value_text(argv[0]);
121797   nInput = sqlite3_value_bytes(argv[argc-1]);
121798   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
121799 
121800   if( argc==3 ){
121801     zArg = (const char *)sqlite3_value_text(argv[1]);
121802   }
121803 
121804   pHash = (Fts3Hash *)sqlite3_user_data(context);
121805   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
121806 
121807   if( !p ){
121808     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
121809     sqlite3_result_error(context, zErr, -1);
121810     sqlite3_free(zErr);
121811     return;
121812   }
121813 
121814   pRet = Tcl_NewObj();
121815   Tcl_IncrRefCount(pRet);
121816 
121817   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
121818     zErr = "error in xCreate()";
121819     goto finish;
121820   }
121821   pTokenizer->pModule = p;
121822   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
121823     zErr = "error in xOpen()";
121824     goto finish;
121825   }
121826   pCsr->pTokenizer = pTokenizer;
121827 
121828   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
121829     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
121830     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
121831     zToken = &zInput[iStart];
121832     nToken = iEnd-iStart;
121833     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
121834   }
121835 
121836   if( SQLITE_OK!=p->xClose(pCsr) ){
121837     zErr = "error in xClose()";
121838     goto finish;
121839   }
121840   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
121841     zErr = "error in xDestroy()";
121842     goto finish;
121843   }
121844 
121845 finish:
121846   if( zErr ){
121847     sqlite3_result_error(context, zErr, -1);
121848   }else{
121849     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
121850   }
121851   Tcl_DecrRefCount(pRet);
121852 }
121853 
121854 static
121855 int registerTokenizer(
121856   sqlite3 *db,
121857   char *zName,
121858   const sqlite3_tokenizer_module *p
121859 ){
121860   int rc;
121861   sqlite3_stmt *pStmt;
121862   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
121863 
121864   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
121865   if( rc!=SQLITE_OK ){
121866     return rc;
121867   }
121868 
121869   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
121870   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
121871   sqlite3_step(pStmt);
121872 
121873   return sqlite3_finalize(pStmt);
121874 }
121875 
121876 static
121877 int queryTokenizer(
121878   sqlite3 *db,
121879   char *zName,
121880   const sqlite3_tokenizer_module **pp
121881 ){
121882   int rc;
121883   sqlite3_stmt *pStmt;
121884   const char zSql[] = "SELECT fts3_tokenizer(?)";
121885 
121886   *pp = 0;
121887   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
121888   if( rc!=SQLITE_OK ){
121889     return rc;
121890   }
121891 
121892   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
121893   if( SQLITE_ROW==sqlite3_step(pStmt) ){
121894     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
121895       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
121896     }
121897   }
121898 
121899   return sqlite3_finalize(pStmt);
121900 }
121901 
121902 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
121903 
121904 /*
121905 ** Implementation of the scalar function fts3_tokenizer_internal_test().
121906 ** This function is used for testing only, it is not included in the
121907 ** build unless SQLITE_TEST is defined.
121908 **
121909 ** The purpose of this is to test that the fts3_tokenizer() function
121910 ** can be used as designed by the C-code in the queryTokenizer and
121911 ** registerTokenizer() functions above. These two functions are repeated
121912 ** in the README.tokenizer file as an example, so it is important to
121913 ** test them.
121914 **
121915 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
121916 ** function with no arguments. An assert() will fail if a problem is
121917 ** detected. i.e.:
121918 **
121919 **     SELECT fts3_tokenizer_internal_test();
121920 **
121921 */
121922 static void intTestFunc(
121923   sqlite3_context *context,
121924   int argc,
121925   sqlite3_value **argv
121926 ){
121927   int rc;
121928   const sqlite3_tokenizer_module *p1;
121929   const sqlite3_tokenizer_module *p2;
121930   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
121931 
121932   UNUSED_PARAMETER(argc);
121933   UNUSED_PARAMETER(argv);
121934 
121935   /* Test the query function */
121936   sqlite3Fts3SimpleTokenizerModule(&p1);
121937   rc = queryTokenizer(db, "simple", &p2);
121938   assert( rc==SQLITE_OK );
121939   assert( p1==p2 );
121940   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
121941   assert( rc==SQLITE_ERROR );
121942   assert( p2==0 );
121943   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
121944 
121945   /* Test the storage function */
121946   rc = registerTokenizer(db, "nosuchtokenizer", p1);
121947   assert( rc==SQLITE_OK );
121948   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
121949   assert( rc==SQLITE_OK );
121950   assert( p2==p1 );
121951 
121952   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
121953 }
121954 
121955 #endif
121956 
121957 /*
121958 ** Set up SQL objects in database db used to access the contents of
121959 ** the hash table pointed to by argument pHash. The hash table must
121960 ** been initialised to use string keys, and to take a private copy
121961 ** of the key when a value is inserted. i.e. by a call similar to:
121962 **
121963 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
121964 **
121965 ** This function adds a scalar function (see header comment above
121966 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
121967 ** defined at compilation time, a temporary virtual table (see header
121968 ** comment above struct HashTableVtab) to the database schema. Both
121969 ** provide read/write access to the contents of *pHash.
121970 **
121971 ** The third argument to this function, zName, is used as the name
121972 ** of both the scalar and, if created, the virtual table.
121973 */
121974 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
121975   sqlite3 *db,
121976   Fts3Hash *pHash,
121977   const char *zName
121978 ){
121979   int rc = SQLITE_OK;
121980   void *p = (void *)pHash;
121981   const int any = SQLITE_ANY;
121982 
121983 #ifdef SQLITE_TEST
121984   char *zTest = 0;
121985   char *zTest2 = 0;
121986   void *pdb = (void *)db;
121987   zTest = sqlite3_mprintf("%s_test", zName);
121988   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
121989   if( !zTest || !zTest2 ){
121990     rc = SQLITE_NOMEM;
121991   }
121992 #endif
121993 
121994   if( SQLITE_OK==rc ){
121995     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
121996   }
121997   if( SQLITE_OK==rc ){
121998     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
121999   }
122000 #ifdef SQLITE_TEST
122001   if( SQLITE_OK==rc ){
122002     rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
122003   }
122004   if( SQLITE_OK==rc ){
122005     rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
122006   }
122007   if( SQLITE_OK==rc ){
122008     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
122009   }
122010 #endif
122011 
122012 #ifdef SQLITE_TEST
122013   sqlite3_free(zTest);
122014   sqlite3_free(zTest2);
122015 #endif
122016 
122017   return rc;
122018 }
122019 
122020 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122021 
122022 /************** End of fts3_tokenizer.c **************************************/
122023 /************** Begin file fts3_tokenizer1.c *********************************/
122024 /*
122025 ** 2006 Oct 10
122026 **
122027 ** The author disclaims copyright to this source code.  In place of
122028 ** a legal notice, here is a blessing:
122029 **
122030 **    May you do good and not evil.
122031 **    May you find forgiveness for yourself and forgive others.
122032 **    May you share freely, never taking more than you give.
122033 **
122034 ******************************************************************************
122035 **
122036 ** Implementation of the "simple" full-text-search tokenizer.
122037 */
122038 
122039 /*
122040 ** The code in this file is only compiled if:
122041 **
122042 **     * The FTS3 module is being built as an extension
122043 **       (in which case SQLITE_CORE is not defined), or
122044 **
122045 **     * The FTS3 module is being built into the core of
122046 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
122047 */
122048 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122049 
122050 /* #include <assert.h> */
122051 /* #include <stdlib.h> */
122052 /* #include <stdio.h> */
122053 /* #include <string.h> */
122054 
122055 
122056 typedef struct simple_tokenizer {
122057   sqlite3_tokenizer base;
122058   char delim[128];             /* flag ASCII delimiters */
122059 } simple_tokenizer;
122060 
122061 typedef struct simple_tokenizer_cursor {
122062   sqlite3_tokenizer_cursor base;
122063   const char *pInput;          /* input we are tokenizing */
122064   int nBytes;                  /* size of the input */
122065   int iOffset;                 /* current position in pInput */
122066   int iToken;                  /* index of next token to be returned */
122067   char *pToken;                /* storage for current token */
122068   int nTokenAllocated;         /* space allocated to zToken buffer */
122069 } simple_tokenizer_cursor;
122070 
122071 
122072 static int simpleDelim(simple_tokenizer *t, unsigned char c){
122073   return c<0x80 && t->delim[c];
122074 }
122075 static int fts3_isalnum(int x){
122076   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
122077 }
122078 
122079 /*
122080 ** Create a new tokenizer instance.
122081 */
122082 static int simpleCreate(
122083   int argc, const char * const *argv,
122084   sqlite3_tokenizer **ppTokenizer
122085 ){
122086   simple_tokenizer *t;
122087 
122088   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
122089   if( t==NULL ) return SQLITE_NOMEM;
122090   memset(t, 0, sizeof(*t));
122091 
122092   /* TODO(shess) Delimiters need to remain the same from run to run,
122093   ** else we need to reindex.  One solution would be a meta-table to
122094   ** track such information in the database, then we'd only want this
122095   ** information on the initial create.
122096   */
122097   if( argc>1 ){
122098     int i, n = (int)strlen(argv[1]);
122099     for(i=0; i<n; i++){
122100       unsigned char ch = argv[1][i];
122101       /* We explicitly don't support UTF-8 delimiters for now. */
122102       if( ch>=0x80 ){
122103         sqlite3_free(t);
122104         return SQLITE_ERROR;
122105       }
122106       t->delim[ch] = 1;
122107     }
122108   } else {
122109     /* Mark non-alphanumeric ASCII characters as delimiters */
122110     int i;
122111     for(i=1; i<0x80; i++){
122112       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
122113     }
122114   }
122115 
122116   *ppTokenizer = &t->base;
122117   return SQLITE_OK;
122118 }
122119 
122120 /*
122121 ** Destroy a tokenizer
122122 */
122123 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
122124   sqlite3_free(pTokenizer);
122125   return SQLITE_OK;
122126 }
122127 
122128 /*
122129 ** Prepare to begin tokenizing a particular string.  The input
122130 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
122131 ** used to incrementally tokenize this string is returned in
122132 ** *ppCursor.
122133 */
122134 static int simpleOpen(
122135   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
122136   const char *pInput, int nBytes,        /* String to be tokenized */
122137   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
122138 ){
122139   simple_tokenizer_cursor *c;
122140 
122141   UNUSED_PARAMETER(pTokenizer);
122142 
122143   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
122144   if( c==NULL ) return SQLITE_NOMEM;
122145 
122146   c->pInput = pInput;
122147   if( pInput==0 ){
122148     c->nBytes = 0;
122149   }else if( nBytes<0 ){
122150     c->nBytes = (int)strlen(pInput);
122151   }else{
122152     c->nBytes = nBytes;
122153   }
122154   c->iOffset = 0;                 /* start tokenizing at the beginning */
122155   c->iToken = 0;
122156   c->pToken = NULL;               /* no space allocated, yet. */
122157   c->nTokenAllocated = 0;
122158 
122159   *ppCursor = &c->base;
122160   return SQLITE_OK;
122161 }
122162 
122163 /*
122164 ** Close a tokenization cursor previously opened by a call to
122165 ** simpleOpen() above.
122166 */
122167 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
122168   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
122169   sqlite3_free(c->pToken);
122170   sqlite3_free(c);
122171   return SQLITE_OK;
122172 }
122173 
122174 /*
122175 ** Extract the next token from a tokenization cursor.  The cursor must
122176 ** have been opened by a prior call to simpleOpen().
122177 */
122178 static int simpleNext(
122179   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
122180   const char **ppToken,               /* OUT: *ppToken is the token text */
122181   int *pnBytes,                       /* OUT: Number of bytes in token */
122182   int *piStartOffset,                 /* OUT: Starting offset of token */
122183   int *piEndOffset,                   /* OUT: Ending offset of token */
122184   int *piPosition                     /* OUT: Position integer of token */
122185 ){
122186   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
122187   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
122188   unsigned char *p = (unsigned char *)c->pInput;
122189 
122190   while( c->iOffset<c->nBytes ){
122191     int iStartOffset;
122192 
122193     /* Scan past delimiter characters */
122194     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
122195       c->iOffset++;
122196     }
122197 
122198     /* Count non-delimiter characters. */
122199     iStartOffset = c->iOffset;
122200     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
122201       c->iOffset++;
122202     }
122203 
122204     if( c->iOffset>iStartOffset ){
122205       int i, n = c->iOffset-iStartOffset;
122206       if( n>c->nTokenAllocated ){
122207         char *pNew;
122208         c->nTokenAllocated = n+20;
122209         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
122210         if( !pNew ) return SQLITE_NOMEM;
122211         c->pToken = pNew;
122212       }
122213       for(i=0; i<n; i++){
122214         /* TODO(shess) This needs expansion to handle UTF-8
122215         ** case-insensitivity.
122216         */
122217         unsigned char ch = p[iStartOffset+i];
122218         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
122219       }
122220       *ppToken = c->pToken;
122221       *pnBytes = n;
122222       *piStartOffset = iStartOffset;
122223       *piEndOffset = c->iOffset;
122224       *piPosition = c->iToken++;
122225 
122226       return SQLITE_OK;
122227     }
122228   }
122229   return SQLITE_DONE;
122230 }
122231 
122232 /*
122233 ** The set of routines that implement the simple tokenizer
122234 */
122235 static const sqlite3_tokenizer_module simpleTokenizerModule = {
122236   0,
122237   simpleCreate,
122238   simpleDestroy,
122239   simpleOpen,
122240   simpleClose,
122241   simpleNext,
122242 };
122243 
122244 /*
122245 ** Allocate a new simple tokenizer.  Return a pointer to the new
122246 ** tokenizer in *ppModule
122247 */
122248 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
122249   sqlite3_tokenizer_module const**ppModule
122250 ){
122251   *ppModule = &simpleTokenizerModule;
122252 }
122253 
122254 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122255 
122256 /************** End of fts3_tokenizer1.c *************************************/
122257 /************** Begin file fts3_write.c **************************************/
122258 /*
122259 ** 2009 Oct 23
122260 **
122261 ** The author disclaims copyright to this source code.  In place of
122262 ** a legal notice, here is a blessing:
122263 **
122264 **    May you do good and not evil.
122265 **    May you find forgiveness for yourself and forgive others.
122266 **    May you share freely, never taking more than you give.
122267 **
122268 ******************************************************************************
122269 **
122270 ** This file is part of the SQLite FTS3 extension module. Specifically,
122271 ** this file contains code to insert, update and delete rows from FTS3
122272 ** tables. It also contains code to merge FTS3 b-tree segments. Some
122273 ** of the sub-routines used to merge segments are also used by the query
122274 ** code in fts3.c.
122275 */
122276 
122277 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122278 
122279 /* #include <string.h> */
122280 /* #include <assert.h> */
122281 /* #include <stdlib.h> */
122282 
122283 /*
122284 ** When full-text index nodes are loaded from disk, the buffer that they
122285 ** are loaded into has the following number of bytes of padding at the end
122286 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
122287 ** of 920 bytes is allocated for it.
122288 **
122289 ** This means that if we have a pointer into a buffer containing node data,
122290 ** it is always safe to read up to two varints from it without risking an
122291 ** overread, even if the node data is corrupted.
122292 */
122293 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
122294 
122295 /*
122296 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
122297 ** memory incrementally instead of all at once. This can be a big performance
122298 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
122299 ** method before retrieving all query results (as may happen, for example,
122300 ** if a query has a LIMIT clause).
122301 **
122302 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
122303 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
122304 ** The code is written so that the hard lower-limit for each of these values
122305 ** is 1. Clearly such small values would be inefficient, but can be useful
122306 ** for testing purposes.
122307 **
122308 ** If this module is built with SQLITE_TEST defined, these constants may
122309 ** be overridden at runtime for testing purposes. File fts3_test.c contains
122310 ** a Tcl interface to read and write the values.
122311 */
122312 #ifdef SQLITE_TEST
122313 int test_fts3_node_chunksize = (4*1024);
122314 int test_fts3_node_chunk_threshold = (4*1024)*4;
122315 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
122316 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
122317 #else
122318 # define FTS3_NODE_CHUNKSIZE (4*1024)
122319 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
122320 #endif
122321 
122322 typedef struct PendingList PendingList;
122323 typedef struct SegmentNode SegmentNode;
122324 typedef struct SegmentWriter SegmentWriter;
122325 
122326 /*
122327 ** An instance of the following data structure is used to build doclists
122328 ** incrementally. See function fts3PendingListAppend() for details.
122329 */
122330 struct PendingList {
122331   int nData;
122332   char *aData;
122333   int nSpace;
122334   sqlite3_int64 iLastDocid;
122335   sqlite3_int64 iLastCol;
122336   sqlite3_int64 iLastPos;
122337 };
122338 
122339 
122340 /*
122341 ** Each cursor has a (possibly empty) linked list of the following objects.
122342 */
122343 struct Fts3DeferredToken {
122344   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
122345   int iCol;                       /* Column token must occur in */
122346   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
122347   PendingList *pList;             /* Doclist is assembled here */
122348 };
122349 
122350 /*
122351 ** An instance of this structure is used to iterate through the terms on
122352 ** a contiguous set of segment b-tree leaf nodes. Although the details of
122353 ** this structure are only manipulated by code in this file, opaque handles
122354 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
122355 ** terms when querying the full-text index. See functions:
122356 **
122357 **   sqlite3Fts3SegReaderNew()
122358 **   sqlite3Fts3SegReaderFree()
122359 **   sqlite3Fts3SegReaderIterate()
122360 **
122361 ** Methods used to manipulate Fts3SegReader structures:
122362 **
122363 **   fts3SegReaderNext()
122364 **   fts3SegReaderFirstDocid()
122365 **   fts3SegReaderNextDocid()
122366 */
122367 struct Fts3SegReader {
122368   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
122369 
122370   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
122371   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
122372   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
122373   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
122374 
122375   char *aNode;                    /* Pointer to node data (or NULL) */
122376   int nNode;                      /* Size of buffer at aNode (or 0) */
122377   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
122378   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
122379 
122380   Fts3HashElem **ppNextElem;
122381 
122382   /* Variables set by fts3SegReaderNext(). These may be read directly
122383   ** by the caller. They are valid from the time SegmentReaderNew() returns
122384   ** until SegmentReaderNext() returns something other than SQLITE_OK
122385   ** (i.e. SQLITE_DONE).
122386   */
122387   int nTerm;                      /* Number of bytes in current term */
122388   char *zTerm;                    /* Pointer to current term */
122389   int nTermAlloc;                 /* Allocated size of zTerm buffer */
122390   char *aDoclist;                 /* Pointer to doclist of current entry */
122391   int nDoclist;                   /* Size of doclist in current entry */
122392 
122393   /* The following variables are used by fts3SegReaderNextDocid() to iterate
122394   ** through the current doclist (aDoclist/nDoclist).
122395   */
122396   char *pOffsetList;
122397   int nOffsetList;                /* For descending pending seg-readers only */
122398   sqlite3_int64 iDocid;
122399 };
122400 
122401 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
122402 #define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
122403 
122404 /*
122405 ** An instance of this structure is used to create a segment b-tree in the
122406 ** database. The internal details of this type are only accessed by the
122407 ** following functions:
122408 **
122409 **   fts3SegWriterAdd()
122410 **   fts3SegWriterFlush()
122411 **   fts3SegWriterFree()
122412 */
122413 struct SegmentWriter {
122414   SegmentNode *pTree;             /* Pointer to interior tree structure */
122415   sqlite3_int64 iFirst;           /* First slot in %_segments written */
122416   sqlite3_int64 iFree;            /* Next free slot in %_segments */
122417   char *zTerm;                    /* Pointer to previous term buffer */
122418   int nTerm;                      /* Number of bytes in zTerm */
122419   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
122420   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
122421   int nSize;                      /* Size of allocation at aData */
122422   int nData;                      /* Bytes of data in aData */
122423   char *aData;                    /* Pointer to block from malloc() */
122424 };
122425 
122426 /*
122427 ** Type SegmentNode is used by the following three functions to create
122428 ** the interior part of the segment b+-tree structures (everything except
122429 ** the leaf nodes). These functions and type are only ever used by code
122430 ** within the fts3SegWriterXXX() family of functions described above.
122431 **
122432 **   fts3NodeAddTerm()
122433 **   fts3NodeWrite()
122434 **   fts3NodeFree()
122435 **
122436 ** When a b+tree is written to the database (either as a result of a merge
122437 ** or the pending-terms table being flushed), leaves are written into the
122438 ** database file as soon as they are completely populated. The interior of
122439 ** the tree is assembled in memory and written out only once all leaves have
122440 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
122441 ** very large, meaning that the interior of the tree consumes relatively
122442 ** little memory.
122443 */
122444 struct SegmentNode {
122445   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
122446   SegmentNode *pRight;            /* Pointer to right-sibling */
122447   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
122448   int nEntry;                     /* Number of terms written to node so far */
122449   char *zTerm;                    /* Pointer to previous term buffer */
122450   int nTerm;                      /* Number of bytes in zTerm */
122451   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
122452   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
122453   int nData;                      /* Bytes of valid data so far */
122454   char *aData;                    /* Node data */
122455 };
122456 
122457 /*
122458 ** Valid values for the second argument to fts3SqlStmt().
122459 */
122460 #define SQL_DELETE_CONTENT             0
122461 #define SQL_IS_EMPTY                   1
122462 #define SQL_DELETE_ALL_CONTENT         2
122463 #define SQL_DELETE_ALL_SEGMENTS        3
122464 #define SQL_DELETE_ALL_SEGDIR          4
122465 #define SQL_DELETE_ALL_DOCSIZE         5
122466 #define SQL_DELETE_ALL_STAT            6
122467 #define SQL_SELECT_CONTENT_BY_ROWID    7
122468 #define SQL_NEXT_SEGMENT_INDEX         8
122469 #define SQL_INSERT_SEGMENTS            9
122470 #define SQL_NEXT_SEGMENTS_ID          10
122471 #define SQL_INSERT_SEGDIR             11
122472 #define SQL_SELECT_LEVEL              12
122473 #define SQL_SELECT_LEVEL_RANGE        13
122474 #define SQL_SELECT_LEVEL_COUNT        14
122475 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
122476 #define SQL_DELETE_SEGDIR_LEVEL       16
122477 #define SQL_DELETE_SEGMENTS_RANGE     17
122478 #define SQL_CONTENT_INSERT            18
122479 #define SQL_DELETE_DOCSIZE            19
122480 #define SQL_REPLACE_DOCSIZE           20
122481 #define SQL_SELECT_DOCSIZE            21
122482 #define SQL_SELECT_DOCTOTAL           22
122483 #define SQL_REPLACE_DOCTOTAL          23
122484 
122485 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
122486 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
122487 
122488 #define SQL_DELETE_SEGDIR_RANGE       26
122489 
122490 /*
122491 ** This function is used to obtain an SQLite prepared statement handle
122492 ** for the statement identified by the second argument. If successful,
122493 ** *pp is set to the requested statement handle and SQLITE_OK returned.
122494 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
122495 **
122496 ** If argument apVal is not NULL, then it must point to an array with
122497 ** at least as many entries as the requested statement has bound
122498 ** parameters. The values are bound to the statements parameters before
122499 ** returning.
122500 */
122501 static int fts3SqlStmt(
122502   Fts3Table *p,                   /* Virtual table handle */
122503   int eStmt,                      /* One of the SQL_XXX constants above */
122504   sqlite3_stmt **pp,              /* OUT: Statement handle */
122505   sqlite3_value **apVal           /* Values to bind to statement */
122506 ){
122507   const char *azSql[] = {
122508 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
122509 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
122510 /* 2  */  "DELETE FROM %Q.'%q_content'",
122511 /* 3  */  "DELETE FROM %Q.'%q_segments'",
122512 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
122513 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
122514 /* 6  */  "DELETE FROM %Q.'%q_stat'",
122515 /* 7  */  "SELECT %s FROM %Q.'%q_content' AS x WHERE rowid=?",
122516 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
122517 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
122518 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
122519 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
122520 
122521           /* Return segments in order from oldest to newest.*/
122522 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
122523             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
122524 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
122525             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
122526             "ORDER BY level DESC, idx ASC",
122527 
122528 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
122529 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
122530 
122531 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
122532 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
122533 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
122534 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
122535 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
122536 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
122537 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
122538 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
122539 /* 24 */  "",
122540 /* 25 */  "",
122541 
122542 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
122543 
122544   };
122545   int rc = SQLITE_OK;
122546   sqlite3_stmt *pStmt;
122547 
122548   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
122549   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
122550 
122551   pStmt = p->aStmt[eStmt];
122552   if( !pStmt ){
122553     char *zSql;
122554     if( eStmt==SQL_CONTENT_INSERT ){
122555       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
122556     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
122557       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist, p->zDb, p->zName);
122558     }else{
122559       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
122560     }
122561     if( !zSql ){
122562       rc = SQLITE_NOMEM;
122563     }else{
122564       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
122565       sqlite3_free(zSql);
122566       assert( rc==SQLITE_OK || pStmt==0 );
122567       p->aStmt[eStmt] = pStmt;
122568     }
122569   }
122570   if( apVal ){
122571     int i;
122572     int nParam = sqlite3_bind_parameter_count(pStmt);
122573     for(i=0; rc==SQLITE_OK && i<nParam; i++){
122574       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
122575     }
122576   }
122577   *pp = pStmt;
122578   return rc;
122579 }
122580 
122581 static int fts3SelectDocsize(
122582   Fts3Table *pTab,                /* FTS3 table handle */
122583   int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
122584   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
122585   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
122586 ){
122587   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
122588   int rc;                         /* Return code */
122589 
122590   assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
122591 
122592   rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
122593   if( rc==SQLITE_OK ){
122594     if( eStmt==SQL_SELECT_DOCSIZE ){
122595       sqlite3_bind_int64(pStmt, 1, iDocid);
122596     }
122597     rc = sqlite3_step(pStmt);
122598     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
122599       rc = sqlite3_reset(pStmt);
122600       if( rc==SQLITE_OK ) rc = SQLITE_CORRUPT_VTAB;
122601       pStmt = 0;
122602     }else{
122603       rc = SQLITE_OK;
122604     }
122605   }
122606 
122607   *ppStmt = pStmt;
122608   return rc;
122609 }
122610 
122611 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
122612   Fts3Table *pTab,                /* Fts3 table handle */
122613   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
122614 ){
122615   return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
122616 }
122617 
122618 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
122619   Fts3Table *pTab,                /* Fts3 table handle */
122620   sqlite3_int64 iDocid,           /* Docid to read size data for */
122621   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
122622 ){
122623   return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
122624 }
122625 
122626 /*
122627 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
122628 ** array apVal[] to the SQL statement identified by eStmt, the statement
122629 ** is executed.
122630 **
122631 ** Returns SQLITE_OK if the statement is successfully executed, or an
122632 ** SQLite error code otherwise.
122633 */
122634 static void fts3SqlExec(
122635   int *pRC,                /* Result code */
122636   Fts3Table *p,            /* The FTS3 table */
122637   int eStmt,               /* Index of statement to evaluate */
122638   sqlite3_value **apVal    /* Parameters to bind */
122639 ){
122640   sqlite3_stmt *pStmt;
122641   int rc;
122642   if( *pRC ) return;
122643   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
122644   if( rc==SQLITE_OK ){
122645     sqlite3_step(pStmt);
122646     rc = sqlite3_reset(pStmt);
122647   }
122648   *pRC = rc;
122649 }
122650 
122651 
122652 /*
122653 ** This function ensures that the caller has obtained a shared-cache
122654 ** table-lock on the %_content table. This is required before reading
122655 ** data from the fts3 table. If this lock is not acquired first, then
122656 ** the caller may end up holding read-locks on the %_segments and %_segdir
122657 ** tables, but no read-lock on the %_content table. If this happens
122658 ** a second connection will be able to write to the fts3 table, but
122659 ** attempting to commit those writes might return SQLITE_LOCKED or
122660 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
122661 ** write-locks on the %_segments and %_segdir ** tables).
122662 **
122663 ** We try to avoid this because if FTS3 returns any error when committing
122664 ** a transaction, the whole transaction will be rolled back. And this is
122665 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
122666 ** still happen if the user reads data directly from the %_segments or
122667 ** %_segdir tables instead of going through FTS3 though.
122668 */
122669 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
122670   int rc;                         /* Return code */
122671   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
122672 
122673   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
122674   if( rc==SQLITE_OK ){
122675     sqlite3_bind_null(pStmt, 1);
122676     sqlite3_step(pStmt);
122677     rc = sqlite3_reset(pStmt);
122678   }
122679   return rc;
122680 }
122681 
122682 /*
122683 ** Set *ppStmt to a statement handle that may be used to iterate through
122684 ** all rows in the %_segdir table, from oldest to newest. If successful,
122685 ** return SQLITE_OK. If an error occurs while preparing the statement,
122686 ** return an SQLite error code.
122687 **
122688 ** There is only ever one instance of this SQL statement compiled for
122689 ** each FTS3 table.
122690 **
122691 ** The statement returns the following columns from the %_segdir table:
122692 **
122693 **   0: idx
122694 **   1: start_block
122695 **   2: leaves_end_block
122696 **   3: end_block
122697 **   4: root
122698 */
122699 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
122700   Fts3Table *p,                   /* FTS3 table */
122701   int iIndex,                     /* Index for p->aIndex[] */
122702   int iLevel,                     /* Level to select */
122703   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
122704 ){
122705   int rc;
122706   sqlite3_stmt *pStmt = 0;
122707 
122708   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
122709   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
122710   assert( iIndex>=0 && iIndex<p->nIndex );
122711 
122712   if( iLevel<0 ){
122713     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
122714     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
122715     if( rc==SQLITE_OK ){
122716       sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
122717       sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL-1);
122718     }
122719   }else{
122720     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
122721     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
122722     if( rc==SQLITE_OK ){
122723       sqlite3_bind_int(pStmt, 1, iLevel+iIndex*FTS3_SEGDIR_MAXLEVEL);
122724     }
122725   }
122726   *ppStmt = pStmt;
122727   return rc;
122728 }
122729 
122730 
122731 /*
122732 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
122733 ** if successful, or an SQLite error code otherwise.
122734 **
122735 ** This function also serves to allocate the PendingList structure itself.
122736 ** For example, to create a new PendingList structure containing two
122737 ** varints:
122738 **
122739 **   PendingList *p = 0;
122740 **   fts3PendingListAppendVarint(&p, 1);
122741 **   fts3PendingListAppendVarint(&p, 2);
122742 */
122743 static int fts3PendingListAppendVarint(
122744   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
122745   sqlite3_int64 i                 /* Value to append to data */
122746 ){
122747   PendingList *p = *pp;
122748 
122749   /* Allocate or grow the PendingList as required. */
122750   if( !p ){
122751     p = sqlite3_malloc(sizeof(*p) + 100);
122752     if( !p ){
122753       return SQLITE_NOMEM;
122754     }
122755     p->nSpace = 100;
122756     p->aData = (char *)&p[1];
122757     p->nData = 0;
122758   }
122759   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
122760     int nNew = p->nSpace * 2;
122761     p = sqlite3_realloc(p, sizeof(*p) + nNew);
122762     if( !p ){
122763       sqlite3_free(*pp);
122764       *pp = 0;
122765       return SQLITE_NOMEM;
122766     }
122767     p->nSpace = nNew;
122768     p->aData = (char *)&p[1];
122769   }
122770 
122771   /* Append the new serialized varint to the end of the list. */
122772   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
122773   p->aData[p->nData] = '\0';
122774   *pp = p;
122775   return SQLITE_OK;
122776 }
122777 
122778 /*
122779 ** Add a docid/column/position entry to a PendingList structure. Non-zero
122780 ** is returned if the structure is sqlite3_realloced as part of adding
122781 ** the entry. Otherwise, zero.
122782 **
122783 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
122784 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
122785 ** it is set to SQLITE_OK.
122786 */
122787 static int fts3PendingListAppend(
122788   PendingList **pp,               /* IN/OUT: PendingList structure */
122789   sqlite3_int64 iDocid,           /* Docid for entry to add */
122790   sqlite3_int64 iCol,             /* Column for entry to add */
122791   sqlite3_int64 iPos,             /* Position of term for entry to add */
122792   int *pRc                        /* OUT: Return code */
122793 ){
122794   PendingList *p = *pp;
122795   int rc = SQLITE_OK;
122796 
122797   assert( !p || p->iLastDocid<=iDocid );
122798 
122799   if( !p || p->iLastDocid!=iDocid ){
122800     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
122801     if( p ){
122802       assert( p->nData<p->nSpace );
122803       assert( p->aData[p->nData]==0 );
122804       p->nData++;
122805     }
122806     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
122807       goto pendinglistappend_out;
122808     }
122809     p->iLastCol = -1;
122810     p->iLastPos = 0;
122811     p->iLastDocid = iDocid;
122812   }
122813   if( iCol>0 && p->iLastCol!=iCol ){
122814     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
122815      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
122816     ){
122817       goto pendinglistappend_out;
122818     }
122819     p->iLastCol = iCol;
122820     p->iLastPos = 0;
122821   }
122822   if( iCol>=0 ){
122823     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
122824     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
122825     if( rc==SQLITE_OK ){
122826       p->iLastPos = iPos;
122827     }
122828   }
122829 
122830  pendinglistappend_out:
122831   *pRc = rc;
122832   if( p!=*pp ){
122833     *pp = p;
122834     return 1;
122835   }
122836   return 0;
122837 }
122838 
122839 /*
122840 ** Free a PendingList object allocated by fts3PendingListAppend().
122841 */
122842 static void fts3PendingListDelete(PendingList *pList){
122843   sqlite3_free(pList);
122844 }
122845 
122846 /*
122847 ** Add an entry to one of the pending-terms hash tables.
122848 */
122849 static int fts3PendingTermsAddOne(
122850   Fts3Table *p,
122851   int iCol,
122852   int iPos,
122853   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
122854   const char *zToken,
122855   int nToken
122856 ){
122857   PendingList *pList;
122858   int rc = SQLITE_OK;
122859 
122860   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
122861   if( pList ){
122862     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
122863   }
122864   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
122865     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
122866       /* Malloc failed while inserting the new entry. This can only
122867       ** happen if there was no previous entry for this token.
122868       */
122869       assert( 0==fts3HashFind(pHash, zToken, nToken) );
122870       sqlite3_free(pList);
122871       rc = SQLITE_NOMEM;
122872     }
122873   }
122874   if( rc==SQLITE_OK ){
122875     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
122876   }
122877   return rc;
122878 }
122879 
122880 /*
122881 ** Tokenize the nul-terminated string zText and add all tokens to the
122882 ** pending-terms hash-table. The docid used is that currently stored in
122883 ** p->iPrevDocid, and the column is specified by argument iCol.
122884 **
122885 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
122886 */
122887 static int fts3PendingTermsAdd(
122888   Fts3Table *p,                   /* Table into which text will be inserted */
122889   const char *zText,              /* Text of document to be inserted */
122890   int iCol,                       /* Column into which text is being inserted */
122891   u32 *pnWord                     /* OUT: Number of tokens inserted */
122892 ){
122893   int rc;
122894   int iStart;
122895   int iEnd;
122896   int iPos;
122897   int nWord = 0;
122898 
122899   char const *zToken;
122900   int nToken;
122901 
122902   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
122903   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122904   sqlite3_tokenizer_cursor *pCsr;
122905   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
122906       const char**,int*,int*,int*,int*);
122907 
122908   assert( pTokenizer && pModule );
122909 
122910   /* If the user has inserted a NULL value, this function may be called with
122911   ** zText==0. In this case, add zero token entries to the hash table and
122912   ** return early. */
122913   if( zText==0 ){
122914     *pnWord = 0;
122915     return SQLITE_OK;
122916   }
122917 
122918   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
122919   if( rc!=SQLITE_OK ){
122920     return rc;
122921   }
122922   pCsr->pTokenizer = pTokenizer;
122923 
122924   xNext = pModule->xNext;
122925   while( SQLITE_OK==rc
122926       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
122927   ){
122928     int i;
122929     if( iPos>=nWord ) nWord = iPos+1;
122930 
122931     /* Positions cannot be negative; we use -1 as a terminator internally.
122932     ** Tokens must have a non-zero length.
122933     */
122934     if( iPos<0 || !zToken || nToken<=0 ){
122935       rc = SQLITE_ERROR;
122936       break;
122937     }
122938 
122939     /* Add the term to the terms index */
122940     rc = fts3PendingTermsAddOne(
122941         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
122942     );
122943 
122944     /* Add the term to each of the prefix indexes that it is not too
122945     ** short for. */
122946     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
122947       struct Fts3Index *pIndex = &p->aIndex[i];
122948       if( nToken<pIndex->nPrefix ) continue;
122949       rc = fts3PendingTermsAddOne(
122950           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
122951       );
122952     }
122953   }
122954 
122955   pModule->xClose(pCsr);
122956   *pnWord = nWord;
122957   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
122958 }
122959 
122960 /*
122961 ** Calling this function indicates that subsequent calls to
122962 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
122963 ** contents of the document with docid iDocid.
122964 */
122965 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
122966   /* TODO(shess) Explore whether partially flushing the buffer on
122967   ** forced-flush would provide better performance.  I suspect that if
122968   ** we ordered the doclists by size and flushed the largest until the
122969   ** buffer was half empty, that would let the less frequent terms
122970   ** generate longer doclists.
122971   */
122972   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
122973     int rc = sqlite3Fts3PendingTermsFlush(p);
122974     if( rc!=SQLITE_OK ) return rc;
122975   }
122976   p->iPrevDocid = iDocid;
122977   return SQLITE_OK;
122978 }
122979 
122980 /*
122981 ** Discard the contents of the pending-terms hash tables.
122982 */
122983 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
122984   int i;
122985   for(i=0; i<p->nIndex; i++){
122986     Fts3HashElem *pElem;
122987     Fts3Hash *pHash = &p->aIndex[i].hPending;
122988     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
122989       PendingList *pList = (PendingList *)fts3HashData(pElem);
122990       fts3PendingListDelete(pList);
122991     }
122992     fts3HashClear(pHash);
122993   }
122994   p->nPendingData = 0;
122995 }
122996 
122997 /*
122998 ** This function is called by the xUpdate() method as part of an INSERT
122999 ** operation. It adds entries for each term in the new record to the
123000 ** pendingTerms hash table.
123001 **
123002 ** Argument apVal is the same as the similarly named argument passed to
123003 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
123004 */
123005 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
123006   int i;                          /* Iterator variable */
123007   for(i=2; i<p->nColumn+2; i++){
123008     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
123009     int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
123010     if( rc!=SQLITE_OK ){
123011       return rc;
123012     }
123013     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
123014   }
123015   return SQLITE_OK;
123016 }
123017 
123018 /*
123019 ** This function is called by the xUpdate() method for an INSERT operation.
123020 ** The apVal parameter is passed a copy of the apVal argument passed by
123021 ** SQLite to the xUpdate() method. i.e:
123022 **
123023 **   apVal[0]                Not used for INSERT.
123024 **   apVal[1]                rowid
123025 **   apVal[2]                Left-most user-defined column
123026 **   ...
123027 **   apVal[p->nColumn+1]     Right-most user-defined column
123028 **   apVal[p->nColumn+2]     Hidden column with same name as table
123029 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
123030 */
123031 static int fts3InsertData(
123032   Fts3Table *p,                   /* Full-text table */
123033   sqlite3_value **apVal,          /* Array of values to insert */
123034   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
123035 ){
123036   int rc;                         /* Return code */
123037   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
123038 
123039   /* Locate the statement handle used to insert data into the %_content
123040   ** table. The SQL for this statement is:
123041   **
123042   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
123043   **
123044   ** The statement features N '?' variables, where N is the number of user
123045   ** defined columns in the FTS3 table, plus one for the docid field.
123046   */
123047   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
123048   if( rc!=SQLITE_OK ){
123049     return rc;
123050   }
123051 
123052   /* There is a quirk here. The users INSERT statement may have specified
123053   ** a value for the "rowid" field, for the "docid" field, or for both.
123054   ** Which is a problem, since "rowid" and "docid" are aliases for the
123055   ** same value. For example:
123056   **
123057   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
123058   **
123059   ** In FTS3, this is an error. It is an error to specify non-NULL values
123060   ** for both docid and some other rowid alias.
123061   */
123062   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
123063     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
123064      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
123065     ){
123066       /* A rowid/docid conflict. */
123067       return SQLITE_ERROR;
123068     }
123069     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
123070     if( rc!=SQLITE_OK ) return rc;
123071   }
123072 
123073   /* Execute the statement to insert the record. Set *piDocid to the
123074   ** new docid value.
123075   */
123076   sqlite3_step(pContentInsert);
123077   rc = sqlite3_reset(pContentInsert);
123078 
123079   *piDocid = sqlite3_last_insert_rowid(p->db);
123080   return rc;
123081 }
123082 
123083 
123084 
123085 /*
123086 ** Remove all data from the FTS3 table. Clear the hash table containing
123087 ** pending terms.
123088 */
123089 static int fts3DeleteAll(Fts3Table *p){
123090   int rc = SQLITE_OK;             /* Return code */
123091 
123092   /* Discard the contents of the pending-terms hash table. */
123093   sqlite3Fts3PendingTermsClear(p);
123094 
123095   /* Delete everything from the %_content, %_segments and %_segdir tables. */
123096   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
123097   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
123098   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
123099   if( p->bHasDocsize ){
123100     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
123101   }
123102   if( p->bHasStat ){
123103     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
123104   }
123105   return rc;
123106 }
123107 
123108 /*
123109 ** The first element in the apVal[] array is assumed to contain the docid
123110 ** (an integer) of a row about to be deleted. Remove all terms from the
123111 ** full-text index.
123112 */
123113 static void fts3DeleteTerms(
123114   int *pRC,               /* Result code */
123115   Fts3Table *p,           /* The FTS table to delete from */
123116   sqlite3_value *pRowid,  /* The docid to be deleted */
123117   u32 *aSz                /* Sizes of deleted document written here */
123118 ){
123119   int rc;
123120   sqlite3_stmt *pSelect;
123121 
123122   if( *pRC ) return;
123123   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
123124   if( rc==SQLITE_OK ){
123125     if( SQLITE_ROW==sqlite3_step(pSelect) ){
123126       int i;
123127       for(i=1; i<=p->nColumn; i++){
123128         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
123129         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
123130         if( rc!=SQLITE_OK ){
123131           sqlite3_reset(pSelect);
123132           *pRC = rc;
123133           return;
123134         }
123135         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
123136       }
123137     }
123138     rc = sqlite3_reset(pSelect);
123139   }else{
123140     sqlite3_reset(pSelect);
123141   }
123142   *pRC = rc;
123143 }
123144 
123145 /*
123146 ** Forward declaration to account for the circular dependency between
123147 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
123148 */
123149 static int fts3SegmentMerge(Fts3Table *, int, int);
123150 
123151 /*
123152 ** This function allocates a new level iLevel index in the segdir table.
123153 ** Usually, indexes are allocated within a level sequentially starting
123154 ** with 0, so the allocated index is one greater than the value returned
123155 ** by:
123156 **
123157 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
123158 **
123159 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
123160 ** level, they are merged into a single level (iLevel+1) segment and the
123161 ** allocated index is 0.
123162 **
123163 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
123164 ** returned. Otherwise, an SQLite error code is returned.
123165 */
123166 static int fts3AllocateSegdirIdx(
123167   Fts3Table *p,
123168   int iIndex,                     /* Index for p->aIndex */
123169   int iLevel,
123170   int *piIdx
123171 ){
123172   int rc;                         /* Return Code */
123173   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
123174   int iNext = 0;                  /* Result of query pNextIdx */
123175 
123176   /* Set variable iNext to the next available segdir index at level iLevel. */
123177   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
123178   if( rc==SQLITE_OK ){
123179     sqlite3_bind_int(pNextIdx, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
123180     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
123181       iNext = sqlite3_column_int(pNextIdx, 0);
123182     }
123183     rc = sqlite3_reset(pNextIdx);
123184   }
123185 
123186   if( rc==SQLITE_OK ){
123187     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
123188     ** full, merge all segments in level iLevel into a single iLevel+1
123189     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
123190     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
123191     */
123192     if( iNext>=FTS3_MERGE_COUNT ){
123193       rc = fts3SegmentMerge(p, iIndex, iLevel);
123194       *piIdx = 0;
123195     }else{
123196       *piIdx = iNext;
123197     }
123198   }
123199 
123200   return rc;
123201 }
123202 
123203 /*
123204 ** The %_segments table is declared as follows:
123205 **
123206 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
123207 **
123208 ** This function reads data from a single row of the %_segments table. The
123209 ** specific row is identified by the iBlockid parameter. If paBlob is not
123210 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
123211 ** with the contents of the blob stored in the "block" column of the
123212 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
123213 ** to the size of the blob in bytes before returning.
123214 **
123215 ** If an error occurs, or the table does not contain the specified row,
123216 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
123217 ** paBlob is non-NULL, then it is the responsibility of the caller to
123218 ** eventually free the returned buffer.
123219 **
123220 ** This function may leave an open sqlite3_blob* handle in the
123221 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
123222 ** to this function. The handle may be closed by calling the
123223 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
123224 ** performance improvement, but the blob handle should always be closed
123225 ** before control is returned to the user (to prevent a lock being held
123226 ** on the database file for longer than necessary). Thus, any virtual table
123227 ** method (xFilter etc.) that may directly or indirectly call this function
123228 ** must call sqlite3Fts3SegmentsClose() before returning.
123229 */
123230 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
123231   Fts3Table *p,                   /* FTS3 table handle */
123232   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
123233   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
123234   int *pnBlob,                    /* OUT: Size of blob data */
123235   int *pnLoad                     /* OUT: Bytes actually loaded */
123236 ){
123237   int rc;                         /* Return code */
123238 
123239   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
123240   assert( pnBlob);
123241 
123242   if( p->pSegments ){
123243     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
123244   }else{
123245     if( 0==p->zSegmentsTbl ){
123246       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
123247       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
123248     }
123249     rc = sqlite3_blob_open(
123250        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
123251     );
123252   }
123253 
123254   if( rc==SQLITE_OK ){
123255     int nByte = sqlite3_blob_bytes(p->pSegments);
123256     *pnBlob = nByte;
123257     if( paBlob ){
123258       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
123259       if( !aByte ){
123260         rc = SQLITE_NOMEM;
123261       }else{
123262         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
123263           nByte = FTS3_NODE_CHUNKSIZE;
123264           *pnLoad = nByte;
123265         }
123266         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
123267         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
123268         if( rc!=SQLITE_OK ){
123269           sqlite3_free(aByte);
123270           aByte = 0;
123271         }
123272       }
123273       *paBlob = aByte;
123274     }
123275   }
123276 
123277   return rc;
123278 }
123279 
123280 /*
123281 ** Close the blob handle at p->pSegments, if it is open. See comments above
123282 ** the sqlite3Fts3ReadBlock() function for details.
123283 */
123284 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
123285   sqlite3_blob_close(p->pSegments);
123286   p->pSegments = 0;
123287 }
123288 
123289 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
123290   int nRead;                      /* Number of bytes to read */
123291   int rc;                         /* Return code */
123292 
123293   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
123294   rc = sqlite3_blob_read(
123295       pReader->pBlob,
123296       &pReader->aNode[pReader->nPopulate],
123297       nRead,
123298       pReader->nPopulate
123299   );
123300 
123301   if( rc==SQLITE_OK ){
123302     pReader->nPopulate += nRead;
123303     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
123304     if( pReader->nPopulate==pReader->nNode ){
123305       sqlite3_blob_close(pReader->pBlob);
123306       pReader->pBlob = 0;
123307       pReader->nPopulate = 0;
123308     }
123309   }
123310   return rc;
123311 }
123312 
123313 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
123314   int rc = SQLITE_OK;
123315   assert( !pReader->pBlob
123316        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
123317   );
123318   while( pReader->pBlob && rc==SQLITE_OK
123319      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
123320   ){
123321     rc = fts3SegReaderIncrRead(pReader);
123322   }
123323   return rc;
123324 }
123325 
123326 /*
123327 ** Move the iterator passed as the first argument to the next term in the
123328 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
123329 ** SQLITE_DONE. Otherwise, an SQLite error code.
123330 */
123331 static int fts3SegReaderNext(
123332   Fts3Table *p,
123333   Fts3SegReader *pReader,
123334   int bIncr
123335 ){
123336   int rc;                         /* Return code of various sub-routines */
123337   char *pNext;                    /* Cursor variable */
123338   int nPrefix;                    /* Number of bytes in term prefix */
123339   int nSuffix;                    /* Number of bytes in term suffix */
123340 
123341   if( !pReader->aDoclist ){
123342     pNext = pReader->aNode;
123343   }else{
123344     pNext = &pReader->aDoclist[pReader->nDoclist];
123345   }
123346 
123347   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
123348 
123349     if( fts3SegReaderIsPending(pReader) ){
123350       Fts3HashElem *pElem = *(pReader->ppNextElem);
123351       if( pElem==0 ){
123352         pReader->aNode = 0;
123353       }else{
123354         PendingList *pList = (PendingList *)fts3HashData(pElem);
123355         pReader->zTerm = (char *)fts3HashKey(pElem);
123356         pReader->nTerm = fts3HashKeysize(pElem);
123357         pReader->nNode = pReader->nDoclist = pList->nData + 1;
123358         pReader->aNode = pReader->aDoclist = pList->aData;
123359         pReader->ppNextElem++;
123360         assert( pReader->aNode );
123361       }
123362       return SQLITE_OK;
123363     }
123364 
123365     if( !fts3SegReaderIsRootOnly(pReader) ){
123366       sqlite3_free(pReader->aNode);
123367       sqlite3_blob_close(pReader->pBlob);
123368       pReader->pBlob = 0;
123369     }
123370     pReader->aNode = 0;
123371 
123372     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
123373     ** blocks have already been traversed.  */
123374     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
123375     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
123376       return SQLITE_OK;
123377     }
123378 
123379     rc = sqlite3Fts3ReadBlock(
123380         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
123381         (bIncr ? &pReader->nPopulate : 0)
123382     );
123383     if( rc!=SQLITE_OK ) return rc;
123384     assert( pReader->pBlob==0 );
123385     if( bIncr && pReader->nPopulate<pReader->nNode ){
123386       pReader->pBlob = p->pSegments;
123387       p->pSegments = 0;
123388     }
123389     pNext = pReader->aNode;
123390   }
123391 
123392   assert( !fts3SegReaderIsPending(pReader) );
123393 
123394   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
123395   if( rc!=SQLITE_OK ) return rc;
123396 
123397   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
123398   ** safe (no risk of overread) even if the node data is corrupted. */
123399   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
123400   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
123401   if( nPrefix<0 || nSuffix<=0
123402    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
123403   ){
123404     return SQLITE_CORRUPT_VTAB;
123405   }
123406 
123407   if( nPrefix+nSuffix>pReader->nTermAlloc ){
123408     int nNew = (nPrefix+nSuffix)*2;
123409     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
123410     if( !zNew ){
123411       return SQLITE_NOMEM;
123412     }
123413     pReader->zTerm = zNew;
123414     pReader->nTermAlloc = nNew;
123415   }
123416 
123417   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
123418   if( rc!=SQLITE_OK ) return rc;
123419 
123420   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
123421   pReader->nTerm = nPrefix+nSuffix;
123422   pNext += nSuffix;
123423   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
123424   pReader->aDoclist = pNext;
123425   pReader->pOffsetList = 0;
123426 
123427   /* Check that the doclist does not appear to extend past the end of the
123428   ** b-tree node. And that the final byte of the doclist is 0x00. If either
123429   ** of these statements is untrue, then the data structure is corrupt.
123430   */
123431   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
123432    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
123433   ){
123434     return SQLITE_CORRUPT_VTAB;
123435   }
123436   return SQLITE_OK;
123437 }
123438 
123439 /*
123440 ** Set the SegReader to point to the first docid in the doclist associated
123441 ** with the current term.
123442 */
123443 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
123444   int rc = SQLITE_OK;
123445   assert( pReader->aDoclist );
123446   assert( !pReader->pOffsetList );
123447   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
123448     u8 bEof = 0;
123449     pReader->iDocid = 0;
123450     pReader->nOffsetList = 0;
123451     sqlite3Fts3DoclistPrev(0,
123452         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
123453         &pReader->iDocid, &pReader->nOffsetList, &bEof
123454     );
123455   }else{
123456     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
123457     if( rc==SQLITE_OK ){
123458       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
123459       pReader->pOffsetList = &pReader->aDoclist[n];
123460     }
123461   }
123462   return rc;
123463 }
123464 
123465 /*
123466 ** Advance the SegReader to point to the next docid in the doclist
123467 ** associated with the current term.
123468 **
123469 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
123470 ** *ppOffsetList is set to point to the first column-offset list
123471 ** in the doclist entry (i.e. immediately past the docid varint).
123472 ** *pnOffsetList is set to the length of the set of column-offset
123473 ** lists, not including the nul-terminator byte. For example:
123474 */
123475 static int fts3SegReaderNextDocid(
123476   Fts3Table *pTab,
123477   Fts3SegReader *pReader,         /* Reader to advance to next docid */
123478   char **ppOffsetList,            /* OUT: Pointer to current position-list */
123479   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
123480 ){
123481   int rc = SQLITE_OK;
123482   char *p = pReader->pOffsetList;
123483   char c = 0;
123484 
123485   assert( p );
123486 
123487   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
123488     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
123489     ** Pending-terms doclists are always built up in ascending order, so
123490     ** we have to iterate through them backwards here. */
123491     u8 bEof = 0;
123492     if( ppOffsetList ){
123493       *ppOffsetList = pReader->pOffsetList;
123494       *pnOffsetList = pReader->nOffsetList - 1;
123495     }
123496     sqlite3Fts3DoclistPrev(0,
123497         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
123498         &pReader->nOffsetList, &bEof
123499     );
123500     if( bEof ){
123501       pReader->pOffsetList = 0;
123502     }else{
123503       pReader->pOffsetList = p;
123504     }
123505   }else{
123506     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
123507 
123508     /* Pointer p currently points at the first byte of an offset list. The
123509     ** following block advances it to point one byte past the end of
123510     ** the same offset list. */
123511     while( 1 ){
123512 
123513       /* The following line of code (and the "p++" below the while() loop) is
123514       ** normally all that is required to move pointer p to the desired
123515       ** position. The exception is if this node is being loaded from disk
123516       ** incrementally and pointer "p" now points to the first byte passed
123517       ** the populated part of pReader->aNode[].
123518       */
123519       while( *p | c ) c = *p++ & 0x80;
123520       assert( *p==0 );
123521 
123522       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
123523       rc = fts3SegReaderIncrRead(pReader);
123524       if( rc!=SQLITE_OK ) return rc;
123525     }
123526     p++;
123527 
123528     /* If required, populate the output variables with a pointer to and the
123529     ** size of the previous offset-list.
123530     */
123531     if( ppOffsetList ){
123532       *ppOffsetList = pReader->pOffsetList;
123533       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
123534     }
123535 
123536     while( p<pEnd && *p==0 ) p++;
123537 
123538     /* If there are no more entries in the doclist, set pOffsetList to
123539     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
123540     ** Fts3SegReader.pOffsetList to point to the next offset list before
123541     ** returning.
123542     */
123543     if( p>=pEnd ){
123544       pReader->pOffsetList = 0;
123545     }else{
123546       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
123547       if( rc==SQLITE_OK ){
123548         sqlite3_int64 iDelta;
123549         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
123550         if( pTab->bDescIdx ){
123551           pReader->iDocid -= iDelta;
123552         }else{
123553           pReader->iDocid += iDelta;
123554         }
123555       }
123556     }
123557   }
123558 
123559   return SQLITE_OK;
123560 }
123561 
123562 
123563 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
123564   Fts3Cursor *pCsr,
123565   Fts3MultiSegReader *pMsr,
123566   int *pnOvfl
123567 ){
123568   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
123569   int nOvfl = 0;
123570   int ii;
123571   int rc = SQLITE_OK;
123572   int pgsz = p->nPgsz;
123573 
123574   assert( p->bHasStat );
123575   assert( pgsz>0 );
123576 
123577   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
123578     Fts3SegReader *pReader = pMsr->apSegment[ii];
123579     if( !fts3SegReaderIsPending(pReader)
123580      && !fts3SegReaderIsRootOnly(pReader)
123581     ){
123582       sqlite3_int64 jj;
123583       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
123584         int nBlob;
123585         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
123586         if( rc!=SQLITE_OK ) break;
123587         if( (nBlob+35)>pgsz ){
123588           nOvfl += (nBlob + 34)/pgsz;
123589         }
123590       }
123591     }
123592   }
123593   *pnOvfl = nOvfl;
123594   return rc;
123595 }
123596 
123597 /*
123598 ** Free all allocations associated with the iterator passed as the
123599 ** second argument.
123600 */
123601 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
123602   if( pReader && !fts3SegReaderIsPending(pReader) ){
123603     sqlite3_free(pReader->zTerm);
123604     if( !fts3SegReaderIsRootOnly(pReader) ){
123605       sqlite3_free(pReader->aNode);
123606       sqlite3_blob_close(pReader->pBlob);
123607     }
123608   }
123609   sqlite3_free(pReader);
123610 }
123611 
123612 /*
123613 ** Allocate a new SegReader object.
123614 */
123615 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
123616   int iAge,                       /* Segment "age". */
123617   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
123618   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
123619   sqlite3_int64 iEndBlock,        /* Final block of segment */
123620   const char *zRoot,              /* Buffer containing root node */
123621   int nRoot,                      /* Size of buffer containing root node */
123622   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
123623 ){
123624   int rc = SQLITE_OK;             /* Return code */
123625   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
123626   int nExtra = 0;                 /* Bytes to allocate segment root node */
123627 
123628   assert( iStartLeaf<=iEndLeaf );
123629   if( iStartLeaf==0 ){
123630     nExtra = nRoot + FTS3_NODE_PADDING;
123631   }
123632 
123633   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
123634   if( !pReader ){
123635     return SQLITE_NOMEM;
123636   }
123637   memset(pReader, 0, sizeof(Fts3SegReader));
123638   pReader->iIdx = iAge;
123639   pReader->iStartBlock = iStartLeaf;
123640   pReader->iLeafEndBlock = iEndLeaf;
123641   pReader->iEndBlock = iEndBlock;
123642 
123643   if( nExtra ){
123644     /* The entire segment is stored in the root node. */
123645     pReader->aNode = (char *)&pReader[1];
123646     pReader->nNode = nRoot;
123647     memcpy(pReader->aNode, zRoot, nRoot);
123648     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
123649   }else{
123650     pReader->iCurrentBlock = iStartLeaf-1;
123651   }
123652 
123653   if( rc==SQLITE_OK ){
123654     *ppReader = pReader;
123655   }else{
123656     sqlite3Fts3SegReaderFree(pReader);
123657   }
123658   return rc;
123659 }
123660 
123661 /*
123662 ** This is a comparison function used as a qsort() callback when sorting
123663 ** an array of pending terms by term. This occurs as part of flushing
123664 ** the contents of the pending-terms hash table to the database.
123665 */
123666 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
123667   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
123668   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
123669   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
123670   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
123671 
123672   int n = (n1<n2 ? n1 : n2);
123673   int c = memcmp(z1, z2, n);
123674   if( c==0 ){
123675     c = n1 - n2;
123676   }
123677   return c;
123678 }
123679 
123680 /*
123681 ** This function is used to allocate an Fts3SegReader that iterates through
123682 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
123683 **
123684 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
123685 ** through each term in the pending-terms table. Or, if isPrefixIter is
123686 ** non-zero, it iterates through each term and its prefixes. For example, if
123687 ** the pending terms hash table contains the terms "sqlite", "mysql" and
123688 ** "firebird", then the iterator visits the following 'terms' (in the order
123689 ** shown):
123690 **
123691 **   f fi fir fire fireb firebi firebir firebird
123692 **   m my mys mysq mysql
123693 **   s sq sql sqli sqlit sqlite
123694 **
123695 ** Whereas if isPrefixIter is zero, the terms visited are:
123696 **
123697 **   firebird mysql sqlite
123698 */
123699 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
123700   Fts3Table *p,                   /* Virtual table handle */
123701   int iIndex,                     /* Index for p->aIndex */
123702   const char *zTerm,              /* Term to search for */
123703   int nTerm,                      /* Size of buffer zTerm */
123704   int bPrefix,                    /* True for a prefix iterator */
123705   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
123706 ){
123707   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
123708   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
123709   int nElem = 0;                  /* Size of array at aElem */
123710   int rc = SQLITE_OK;             /* Return Code */
123711   Fts3Hash *pHash;
123712 
123713   pHash = &p->aIndex[iIndex].hPending;
123714   if( bPrefix ){
123715     int nAlloc = 0;               /* Size of allocated array at aElem */
123716     Fts3HashElem *pE = 0;         /* Iterator variable */
123717 
123718     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
123719       char *zKey = (char *)fts3HashKey(pE);
123720       int nKey = fts3HashKeysize(pE);
123721       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
123722         if( nElem==nAlloc ){
123723           Fts3HashElem **aElem2;
123724           nAlloc += 16;
123725           aElem2 = (Fts3HashElem **)sqlite3_realloc(
123726               aElem, nAlloc*sizeof(Fts3HashElem *)
123727           );
123728           if( !aElem2 ){
123729             rc = SQLITE_NOMEM;
123730             nElem = 0;
123731             break;
123732           }
123733           aElem = aElem2;
123734         }
123735 
123736         aElem[nElem++] = pE;
123737       }
123738     }
123739 
123740     /* If more than one term matches the prefix, sort the Fts3HashElem
123741     ** objects in term order using qsort(). This uses the same comparison
123742     ** callback as is used when flushing terms to disk.
123743     */
123744     if( nElem>1 ){
123745       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
123746     }
123747 
123748   }else{
123749     /* The query is a simple term lookup that matches at most one term in
123750     ** the index. All that is required is a straight hash-lookup. */
123751     Fts3HashElem *pE = fts3HashFindElem(pHash, zTerm, nTerm);
123752     if( pE ){
123753       aElem = &pE;
123754       nElem = 1;
123755     }
123756   }
123757 
123758   if( nElem>0 ){
123759     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
123760     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
123761     if( !pReader ){
123762       rc = SQLITE_NOMEM;
123763     }else{
123764       memset(pReader, 0, nByte);
123765       pReader->iIdx = 0x7FFFFFFF;
123766       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
123767       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
123768     }
123769   }
123770 
123771   if( bPrefix ){
123772     sqlite3_free(aElem);
123773   }
123774   *ppReader = pReader;
123775   return rc;
123776 }
123777 
123778 /*
123779 ** Compare the entries pointed to by two Fts3SegReader structures.
123780 ** Comparison is as follows:
123781 **
123782 **   1) EOF is greater than not EOF.
123783 **
123784 **   2) The current terms (if any) are compared using memcmp(). If one
123785 **      term is a prefix of another, the longer term is considered the
123786 **      larger.
123787 **
123788 **   3) By segment age. An older segment is considered larger.
123789 */
123790 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
123791   int rc;
123792   if( pLhs->aNode && pRhs->aNode ){
123793     int rc2 = pLhs->nTerm - pRhs->nTerm;
123794     if( rc2<0 ){
123795       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
123796     }else{
123797       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
123798     }
123799     if( rc==0 ){
123800       rc = rc2;
123801     }
123802   }else{
123803     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
123804   }
123805   if( rc==0 ){
123806     rc = pRhs->iIdx - pLhs->iIdx;
123807   }
123808   assert( rc!=0 );
123809   return rc;
123810 }
123811 
123812 /*
123813 ** A different comparison function for SegReader structures. In this
123814 ** version, it is assumed that each SegReader points to an entry in
123815 ** a doclist for identical terms. Comparison is made as follows:
123816 **
123817 **   1) EOF (end of doclist in this case) is greater than not EOF.
123818 **
123819 **   2) By current docid.
123820 **
123821 **   3) By segment age. An older segment is considered larger.
123822 */
123823 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
123824   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
123825   if( rc==0 ){
123826     if( pLhs->iDocid==pRhs->iDocid ){
123827       rc = pRhs->iIdx - pLhs->iIdx;
123828     }else{
123829       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
123830     }
123831   }
123832   assert( pLhs->aNode && pRhs->aNode );
123833   return rc;
123834 }
123835 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
123836   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
123837   if( rc==0 ){
123838     if( pLhs->iDocid==pRhs->iDocid ){
123839       rc = pRhs->iIdx - pLhs->iIdx;
123840     }else{
123841       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
123842     }
123843   }
123844   assert( pLhs->aNode && pRhs->aNode );
123845   return rc;
123846 }
123847 
123848 /*
123849 ** Compare the term that the Fts3SegReader object passed as the first argument
123850 ** points to with the term specified by arguments zTerm and nTerm.
123851 **
123852 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
123853 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
123854 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
123855 */
123856 static int fts3SegReaderTermCmp(
123857   Fts3SegReader *pSeg,            /* Segment reader object */
123858   const char *zTerm,              /* Term to compare to */
123859   int nTerm                       /* Size of term zTerm in bytes */
123860 ){
123861   int res = 0;
123862   if( pSeg->aNode ){
123863     if( pSeg->nTerm>nTerm ){
123864       res = memcmp(pSeg->zTerm, zTerm, nTerm);
123865     }else{
123866       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
123867     }
123868     if( res==0 ){
123869       res = pSeg->nTerm-nTerm;
123870     }
123871   }
123872   return res;
123873 }
123874 
123875 /*
123876 ** Argument apSegment is an array of nSegment elements. It is known that
123877 ** the final (nSegment-nSuspect) members are already in sorted order
123878 ** (according to the comparison function provided). This function shuffles
123879 ** the array around until all entries are in sorted order.
123880 */
123881 static void fts3SegReaderSort(
123882   Fts3SegReader **apSegment,                     /* Array to sort entries of */
123883   int nSegment,                                  /* Size of apSegment array */
123884   int nSuspect,                                  /* Unsorted entry count */
123885   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
123886 ){
123887   int i;                          /* Iterator variable */
123888 
123889   assert( nSuspect<=nSegment );
123890 
123891   if( nSuspect==nSegment ) nSuspect--;
123892   for(i=nSuspect-1; i>=0; i--){
123893     int j;
123894     for(j=i; j<(nSegment-1); j++){
123895       Fts3SegReader *pTmp;
123896       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
123897       pTmp = apSegment[j+1];
123898       apSegment[j+1] = apSegment[j];
123899       apSegment[j] = pTmp;
123900     }
123901   }
123902 
123903 #ifndef NDEBUG
123904   /* Check that the list really is sorted now. */
123905   for(i=0; i<(nSuspect-1); i++){
123906     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
123907   }
123908 #endif
123909 }
123910 
123911 /*
123912 ** Insert a record into the %_segments table.
123913 */
123914 static int fts3WriteSegment(
123915   Fts3Table *p,                   /* Virtual table handle */
123916   sqlite3_int64 iBlock,           /* Block id for new block */
123917   char *z,                        /* Pointer to buffer containing block data */
123918   int n                           /* Size of buffer z in bytes */
123919 ){
123920   sqlite3_stmt *pStmt;
123921   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
123922   if( rc==SQLITE_OK ){
123923     sqlite3_bind_int64(pStmt, 1, iBlock);
123924     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
123925     sqlite3_step(pStmt);
123926     rc = sqlite3_reset(pStmt);
123927   }
123928   return rc;
123929 }
123930 
123931 /*
123932 ** Insert a record into the %_segdir table.
123933 */
123934 static int fts3WriteSegdir(
123935   Fts3Table *p,                   /* Virtual table handle */
123936   int iLevel,                     /* Value for "level" field */
123937   int iIdx,                       /* Value for "idx" field */
123938   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
123939   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
123940   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
123941   char *zRoot,                    /* Blob value for "root" field */
123942   int nRoot                       /* Number of bytes in buffer zRoot */
123943 ){
123944   sqlite3_stmt *pStmt;
123945   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
123946   if( rc==SQLITE_OK ){
123947     sqlite3_bind_int(pStmt, 1, iLevel);
123948     sqlite3_bind_int(pStmt, 2, iIdx);
123949     sqlite3_bind_int64(pStmt, 3, iStartBlock);
123950     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
123951     sqlite3_bind_int64(pStmt, 5, iEndBlock);
123952     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
123953     sqlite3_step(pStmt);
123954     rc = sqlite3_reset(pStmt);
123955   }
123956   return rc;
123957 }
123958 
123959 /*
123960 ** Return the size of the common prefix (if any) shared by zPrev and
123961 ** zNext, in bytes. For example,
123962 **
123963 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
123964 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
123965 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
123966 */
123967 static int fts3PrefixCompress(
123968   const char *zPrev,              /* Buffer containing previous term */
123969   int nPrev,                      /* Size of buffer zPrev in bytes */
123970   const char *zNext,              /* Buffer containing next term */
123971   int nNext                       /* Size of buffer zNext in bytes */
123972 ){
123973   int n;
123974   UNUSED_PARAMETER(nNext);
123975   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
123976   return n;
123977 }
123978 
123979 /*
123980 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
123981 ** (according to memcmp) than the previous term.
123982 */
123983 static int fts3NodeAddTerm(
123984   Fts3Table *p,                   /* Virtual table handle */
123985   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
123986   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
123987   const char *zTerm,              /* Pointer to buffer containing term */
123988   int nTerm                       /* Size of term in bytes */
123989 ){
123990   SegmentNode *pTree = *ppTree;
123991   int rc;
123992   SegmentNode *pNew;
123993 
123994   /* First try to append the term to the current node. Return early if
123995   ** this is possible.
123996   */
123997   if( pTree ){
123998     int nData = pTree->nData;     /* Current size of node in bytes */
123999     int nReq = nData;             /* Required space after adding zTerm */
124000     int nPrefix;                  /* Number of bytes of prefix compression */
124001     int nSuffix;                  /* Suffix length */
124002 
124003     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
124004     nSuffix = nTerm-nPrefix;
124005 
124006     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
124007     if( nReq<=p->nNodeSize || !pTree->zTerm ){
124008 
124009       if( nReq>p->nNodeSize ){
124010         /* An unusual case: this is the first term to be added to the node
124011         ** and the static node buffer (p->nNodeSize bytes) is not large
124012         ** enough. Use a separately malloced buffer instead This wastes
124013         ** p->nNodeSize bytes, but since this scenario only comes about when
124014         ** the database contain two terms that share a prefix of almost 2KB,
124015         ** this is not expected to be a serious problem.
124016         */
124017         assert( pTree->aData==(char *)&pTree[1] );
124018         pTree->aData = (char *)sqlite3_malloc(nReq);
124019         if( !pTree->aData ){
124020           return SQLITE_NOMEM;
124021         }
124022       }
124023 
124024       if( pTree->zTerm ){
124025         /* There is no prefix-length field for first term in a node */
124026         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
124027       }
124028 
124029       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
124030       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
124031       pTree->nData = nData + nSuffix;
124032       pTree->nEntry++;
124033 
124034       if( isCopyTerm ){
124035         if( pTree->nMalloc<nTerm ){
124036           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
124037           if( !zNew ){
124038             return SQLITE_NOMEM;
124039           }
124040           pTree->nMalloc = nTerm*2;
124041           pTree->zMalloc = zNew;
124042         }
124043         pTree->zTerm = pTree->zMalloc;
124044         memcpy(pTree->zTerm, zTerm, nTerm);
124045         pTree->nTerm = nTerm;
124046       }else{
124047         pTree->zTerm = (char *)zTerm;
124048         pTree->nTerm = nTerm;
124049       }
124050       return SQLITE_OK;
124051     }
124052   }
124053 
124054   /* If control flows to here, it was not possible to append zTerm to the
124055   ** current node. Create a new node (a right-sibling of the current node).
124056   ** If this is the first node in the tree, the term is added to it.
124057   **
124058   ** Otherwise, the term is not added to the new node, it is left empty for
124059   ** now. Instead, the term is inserted into the parent of pTree. If pTree
124060   ** has no parent, one is created here.
124061   */
124062   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
124063   if( !pNew ){
124064     return SQLITE_NOMEM;
124065   }
124066   memset(pNew, 0, sizeof(SegmentNode));
124067   pNew->nData = 1 + FTS3_VARINT_MAX;
124068   pNew->aData = (char *)&pNew[1];
124069 
124070   if( pTree ){
124071     SegmentNode *pParent = pTree->pParent;
124072     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
124073     if( pTree->pParent==0 ){
124074       pTree->pParent = pParent;
124075     }
124076     pTree->pRight = pNew;
124077     pNew->pLeftmost = pTree->pLeftmost;
124078     pNew->pParent = pParent;
124079     pNew->zMalloc = pTree->zMalloc;
124080     pNew->nMalloc = pTree->nMalloc;
124081     pTree->zMalloc = 0;
124082   }else{
124083     pNew->pLeftmost = pNew;
124084     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
124085   }
124086 
124087   *ppTree = pNew;
124088   return rc;
124089 }
124090 
124091 /*
124092 ** Helper function for fts3NodeWrite().
124093 */
124094 static int fts3TreeFinishNode(
124095   SegmentNode *pTree,
124096   int iHeight,
124097   sqlite3_int64 iLeftChild
124098 ){
124099   int nStart;
124100   assert( iHeight>=1 && iHeight<128 );
124101   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
124102   pTree->aData[nStart] = (char)iHeight;
124103   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
124104   return nStart;
124105 }
124106 
124107 /*
124108 ** Write the buffer for the segment node pTree and all of its peers to the
124109 ** database. Then call this function recursively to write the parent of
124110 ** pTree and its peers to the database.
124111 **
124112 ** Except, if pTree is a root node, do not write it to the database. Instead,
124113 ** set output variables *paRoot and *pnRoot to contain the root node.
124114 **
124115 ** If successful, SQLITE_OK is returned and output variable *piLast is
124116 ** set to the largest blockid written to the database (or zero if no
124117 ** blocks were written to the db). Otherwise, an SQLite error code is
124118 ** returned.
124119 */
124120 static int fts3NodeWrite(
124121   Fts3Table *p,                   /* Virtual table handle */
124122   SegmentNode *pTree,             /* SegmentNode handle */
124123   int iHeight,                    /* Height of this node in tree */
124124   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
124125   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
124126   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
124127   char **paRoot,                  /* OUT: Data for root node */
124128   int *pnRoot                     /* OUT: Size of root node in bytes */
124129 ){
124130   int rc = SQLITE_OK;
124131 
124132   if( !pTree->pParent ){
124133     /* Root node of the tree. */
124134     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
124135     *piLast = iFree-1;
124136     *pnRoot = pTree->nData - nStart;
124137     *paRoot = &pTree->aData[nStart];
124138   }else{
124139     SegmentNode *pIter;
124140     sqlite3_int64 iNextFree = iFree;
124141     sqlite3_int64 iNextLeaf = iLeaf;
124142     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
124143       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
124144       int nWrite = pIter->nData - nStart;
124145 
124146       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
124147       iNextFree++;
124148       iNextLeaf += (pIter->nEntry+1);
124149     }
124150     if( rc==SQLITE_OK ){
124151       assert( iNextLeaf==iFree );
124152       rc = fts3NodeWrite(
124153           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
124154       );
124155     }
124156   }
124157 
124158   return rc;
124159 }
124160 
124161 /*
124162 ** Free all memory allocations associated with the tree pTree.
124163 */
124164 static void fts3NodeFree(SegmentNode *pTree){
124165   if( pTree ){
124166     SegmentNode *p = pTree->pLeftmost;
124167     fts3NodeFree(p->pParent);
124168     while( p ){
124169       SegmentNode *pRight = p->pRight;
124170       if( p->aData!=(char *)&p[1] ){
124171         sqlite3_free(p->aData);
124172       }
124173       assert( pRight==0 || p->zMalloc==0 );
124174       sqlite3_free(p->zMalloc);
124175       sqlite3_free(p);
124176       p = pRight;
124177     }
124178   }
124179 }
124180 
124181 /*
124182 ** Add a term to the segment being constructed by the SegmentWriter object
124183 ** *ppWriter. When adding the first term to a segment, *ppWriter should
124184 ** be passed NULL. This function will allocate a new SegmentWriter object
124185 ** and return it via the input/output variable *ppWriter in this case.
124186 **
124187 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
124188 */
124189 static int fts3SegWriterAdd(
124190   Fts3Table *p,                   /* Virtual table handle */
124191   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
124192   int isCopyTerm,                 /* True if buffer zTerm must be copied */
124193   const char *zTerm,              /* Pointer to buffer containing term */
124194   int nTerm,                      /* Size of term in bytes */
124195   const char *aDoclist,           /* Pointer to buffer containing doclist */
124196   int nDoclist                    /* Size of doclist in bytes */
124197 ){
124198   int nPrefix;                    /* Size of term prefix in bytes */
124199   int nSuffix;                    /* Size of term suffix in bytes */
124200   int nReq;                       /* Number of bytes required on leaf page */
124201   int nData;
124202   SegmentWriter *pWriter = *ppWriter;
124203 
124204   if( !pWriter ){
124205     int rc;
124206     sqlite3_stmt *pStmt;
124207 
124208     /* Allocate the SegmentWriter structure */
124209     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
124210     if( !pWriter ) return SQLITE_NOMEM;
124211     memset(pWriter, 0, sizeof(SegmentWriter));
124212     *ppWriter = pWriter;
124213 
124214     /* Allocate a buffer in which to accumulate data */
124215     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
124216     if( !pWriter->aData ) return SQLITE_NOMEM;
124217     pWriter->nSize = p->nNodeSize;
124218 
124219     /* Find the next free blockid in the %_segments table */
124220     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
124221     if( rc!=SQLITE_OK ) return rc;
124222     if( SQLITE_ROW==sqlite3_step(pStmt) ){
124223       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
124224       pWriter->iFirst = pWriter->iFree;
124225     }
124226     rc = sqlite3_reset(pStmt);
124227     if( rc!=SQLITE_OK ) return rc;
124228   }
124229   nData = pWriter->nData;
124230 
124231   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
124232   nSuffix = nTerm-nPrefix;
124233 
124234   /* Figure out how many bytes are required by this new entry */
124235   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
124236     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
124237     nSuffix +                               /* Term suffix */
124238     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
124239     nDoclist;                               /* Doclist data */
124240 
124241   if( nData>0 && nData+nReq>p->nNodeSize ){
124242     int rc;
124243 
124244     /* The current leaf node is full. Write it out to the database. */
124245     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
124246     if( rc!=SQLITE_OK ) return rc;
124247 
124248     /* Add the current term to the interior node tree. The term added to
124249     ** the interior tree must:
124250     **
124251     **   a) be greater than the largest term on the leaf node just written
124252     **      to the database (still available in pWriter->zTerm), and
124253     **
124254     **   b) be less than or equal to the term about to be added to the new
124255     **      leaf node (zTerm/nTerm).
124256     **
124257     ** In other words, it must be the prefix of zTerm 1 byte longer than
124258     ** the common prefix (if any) of zTerm and pWriter->zTerm.
124259     */
124260     assert( nPrefix<nTerm );
124261     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
124262     if( rc!=SQLITE_OK ) return rc;
124263 
124264     nData = 0;
124265     pWriter->nTerm = 0;
124266 
124267     nPrefix = 0;
124268     nSuffix = nTerm;
124269     nReq = 1 +                              /* varint containing prefix size */
124270       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
124271       nTerm +                               /* Term suffix */
124272       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
124273       nDoclist;                             /* Doclist data */
124274   }
124275 
124276   /* If the buffer currently allocated is too small for this entry, realloc
124277   ** the buffer to make it large enough.
124278   */
124279   if( nReq>pWriter->nSize ){
124280     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
124281     if( !aNew ) return SQLITE_NOMEM;
124282     pWriter->aData = aNew;
124283     pWriter->nSize = nReq;
124284   }
124285   assert( nData+nReq<=pWriter->nSize );
124286 
124287   /* Append the prefix-compressed term and doclist to the buffer. */
124288   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
124289   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
124290   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
124291   nData += nSuffix;
124292   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
124293   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
124294   pWriter->nData = nData + nDoclist;
124295 
124296   /* Save the current term so that it can be used to prefix-compress the next.
124297   ** If the isCopyTerm parameter is true, then the buffer pointed to by
124298   ** zTerm is transient, so take a copy of the term data. Otherwise, just
124299   ** store a copy of the pointer.
124300   */
124301   if( isCopyTerm ){
124302     if( nTerm>pWriter->nMalloc ){
124303       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
124304       if( !zNew ){
124305         return SQLITE_NOMEM;
124306       }
124307       pWriter->nMalloc = nTerm*2;
124308       pWriter->zMalloc = zNew;
124309       pWriter->zTerm = zNew;
124310     }
124311     assert( pWriter->zTerm==pWriter->zMalloc );
124312     memcpy(pWriter->zTerm, zTerm, nTerm);
124313   }else{
124314     pWriter->zTerm = (char *)zTerm;
124315   }
124316   pWriter->nTerm = nTerm;
124317 
124318   return SQLITE_OK;
124319 }
124320 
124321 /*
124322 ** Flush all data associated with the SegmentWriter object pWriter to the
124323 ** database. This function must be called after all terms have been added
124324 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
124325 ** returned. Otherwise, an SQLite error code.
124326 */
124327 static int fts3SegWriterFlush(
124328   Fts3Table *p,                   /* Virtual table handle */
124329   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
124330   int iLevel,                     /* Value for 'level' column of %_segdir */
124331   int iIdx                        /* Value for 'idx' column of %_segdir */
124332 ){
124333   int rc;                         /* Return code */
124334   if( pWriter->pTree ){
124335     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
124336     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
124337     char *zRoot = NULL;           /* Pointer to buffer containing root node */
124338     int nRoot = 0;                /* Size of buffer zRoot */
124339 
124340     iLastLeaf = pWriter->iFree;
124341     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
124342     if( rc==SQLITE_OK ){
124343       rc = fts3NodeWrite(p, pWriter->pTree, 1,
124344           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
124345     }
124346     if( rc==SQLITE_OK ){
124347       rc = fts3WriteSegdir(
124348           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
124349     }
124350   }else{
124351     /* The entire tree fits on the root node. Write it to the segdir table. */
124352     rc = fts3WriteSegdir(
124353         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
124354   }
124355   return rc;
124356 }
124357 
124358 /*
124359 ** Release all memory held by the SegmentWriter object passed as the
124360 ** first argument.
124361 */
124362 static void fts3SegWriterFree(SegmentWriter *pWriter){
124363   if( pWriter ){
124364     sqlite3_free(pWriter->aData);
124365     sqlite3_free(pWriter->zMalloc);
124366     fts3NodeFree(pWriter->pTree);
124367     sqlite3_free(pWriter);
124368   }
124369 }
124370 
124371 /*
124372 ** The first value in the apVal[] array is assumed to contain an integer.
124373 ** This function tests if there exist any documents with docid values that
124374 ** are different from that integer. i.e. if deleting the document with docid
124375 ** pRowid would mean the FTS3 table were empty.
124376 **
124377 ** If successful, *pisEmpty is set to true if the table is empty except for
124378 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
124379 ** error occurs, an SQLite error code is returned.
124380 */
124381 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
124382   sqlite3_stmt *pStmt;
124383   int rc;
124384   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
124385   if( rc==SQLITE_OK ){
124386     if( SQLITE_ROW==sqlite3_step(pStmt) ){
124387       *pisEmpty = sqlite3_column_int(pStmt, 0);
124388     }
124389     rc = sqlite3_reset(pStmt);
124390   }
124391   return rc;
124392 }
124393 
124394 /*
124395 ** Set *pnMax to the largest segment level in the database for the index
124396 ** iIndex.
124397 **
124398 ** Segment levels are stored in the 'level' column of the %_segdir table.
124399 **
124400 ** Return SQLITE_OK if successful, or an SQLite error code if not.
124401 */
124402 static int fts3SegmentMaxLevel(Fts3Table *p, int iIndex, int *pnMax){
124403   sqlite3_stmt *pStmt;
124404   int rc;
124405   assert( iIndex>=0 && iIndex<p->nIndex );
124406 
124407   /* Set pStmt to the compiled version of:
124408   **
124409   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
124410   **
124411   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
124412   */
124413   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
124414   if( rc!=SQLITE_OK ) return rc;
124415   sqlite3_bind_int(pStmt, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
124416   sqlite3_bind_int(pStmt, 2, (iIndex+1)*FTS3_SEGDIR_MAXLEVEL - 1);
124417   if( SQLITE_ROW==sqlite3_step(pStmt) ){
124418     *pnMax = sqlite3_column_int(pStmt, 0);
124419   }
124420   return sqlite3_reset(pStmt);
124421 }
124422 
124423 /*
124424 ** This function is used after merging multiple segments into a single large
124425 ** segment to delete the old, now redundant, segment b-trees. Specifically,
124426 ** it:
124427 **
124428 **   1) Deletes all %_segments entries for the segments associated with
124429 **      each of the SegReader objects in the array passed as the third
124430 **      argument, and
124431 **
124432 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
124433 **      entries regardless of level if (iLevel<0).
124434 **
124435 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
124436 */
124437 static int fts3DeleteSegdir(
124438   Fts3Table *p,                   /* Virtual table handle */
124439   int iIndex,                     /* Index for p->aIndex */
124440   int iLevel,                     /* Level of %_segdir entries to delete */
124441   Fts3SegReader **apSegment,      /* Array of SegReader objects */
124442   int nReader                     /* Size of array apSegment */
124443 ){
124444   int rc;                         /* Return Code */
124445   int i;                          /* Iterator variable */
124446   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
124447 
124448   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
124449   for(i=0; rc==SQLITE_OK && i<nReader; i++){
124450     Fts3SegReader *pSegment = apSegment[i];
124451     if( pSegment->iStartBlock ){
124452       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
124453       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
124454       sqlite3_step(pDelete);
124455       rc = sqlite3_reset(pDelete);
124456     }
124457   }
124458   if( rc!=SQLITE_OK ){
124459     return rc;
124460   }
124461 
124462   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
124463   if( iLevel==FTS3_SEGCURSOR_ALL ){
124464     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
124465     if( rc==SQLITE_OK ){
124466       sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL);
124467       sqlite3_bind_int(pDelete, 2, (iIndex+1) * FTS3_SEGDIR_MAXLEVEL - 1);
124468     }
124469   }else{
124470     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
124471     if( rc==SQLITE_OK ){
124472       sqlite3_bind_int(pDelete, 1, iIndex*FTS3_SEGDIR_MAXLEVEL + iLevel);
124473     }
124474   }
124475 
124476   if( rc==SQLITE_OK ){
124477     sqlite3_step(pDelete);
124478     rc = sqlite3_reset(pDelete);
124479   }
124480 
124481   return rc;
124482 }
124483 
124484 /*
124485 ** When this function is called, buffer *ppList (size *pnList bytes) contains
124486 ** a position list that may (or may not) feature multiple columns. This
124487 ** function adjusts the pointer *ppList and the length *pnList so that they
124488 ** identify the subset of the position list that corresponds to column iCol.
124489 **
124490 ** If there are no entries in the input position list for column iCol, then
124491 ** *pnList is set to zero before returning.
124492 */
124493 static void fts3ColumnFilter(
124494   int iCol,                       /* Column to filter on */
124495   char **ppList,                  /* IN/OUT: Pointer to position list */
124496   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
124497 ){
124498   char *pList = *ppList;
124499   int nList = *pnList;
124500   char *pEnd = &pList[nList];
124501   int iCurrent = 0;
124502   char *p = pList;
124503 
124504   assert( iCol>=0 );
124505   while( 1 ){
124506     char c = 0;
124507     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
124508 
124509     if( iCol==iCurrent ){
124510       nList = (int)(p - pList);
124511       break;
124512     }
124513 
124514     nList -= (int)(p - pList);
124515     pList = p;
124516     if( nList==0 ){
124517       break;
124518     }
124519     p = &pList[1];
124520     p += sqlite3Fts3GetVarint32(p, &iCurrent);
124521   }
124522 
124523   *ppList = pList;
124524   *pnList = nList;
124525 }
124526 
124527 /*
124528 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
124529 ** existing data). Grow the buffer if required.
124530 **
124531 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
124532 ** trying to resize the buffer, return SQLITE_NOMEM.
124533 */
124534 static int fts3MsrBufferData(
124535   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
124536   char *pList,
124537   int nList
124538 ){
124539   if( nList>pMsr->nBuffer ){
124540     char *pNew;
124541     pMsr->nBuffer = nList*2;
124542     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
124543     if( !pNew ) return SQLITE_NOMEM;
124544     pMsr->aBuffer = pNew;
124545   }
124546 
124547   memcpy(pMsr->aBuffer, pList, nList);
124548   return SQLITE_OK;
124549 }
124550 
124551 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
124552   Fts3Table *p,                   /* Virtual table handle */
124553   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
124554   sqlite3_int64 *piDocid,         /* OUT: Docid value */
124555   char **paPoslist,               /* OUT: Pointer to position list */
124556   int *pnPoslist                  /* OUT: Size of position list in bytes */
124557 ){
124558   int nMerge = pMsr->nAdvance;
124559   Fts3SegReader **apSegment = pMsr->apSegment;
124560   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
124561     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
124562   );
124563 
124564   if( nMerge==0 ){
124565     *paPoslist = 0;
124566     return SQLITE_OK;
124567   }
124568 
124569   while( 1 ){
124570     Fts3SegReader *pSeg;
124571     pSeg = pMsr->apSegment[0];
124572 
124573     if( pSeg->pOffsetList==0 ){
124574       *paPoslist = 0;
124575       break;
124576     }else{
124577       int rc;
124578       char *pList;
124579       int nList;
124580       int j;
124581       sqlite3_int64 iDocid = apSegment[0]->iDocid;
124582 
124583       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
124584       j = 1;
124585       while( rc==SQLITE_OK
124586         && j<nMerge
124587         && apSegment[j]->pOffsetList
124588         && apSegment[j]->iDocid==iDocid
124589       ){
124590         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
124591         j++;
124592       }
124593       if( rc!=SQLITE_OK ) return rc;
124594       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
124595 
124596       if( pMsr->iColFilter>=0 ){
124597         fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
124598       }
124599 
124600       if( nList>0 ){
124601         if( fts3SegReaderIsPending(apSegment[0]) ){
124602           rc = fts3MsrBufferData(pMsr, pList, nList+1);
124603           if( rc!=SQLITE_OK ) return rc;
124604           *paPoslist = pMsr->aBuffer;
124605           assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
124606         }else{
124607           *paPoslist = pList;
124608         }
124609         *piDocid = iDocid;
124610         *pnPoslist = nList;
124611         break;
124612       }
124613     }
124614   }
124615 
124616   return SQLITE_OK;
124617 }
124618 
124619 static int fts3SegReaderStart(
124620   Fts3Table *p,                   /* Virtual table handle */
124621   Fts3MultiSegReader *pCsr,       /* Cursor object */
124622   const char *zTerm,              /* Term searched for (or NULL) */
124623   int nTerm                       /* Length of zTerm in bytes */
124624 ){
124625   int i;
124626   int nSeg = pCsr->nSegment;
124627 
124628   /* If the Fts3SegFilter defines a specific term (or term prefix) to search
124629   ** for, then advance each segment iterator until it points to a term of
124630   ** equal or greater value than the specified term. This prevents many
124631   ** unnecessary merge/sort operations for the case where single segment
124632   ** b-tree leaf nodes contain more than one term.
124633   */
124634   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
124635     Fts3SegReader *pSeg = pCsr->apSegment[i];
124636     do {
124637       int rc = fts3SegReaderNext(p, pSeg, 0);
124638       if( rc!=SQLITE_OK ) return rc;
124639     }while( zTerm && fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 );
124640   }
124641   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
124642 
124643   return SQLITE_OK;
124644 }
124645 
124646 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
124647   Fts3Table *p,                   /* Virtual table handle */
124648   Fts3MultiSegReader *pCsr,       /* Cursor object */
124649   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
124650 ){
124651   pCsr->pFilter = pFilter;
124652   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
124653 }
124654 
124655 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
124656   Fts3Table *p,                   /* Virtual table handle */
124657   Fts3MultiSegReader *pCsr,       /* Cursor object */
124658   int iCol,                       /* Column to match on. */
124659   const char *zTerm,              /* Term to iterate through a doclist for */
124660   int nTerm                       /* Number of bytes in zTerm */
124661 ){
124662   int i;
124663   int rc;
124664   int nSegment = pCsr->nSegment;
124665   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
124666     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
124667   );
124668 
124669   assert( pCsr->pFilter==0 );
124670   assert( zTerm && nTerm>0 );
124671 
124672   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
124673   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
124674   if( rc!=SQLITE_OK ) return rc;
124675 
124676   /* Determine how many of the segments actually point to zTerm/nTerm. */
124677   for(i=0; i<nSegment; i++){
124678     Fts3SegReader *pSeg = pCsr->apSegment[i];
124679     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
124680       break;
124681     }
124682   }
124683   pCsr->nAdvance = i;
124684 
124685   /* Advance each of the segments to point to the first docid. */
124686   for(i=0; i<pCsr->nAdvance; i++){
124687     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
124688     if( rc!=SQLITE_OK ) return rc;
124689   }
124690   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
124691 
124692   assert( iCol<0 || iCol<p->nColumn );
124693   pCsr->iColFilter = iCol;
124694 
124695   return SQLITE_OK;
124696 }
124697 
124698 /*
124699 ** This function is called on a MultiSegReader that has been started using
124700 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
124701 ** have been made. Calling this function puts the MultiSegReader in such
124702 ** a state that if the next two calls are:
124703 **
124704 **   sqlite3Fts3SegReaderStart()
124705 **   sqlite3Fts3SegReaderStep()
124706 **
124707 ** then the entire doclist for the term is available in
124708 ** MultiSegReader.aDoclist/nDoclist.
124709 */
124710 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
124711   int i;                          /* Used to iterate through segment-readers */
124712 
124713   assert( pCsr->zTerm==0 );
124714   assert( pCsr->nTerm==0 );
124715   assert( pCsr->aDoclist==0 );
124716   assert( pCsr->nDoclist==0 );
124717 
124718   pCsr->nAdvance = 0;
124719   pCsr->bRestart = 1;
124720   for(i=0; i<pCsr->nSegment; i++){
124721     pCsr->apSegment[i]->pOffsetList = 0;
124722     pCsr->apSegment[i]->nOffsetList = 0;
124723     pCsr->apSegment[i]->iDocid = 0;
124724   }
124725 
124726   return SQLITE_OK;
124727 }
124728 
124729 
124730 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
124731   Fts3Table *p,                   /* Virtual table handle */
124732   Fts3MultiSegReader *pCsr        /* Cursor object */
124733 ){
124734   int rc = SQLITE_OK;
124735 
124736   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
124737   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
124738   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
124739   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
124740   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
124741 
124742   Fts3SegReader **apSegment = pCsr->apSegment;
124743   int nSegment = pCsr->nSegment;
124744   Fts3SegFilter *pFilter = pCsr->pFilter;
124745   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
124746     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
124747   );
124748 
124749   if( pCsr->nSegment==0 ) return SQLITE_OK;
124750 
124751   do {
124752     int nMerge;
124753     int i;
124754 
124755     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
124756     ** forward. Then sort the list in order of current term again.
124757     */
124758     for(i=0; i<pCsr->nAdvance; i++){
124759       rc = fts3SegReaderNext(p, apSegment[i], 0);
124760       if( rc!=SQLITE_OK ) return rc;
124761     }
124762     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
124763     pCsr->nAdvance = 0;
124764 
124765     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
124766     assert( rc==SQLITE_OK );
124767     if( apSegment[0]->aNode==0 ) break;
124768 
124769     pCsr->nTerm = apSegment[0]->nTerm;
124770     pCsr->zTerm = apSegment[0]->zTerm;
124771 
124772     /* If this is a prefix-search, and if the term that apSegment[0] points
124773     ** to does not share a suffix with pFilter->zTerm/nTerm, then all
124774     ** required callbacks have been made. In this case exit early.
124775     **
124776     ** Similarly, if this is a search for an exact match, and the first term
124777     ** of segment apSegment[0] is not a match, exit early.
124778     */
124779     if( pFilter->zTerm && !isScan ){
124780       if( pCsr->nTerm<pFilter->nTerm
124781        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
124782        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
124783       ){
124784         break;
124785       }
124786     }
124787 
124788     nMerge = 1;
124789     while( nMerge<nSegment
124790         && apSegment[nMerge]->aNode
124791         && apSegment[nMerge]->nTerm==pCsr->nTerm
124792         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
124793     ){
124794       nMerge++;
124795     }
124796 
124797     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
124798     if( nMerge==1
124799      && !isIgnoreEmpty
124800      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
124801     ){
124802       pCsr->nDoclist = apSegment[0]->nDoclist;
124803       if( fts3SegReaderIsPending(apSegment[0]) ){
124804         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
124805         pCsr->aDoclist = pCsr->aBuffer;
124806       }else{
124807         pCsr->aDoclist = apSegment[0]->aDoclist;
124808       }
124809       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
124810     }else{
124811       int nDoclist = 0;           /* Size of doclist */
124812       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
124813 
124814       /* The current term of the first nMerge entries in the array
124815       ** of Fts3SegReader objects is the same. The doclists must be merged
124816       ** and a single term returned with the merged doclist.
124817       */
124818       for(i=0; i<nMerge; i++){
124819         fts3SegReaderFirstDocid(p, apSegment[i]);
124820       }
124821       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
124822       while( apSegment[0]->pOffsetList ){
124823         int j;                    /* Number of segments that share a docid */
124824         char *pList;
124825         int nList;
124826         int nByte;
124827         sqlite3_int64 iDocid = apSegment[0]->iDocid;
124828         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
124829         j = 1;
124830         while( j<nMerge
124831             && apSegment[j]->pOffsetList
124832             && apSegment[j]->iDocid==iDocid
124833         ){
124834           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
124835           j++;
124836         }
124837 
124838         if( isColFilter ){
124839           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
124840         }
124841 
124842         if( !isIgnoreEmpty || nList>0 ){
124843 
124844           /* Calculate the 'docid' delta value to write into the merged
124845           ** doclist. */
124846           sqlite3_int64 iDelta;
124847           if( p->bDescIdx && nDoclist>0 ){
124848             iDelta = iPrev - iDocid;
124849           }else{
124850             iDelta = iDocid - iPrev;
124851           }
124852           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
124853           assert( nDoclist>0 || iDelta==iDocid );
124854 
124855           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
124856           if( nDoclist+nByte>pCsr->nBuffer ){
124857             char *aNew;
124858             pCsr->nBuffer = (nDoclist+nByte)*2;
124859             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
124860             if( !aNew ){
124861               return SQLITE_NOMEM;
124862             }
124863             pCsr->aBuffer = aNew;
124864           }
124865           nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
124866           iPrev = iDocid;
124867           if( isRequirePos ){
124868             memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
124869             nDoclist += nList;
124870             pCsr->aBuffer[nDoclist++] = '\0';
124871           }
124872         }
124873 
124874         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
124875       }
124876       if( nDoclist>0 ){
124877         pCsr->aDoclist = pCsr->aBuffer;
124878         pCsr->nDoclist = nDoclist;
124879         rc = SQLITE_ROW;
124880       }
124881     }
124882     pCsr->nAdvance = nMerge;
124883   }while( rc==SQLITE_OK );
124884 
124885   return rc;
124886 }
124887 
124888 
124889 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
124890   Fts3MultiSegReader *pCsr       /* Cursor object */
124891 ){
124892   if( pCsr ){
124893     int i;
124894     for(i=0; i<pCsr->nSegment; i++){
124895       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
124896     }
124897     sqlite3_free(pCsr->apSegment);
124898     sqlite3_free(pCsr->aBuffer);
124899 
124900     pCsr->nSegment = 0;
124901     pCsr->apSegment = 0;
124902     pCsr->aBuffer = 0;
124903   }
124904 }
124905 
124906 /*
124907 ** Merge all level iLevel segments in the database into a single
124908 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
124909 ** single segment with a level equal to the numerically largest level
124910 ** currently present in the database.
124911 **
124912 ** If this function is called with iLevel<0, but there is only one
124913 ** segment in the database, SQLITE_DONE is returned immediately.
124914 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
124915 ** an SQLite error code is returned.
124916 */
124917 static int fts3SegmentMerge(Fts3Table *p, int iIndex, int iLevel){
124918   int rc;                         /* Return code */
124919   int iIdx = 0;                   /* Index of new segment */
124920   int iNewLevel = 0;              /* Level/index to create new segment at */
124921   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
124922   Fts3SegFilter filter;           /* Segment term filter condition */
124923   Fts3MultiSegReader csr;        /* Cursor to iterate through level(s) */
124924   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
124925 
124926   assert( iLevel==FTS3_SEGCURSOR_ALL
124927        || iLevel==FTS3_SEGCURSOR_PENDING
124928        || iLevel>=0
124929   );
124930   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
124931   assert( iIndex>=0 && iIndex<p->nIndex );
124932 
124933   rc = sqlite3Fts3SegReaderCursor(p, iIndex, iLevel, 0, 0, 1, 0, &csr);
124934   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
124935 
124936   if( iLevel==FTS3_SEGCURSOR_ALL ){
124937     /* This call is to merge all segments in the database to a single
124938     ** segment. The level of the new segment is equal to the the numerically
124939     ** greatest segment level currently present in the database for this
124940     ** index. The idx of the new segment is always 0.  */
124941     if( csr.nSegment==1 ){
124942       rc = SQLITE_DONE;
124943       goto finished;
124944     }
124945     rc = fts3SegmentMaxLevel(p, iIndex, &iNewLevel);
124946     bIgnoreEmpty = 1;
124947 
124948   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
124949     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL;
124950     rc = fts3AllocateSegdirIdx(p, iIndex, 0, &iIdx);
124951   }else{
124952     /* This call is to merge all segments at level iLevel. find the next
124953     ** available segment index at level iLevel+1. The call to
124954     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
124955     ** a single iLevel+2 segment if necessary.  */
124956     rc = fts3AllocateSegdirIdx(p, iIndex, iLevel+1, &iIdx);
124957     iNewLevel = iIndex * FTS3_SEGDIR_MAXLEVEL + iLevel+1;
124958   }
124959   if( rc!=SQLITE_OK ) goto finished;
124960   assert( csr.nSegment>0 );
124961   assert( iNewLevel>=(iIndex*FTS3_SEGDIR_MAXLEVEL) );
124962   assert( iNewLevel<((iIndex+1)*FTS3_SEGDIR_MAXLEVEL) );
124963 
124964   memset(&filter, 0, sizeof(Fts3SegFilter));
124965   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
124966   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
124967 
124968   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
124969   while( SQLITE_OK==rc ){
124970     rc = sqlite3Fts3SegReaderStep(p, &csr);
124971     if( rc!=SQLITE_ROW ) break;
124972     rc = fts3SegWriterAdd(p, &pWriter, 1,
124973         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
124974   }
124975   if( rc!=SQLITE_OK ) goto finished;
124976   assert( pWriter );
124977 
124978   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
124979     rc = fts3DeleteSegdir(p, iIndex, iLevel, csr.apSegment, csr.nSegment);
124980     if( rc!=SQLITE_OK ) goto finished;
124981   }
124982   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
124983 
124984  finished:
124985   fts3SegWriterFree(pWriter);
124986   sqlite3Fts3SegReaderFinish(&csr);
124987   return rc;
124988 }
124989 
124990 
124991 /*
124992 ** Flush the contents of pendingTerms to level 0 segments.
124993 */
124994 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
124995   int rc = SQLITE_OK;
124996   int i;
124997   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
124998     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_PENDING);
124999     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125000   }
125001   sqlite3Fts3PendingTermsClear(p);
125002   return rc;
125003 }
125004 
125005 /*
125006 ** Encode N integers as varints into a blob.
125007 */
125008 static void fts3EncodeIntArray(
125009   int N,             /* The number of integers to encode */
125010   u32 *a,            /* The integer values */
125011   char *zBuf,        /* Write the BLOB here */
125012   int *pNBuf         /* Write number of bytes if zBuf[] used here */
125013 ){
125014   int i, j;
125015   for(i=j=0; i<N; i++){
125016     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
125017   }
125018   *pNBuf = j;
125019 }
125020 
125021 /*
125022 ** Decode a blob of varints into N integers
125023 */
125024 static void fts3DecodeIntArray(
125025   int N,             /* The number of integers to decode */
125026   u32 *a,            /* Write the integer values */
125027   const char *zBuf,  /* The BLOB containing the varints */
125028   int nBuf           /* size of the BLOB */
125029 ){
125030   int i, j;
125031   UNUSED_PARAMETER(nBuf);
125032   for(i=j=0; i<N; i++){
125033     sqlite3_int64 x;
125034     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
125035     assert(j<=nBuf);
125036     a[i] = (u32)(x & 0xffffffff);
125037   }
125038 }
125039 
125040 /*
125041 ** Insert the sizes (in tokens) for each column of the document
125042 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
125043 ** a blob of varints.
125044 */
125045 static void fts3InsertDocsize(
125046   int *pRC,         /* Result code */
125047   Fts3Table *p,     /* Table into which to insert */
125048   u32 *aSz          /* Sizes of each column */
125049 ){
125050   char *pBlob;             /* The BLOB encoding of the document size */
125051   int nBlob;               /* Number of bytes in the BLOB */
125052   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
125053   int rc;                  /* Result code from subfunctions */
125054 
125055   if( *pRC ) return;
125056   pBlob = sqlite3_malloc( 10*p->nColumn );
125057   if( pBlob==0 ){
125058     *pRC = SQLITE_NOMEM;
125059     return;
125060   }
125061   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
125062   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
125063   if( rc ){
125064     sqlite3_free(pBlob);
125065     *pRC = rc;
125066     return;
125067   }
125068   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
125069   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
125070   sqlite3_step(pStmt);
125071   *pRC = sqlite3_reset(pStmt);
125072 }
125073 
125074 /*
125075 ** Record 0 of the %_stat table contains a blob consisting of N varints,
125076 ** where N is the number of user defined columns in the fts3 table plus
125077 ** two. If nCol is the number of user defined columns, then values of the
125078 ** varints are set as follows:
125079 **
125080 **   Varint 0:       Total number of rows in the table.
125081 **
125082 **   Varint 1..nCol: For each column, the total number of tokens stored in
125083 **                   the column for all rows of the table.
125084 **
125085 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
125086 **                   columns of all rows of the table.
125087 **
125088 */
125089 static void fts3UpdateDocTotals(
125090   int *pRC,                       /* The result code */
125091   Fts3Table *p,                   /* Table being updated */
125092   u32 *aSzIns,                    /* Size increases */
125093   u32 *aSzDel,                    /* Size decreases */
125094   int nChng                       /* Change in the number of documents */
125095 ){
125096   char *pBlob;             /* Storage for BLOB written into %_stat */
125097   int nBlob;               /* Size of BLOB written into %_stat */
125098   u32 *a;                  /* Array of integers that becomes the BLOB */
125099   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
125100   int i;                   /* Loop counter */
125101   int rc;                  /* Result code from subfunctions */
125102 
125103   const int nStat = p->nColumn+2;
125104 
125105   if( *pRC ) return;
125106   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
125107   if( a==0 ){
125108     *pRC = SQLITE_NOMEM;
125109     return;
125110   }
125111   pBlob = (char*)&a[nStat];
125112   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
125113   if( rc ){
125114     sqlite3_free(a);
125115     *pRC = rc;
125116     return;
125117   }
125118   if( sqlite3_step(pStmt)==SQLITE_ROW ){
125119     fts3DecodeIntArray(nStat, a,
125120          sqlite3_column_blob(pStmt, 0),
125121          sqlite3_column_bytes(pStmt, 0));
125122   }else{
125123     memset(a, 0, sizeof(u32)*(nStat) );
125124   }
125125   sqlite3_reset(pStmt);
125126   if( nChng<0 && a[0]<(u32)(-nChng) ){
125127     a[0] = 0;
125128   }else{
125129     a[0] += nChng;
125130   }
125131   for(i=0; i<p->nColumn+1; i++){
125132     u32 x = a[i+1];
125133     if( x+aSzIns[i] < aSzDel[i] ){
125134       x = 0;
125135     }else{
125136       x = x + aSzIns[i] - aSzDel[i];
125137     }
125138     a[i+1] = x;
125139   }
125140   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
125141   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
125142   if( rc ){
125143     sqlite3_free(a);
125144     *pRC = rc;
125145     return;
125146   }
125147   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
125148   sqlite3_step(pStmt);
125149   *pRC = sqlite3_reset(pStmt);
125150   sqlite3_free(a);
125151 }
125152 
125153 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
125154   int i;
125155   int bSeenDone = 0;
125156   int rc = SQLITE_OK;
125157   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
125158     rc = fts3SegmentMerge(p, i, FTS3_SEGCURSOR_ALL);
125159     if( rc==SQLITE_DONE ){
125160       bSeenDone = 1;
125161       rc = SQLITE_OK;
125162     }
125163   }
125164   sqlite3Fts3SegmentsClose(p);
125165   sqlite3Fts3PendingTermsClear(p);
125166 
125167   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
125168 }
125169 
125170 /*
125171 ** Handle a 'special' INSERT of the form:
125172 **
125173 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
125174 **
125175 ** Argument pVal contains the result of <expr>. Currently the only
125176 ** meaningful value to insert is the text 'optimize'.
125177 */
125178 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
125179   int rc;                         /* Return Code */
125180   const char *zVal = (const char *)sqlite3_value_text(pVal);
125181   int nVal = sqlite3_value_bytes(pVal);
125182 
125183   if( !zVal ){
125184     return SQLITE_NOMEM;
125185   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
125186     rc = fts3DoOptimize(p, 0);
125187 #ifdef SQLITE_TEST
125188   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
125189     p->nNodeSize = atoi(&zVal[9]);
125190     rc = SQLITE_OK;
125191   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
125192     p->nMaxPendingData = atoi(&zVal[11]);
125193     rc = SQLITE_OK;
125194 #endif
125195   }else{
125196     rc = SQLITE_ERROR;
125197   }
125198 
125199   return rc;
125200 }
125201 
125202 /*
125203 ** Delete all cached deferred doclists. Deferred doclists are cached
125204 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
125205 */
125206 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
125207   Fts3DeferredToken *pDef;
125208   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
125209     fts3PendingListDelete(pDef->pList);
125210     pDef->pList = 0;
125211   }
125212 }
125213 
125214 /*
125215 ** Free all entries in the pCsr->pDeffered list. Entries are added to
125216 ** this list using sqlite3Fts3DeferToken().
125217 */
125218 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
125219   Fts3DeferredToken *pDef;
125220   Fts3DeferredToken *pNext;
125221   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
125222     pNext = pDef->pNext;
125223     fts3PendingListDelete(pDef->pList);
125224     sqlite3_free(pDef);
125225   }
125226   pCsr->pDeferred = 0;
125227 }
125228 
125229 /*
125230 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
125231 ** based on the row that pCsr currently points to.
125232 **
125233 ** A deferred-doclist is like any other doclist with position information
125234 ** included, except that it only contains entries for a single row of the
125235 ** table, not for all rows.
125236 */
125237 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
125238   int rc = SQLITE_OK;             /* Return code */
125239   if( pCsr->pDeferred ){
125240     int i;                        /* Used to iterate through table columns */
125241     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
125242     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
125243 
125244     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
125245     sqlite3_tokenizer *pT = p->pTokenizer;
125246     sqlite3_tokenizer_module const *pModule = pT->pModule;
125247 
125248     assert( pCsr->isRequireSeek==0 );
125249     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
125250 
125251     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
125252       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
125253       sqlite3_tokenizer_cursor *pTC = 0;
125254 
125255       rc = pModule->xOpen(pT, zText, -1, &pTC);
125256       while( rc==SQLITE_OK ){
125257         char const *zToken;       /* Buffer containing token */
125258         int nToken;               /* Number of bytes in token */
125259         int iDum1, iDum2;         /* Dummy variables */
125260         int iPos;                 /* Position of token in zText */
125261 
125262         pTC->pTokenizer = pT;
125263         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
125264         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
125265           Fts3PhraseToken *pPT = pDef->pToken;
125266           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
125267            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
125268            && (0==memcmp(zToken, pPT->z, pPT->n))
125269           ){
125270             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
125271           }
125272         }
125273       }
125274       if( pTC ) pModule->xClose(pTC);
125275       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
125276     }
125277 
125278     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
125279       if( pDef->pList ){
125280         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
125281       }
125282     }
125283   }
125284 
125285   return rc;
125286 }
125287 
125288 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
125289   Fts3DeferredToken *p,
125290   char **ppData,
125291   int *pnData
125292 ){
125293   char *pRet;
125294   int nSkip;
125295   sqlite3_int64 dummy;
125296 
125297   *ppData = 0;
125298   *pnData = 0;
125299 
125300   if( p->pList==0 ){
125301     return SQLITE_OK;
125302   }
125303 
125304   pRet = (char *)sqlite3_malloc(p->pList->nData);
125305   if( !pRet ) return SQLITE_NOMEM;
125306 
125307   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
125308   *pnData = p->pList->nData - nSkip;
125309   *ppData = pRet;
125310 
125311   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
125312   return SQLITE_OK;
125313 }
125314 
125315 /*
125316 ** Add an entry for token pToken to the pCsr->pDeferred list.
125317 */
125318 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
125319   Fts3Cursor *pCsr,               /* Fts3 table cursor */
125320   Fts3PhraseToken *pToken,        /* Token to defer */
125321   int iCol                        /* Column that token must appear in (or -1) */
125322 ){
125323   Fts3DeferredToken *pDeferred;
125324   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
125325   if( !pDeferred ){
125326     return SQLITE_NOMEM;
125327   }
125328   memset(pDeferred, 0, sizeof(*pDeferred));
125329   pDeferred->pToken = pToken;
125330   pDeferred->pNext = pCsr->pDeferred;
125331   pDeferred->iCol = iCol;
125332   pCsr->pDeferred = pDeferred;
125333 
125334   assert( pToken->pDeferred==0 );
125335   pToken->pDeferred = pDeferred;
125336 
125337   return SQLITE_OK;
125338 }
125339 
125340 /*
125341 ** SQLite value pRowid contains the rowid of a row that may or may not be
125342 ** present in the FTS3 table. If it is, delete it and adjust the contents
125343 ** of subsiduary data structures accordingly.
125344 */
125345 static int fts3DeleteByRowid(
125346   Fts3Table *p,
125347   sqlite3_value *pRowid,
125348   int *pnDoc,
125349   u32 *aSzDel
125350 ){
125351   int isEmpty = 0;
125352   int rc = fts3IsEmpty(p, pRowid, &isEmpty);
125353   if( rc==SQLITE_OK ){
125354     if( isEmpty ){
125355       /* Deleting this row means the whole table is empty. In this case
125356       ** delete the contents of all three tables and throw away any
125357       ** data in the pendingTerms hash table.  */
125358       rc = fts3DeleteAll(p);
125359       *pnDoc = *pnDoc - 1;
125360     }else{
125361       sqlite3_int64 iRemove = sqlite3_value_int64(pRowid);
125362       rc = fts3PendingTermsDocid(p, iRemove);
125363       fts3DeleteTerms(&rc, p, pRowid, aSzDel);
125364       fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
125365       if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
125366       if( p->bHasDocsize ){
125367         fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
125368       }
125369     }
125370   }
125371 
125372   return rc;
125373 }
125374 
125375 /*
125376 ** This function does the work for the xUpdate method of FTS3 virtual
125377 ** tables.
125378 */
125379 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
125380   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
125381   int nArg,                       /* Size of argument array */
125382   sqlite3_value **apVal,          /* Array of arguments */
125383   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
125384 ){
125385   Fts3Table *p = (Fts3Table *)pVtab;
125386   int rc = SQLITE_OK;             /* Return Code */
125387   int isRemove = 0;               /* True for an UPDATE or DELETE */
125388   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
125389   u32 *aSzIns = 0;                /* Sizes of inserted documents */
125390   u32 *aSzDel;                    /* Sizes of deleted documents */
125391   int nChng = 0;                  /* Net change in number of documents */
125392   int bInsertDone = 0;
125393 
125394   assert( p->pSegments==0 );
125395 
125396   /* Check for a "special" INSERT operation. One of the form:
125397   **
125398   **   INSERT INTO xyz(xyz) VALUES('command');
125399   */
125400   if( nArg>1
125401    && sqlite3_value_type(apVal[0])==SQLITE_NULL
125402    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
125403   ){
125404     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
125405     goto update_out;
125406   }
125407 
125408   /* Allocate space to hold the change in document sizes */
125409   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
125410   if( aSzIns==0 ){
125411     rc = SQLITE_NOMEM;
125412     goto update_out;
125413   }
125414   aSzDel = &aSzIns[p->nColumn+1];
125415   memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
125416 
125417   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
125418   ** value, then this operation requires constraint handling.
125419   **
125420   ** If the on-conflict mode is REPLACE, this means that the existing row
125421   ** should be deleted from the database before inserting the new row. Or,
125422   ** if the on-conflict mode is other than REPLACE, then this method must
125423   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
125424   ** modify the database file.
125425   */
125426   if( nArg>1 ){
125427     /* Find the value object that holds the new rowid value. */
125428     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
125429     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
125430       pNewRowid = apVal[1];
125431     }
125432 
125433     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
125434         sqlite3_value_type(apVal[0])==SQLITE_NULL
125435      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
125436     )){
125437       /* The new rowid is not NULL (in this case the rowid will be
125438       ** automatically assigned and there is no chance of a conflict), and
125439       ** the statement is either an INSERT or an UPDATE that modifies the
125440       ** rowid column. So if the conflict mode is REPLACE, then delete any
125441       ** existing row with rowid=pNewRowid.
125442       **
125443       ** Or, if the conflict mode is not REPLACE, insert the new record into
125444       ** the %_content table. If we hit the duplicate rowid constraint (or any
125445       ** other error) while doing so, return immediately.
125446       **
125447       ** This branch may also run if pNewRowid contains a value that cannot
125448       ** be losslessly converted to an integer. In this case, the eventual
125449       ** call to fts3InsertData() (either just below or further on in this
125450       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
125451       ** invoked, it will delete zero rows (since no row will have
125452       ** docid=$pNewRowid if $pNewRowid is not an integer value).
125453       */
125454       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
125455         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
125456       }else{
125457         rc = fts3InsertData(p, apVal, pRowid);
125458         bInsertDone = 1;
125459       }
125460     }
125461   }
125462   if( rc!=SQLITE_OK ){
125463     goto update_out;
125464   }
125465 
125466   /* If this is a DELETE or UPDATE operation, remove the old record. */
125467   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
125468     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
125469     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
125470     isRemove = 1;
125471     iRemove = sqlite3_value_int64(apVal[0]);
125472   }
125473 
125474   /* If this is an INSERT or UPDATE operation, insert the new record. */
125475   if( nArg>1 && rc==SQLITE_OK ){
125476     if( bInsertDone==0 ){
125477       rc = fts3InsertData(p, apVal, pRowid);
125478       if( rc==SQLITE_CONSTRAINT ) rc = SQLITE_CORRUPT_VTAB;
125479     }
125480     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
125481       rc = fts3PendingTermsDocid(p, *pRowid);
125482     }
125483     if( rc==SQLITE_OK ){
125484       rc = fts3InsertTerms(p, apVal, aSzIns);
125485     }
125486     if( p->bHasDocsize ){
125487       fts3InsertDocsize(&rc, p, aSzIns);
125488     }
125489     nChng++;
125490   }
125491 
125492   if( p->bHasStat ){
125493     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
125494   }
125495 
125496  update_out:
125497   sqlite3_free(aSzIns);
125498   sqlite3Fts3SegmentsClose(p);
125499   return rc;
125500 }
125501 
125502 /*
125503 ** Flush any data in the pending-terms hash table to disk. If successful,
125504 ** merge all segments in the database (including the new segment, if
125505 ** there was any data to flush) into a single segment.
125506 */
125507 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
125508   int rc;
125509   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
125510   if( rc==SQLITE_OK ){
125511     rc = fts3DoOptimize(p, 1);
125512     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
125513       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
125514       if( rc2!=SQLITE_OK ) rc = rc2;
125515     }else{
125516       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
125517       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
125518     }
125519   }
125520   sqlite3Fts3SegmentsClose(p);
125521   return rc;
125522 }
125523 
125524 #endif
125525 
125526 /************** End of fts3_write.c ******************************************/
125527 /************** Begin file fts3_snippet.c ************************************/
125528 /*
125529 ** 2009 Oct 23
125530 **
125531 ** The author disclaims copyright to this source code.  In place of
125532 ** a legal notice, here is a blessing:
125533 **
125534 **    May you do good and not evil.
125535 **    May you find forgiveness for yourself and forgive others.
125536 **    May you share freely, never taking more than you give.
125537 **
125538 ******************************************************************************
125539 */
125540 
125541 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125542 
125543 /* #include <string.h> */
125544 /* #include <assert.h> */
125545 
125546 /*
125547 ** Characters that may appear in the second argument to matchinfo().
125548 */
125549 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
125550 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
125551 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
125552 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
125553 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
125554 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
125555 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
125556 
125557 /*
125558 ** The default value for the second argument to matchinfo().
125559 */
125560 #define FTS3_MATCHINFO_DEFAULT   "pcx"
125561 
125562 
125563 /*
125564 ** Used as an fts3ExprIterate() context when loading phrase doclists to
125565 ** Fts3Expr.aDoclist[]/nDoclist.
125566 */
125567 typedef struct LoadDoclistCtx LoadDoclistCtx;
125568 struct LoadDoclistCtx {
125569   Fts3Cursor *pCsr;               /* FTS3 Cursor */
125570   int nPhrase;                    /* Number of phrases seen so far */
125571   int nToken;                     /* Number of tokens seen so far */
125572 };
125573 
125574 /*
125575 ** The following types are used as part of the implementation of the
125576 ** fts3BestSnippet() routine.
125577 */
125578 typedef struct SnippetIter SnippetIter;
125579 typedef struct SnippetPhrase SnippetPhrase;
125580 typedef struct SnippetFragment SnippetFragment;
125581 
125582 struct SnippetIter {
125583   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
125584   int iCol;                       /* Extract snippet from this column */
125585   int nSnippet;                   /* Requested snippet length (in tokens) */
125586   int nPhrase;                    /* Number of phrases in query */
125587   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
125588   int iCurrent;                   /* First token of current snippet */
125589 };
125590 
125591 struct SnippetPhrase {
125592   int nToken;                     /* Number of tokens in phrase */
125593   char *pList;                    /* Pointer to start of phrase position list */
125594   int iHead;                      /* Next value in position list */
125595   char *pHead;                    /* Position list data following iHead */
125596   int iTail;                      /* Next value in trailing position list */
125597   char *pTail;                    /* Position list data following iTail */
125598 };
125599 
125600 struct SnippetFragment {
125601   int iCol;                       /* Column snippet is extracted from */
125602   int iPos;                       /* Index of first token in snippet */
125603   u64 covered;                    /* Mask of query phrases covered */
125604   u64 hlmask;                     /* Mask of snippet terms to highlight */
125605 };
125606 
125607 /*
125608 ** This type is used as an fts3ExprIterate() context object while
125609 ** accumulating the data returned by the matchinfo() function.
125610 */
125611 typedef struct MatchInfo MatchInfo;
125612 struct MatchInfo {
125613   Fts3Cursor *pCursor;            /* FTS3 Cursor */
125614   int nCol;                       /* Number of columns in table */
125615   int nPhrase;                    /* Number of matchable phrases in query */
125616   sqlite3_int64 nDoc;             /* Number of docs in database */
125617   u32 *aMatchinfo;                /* Pre-allocated buffer */
125618 };
125619 
125620 
125621 
125622 /*
125623 ** The snippet() and offsets() functions both return text values. An instance
125624 ** of the following structure is used to accumulate those values while the
125625 ** functions are running. See fts3StringAppend() for details.
125626 */
125627 typedef struct StrBuffer StrBuffer;
125628 struct StrBuffer {
125629   char *z;                        /* Pointer to buffer containing string */
125630   int n;                          /* Length of z in bytes (excl. nul-term) */
125631   int nAlloc;                     /* Allocated size of buffer z in bytes */
125632 };
125633 
125634 
125635 /*
125636 ** This function is used to help iterate through a position-list. A position
125637 ** list is a list of unique integers, sorted from smallest to largest. Each
125638 ** element of the list is represented by an FTS3 varint that takes the value
125639 ** of the difference between the current element and the previous one plus
125640 ** two. For example, to store the position-list:
125641 **
125642 **     4 9 113
125643 **
125644 ** the three varints:
125645 **
125646 **     6 7 106
125647 **
125648 ** are encoded.
125649 **
125650 ** When this function is called, *pp points to the start of an element of
125651 ** the list. *piPos contains the value of the previous entry in the list.
125652 ** After it returns, *piPos contains the value of the next element of the
125653 ** list and *pp is advanced to the following varint.
125654 */
125655 static void fts3GetDeltaPosition(char **pp, int *piPos){
125656   int iVal;
125657   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
125658   *piPos += (iVal-2);
125659 }
125660 
125661 /*
125662 ** Helper function for fts3ExprIterate() (see below).
125663 */
125664 static int fts3ExprIterate2(
125665   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
125666   int *piPhrase,                  /* Pointer to phrase counter */
125667   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
125668   void *pCtx                      /* Second argument to pass to callback */
125669 ){
125670   int rc;                         /* Return code */
125671   int eType = pExpr->eType;       /* Type of expression node pExpr */
125672 
125673   if( eType!=FTSQUERY_PHRASE ){
125674     assert( pExpr->pLeft && pExpr->pRight );
125675     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
125676     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
125677       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
125678     }
125679   }else{
125680     rc = x(pExpr, *piPhrase, pCtx);
125681     (*piPhrase)++;
125682   }
125683   return rc;
125684 }
125685 
125686 /*
125687 ** Iterate through all phrase nodes in an FTS3 query, except those that
125688 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
125689 ** For each phrase node found, the supplied callback function is invoked.
125690 **
125691 ** If the callback function returns anything other than SQLITE_OK,
125692 ** the iteration is abandoned and the error code returned immediately.
125693 ** Otherwise, SQLITE_OK is returned after a callback has been made for
125694 ** all eligible phrase nodes.
125695 */
125696 static int fts3ExprIterate(
125697   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
125698   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
125699   void *pCtx                      /* Second argument to pass to callback */
125700 ){
125701   int iPhrase = 0;                /* Variable used as the phrase counter */
125702   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
125703 }
125704 
125705 /*
125706 ** This is an fts3ExprIterate() callback used while loading the doclists
125707 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
125708 ** fts3ExprLoadDoclists().
125709 */
125710 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
125711   int rc = SQLITE_OK;
125712   Fts3Phrase *pPhrase = pExpr->pPhrase;
125713   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
125714 
125715   UNUSED_PARAMETER(iPhrase);
125716 
125717   p->nPhrase++;
125718   p->nToken += pPhrase->nToken;
125719 
125720   return rc;
125721 }
125722 
125723 /*
125724 ** Load the doclists for each phrase in the query associated with FTS3 cursor
125725 ** pCsr.
125726 **
125727 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
125728 ** phrases in the expression (all phrases except those directly or
125729 ** indirectly descended from the right-hand-side of a NOT operator). If
125730 ** pnToken is not NULL, then it is set to the number of tokens in all
125731 ** matchable phrases of the expression.
125732 */
125733 static int fts3ExprLoadDoclists(
125734   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
125735   int *pnPhrase,                  /* OUT: Number of phrases in query */
125736   int *pnToken                    /* OUT: Number of tokens in query */
125737 ){
125738   int rc;                         /* Return Code */
125739   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
125740   sCtx.pCsr = pCsr;
125741   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
125742   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
125743   if( pnToken ) *pnToken = sCtx.nToken;
125744   return rc;
125745 }
125746 
125747 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
125748   (*(int *)ctx)++;
125749   UNUSED_PARAMETER(pExpr);
125750   UNUSED_PARAMETER(iPhrase);
125751   return SQLITE_OK;
125752 }
125753 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
125754   int nPhrase = 0;
125755   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
125756   return nPhrase;
125757 }
125758 
125759 /*
125760 ** Advance the position list iterator specified by the first two
125761 ** arguments so that it points to the first element with a value greater
125762 ** than or equal to parameter iNext.
125763 */
125764 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
125765   char *pIter = *ppIter;
125766   if( pIter ){
125767     int iIter = *piIter;
125768 
125769     while( iIter<iNext ){
125770       if( 0==(*pIter & 0xFE) ){
125771         iIter = -1;
125772         pIter = 0;
125773         break;
125774       }
125775       fts3GetDeltaPosition(&pIter, &iIter);
125776     }
125777 
125778     *piIter = iIter;
125779     *ppIter = pIter;
125780   }
125781 }
125782 
125783 /*
125784 ** Advance the snippet iterator to the next candidate snippet.
125785 */
125786 static int fts3SnippetNextCandidate(SnippetIter *pIter){
125787   int i;                          /* Loop counter */
125788 
125789   if( pIter->iCurrent<0 ){
125790     /* The SnippetIter object has just been initialized. The first snippet
125791     ** candidate always starts at offset 0 (even if this candidate has a
125792     ** score of 0.0).
125793     */
125794     pIter->iCurrent = 0;
125795 
125796     /* Advance the 'head' iterator of each phrase to the first offset that
125797     ** is greater than or equal to (iNext+nSnippet).
125798     */
125799     for(i=0; i<pIter->nPhrase; i++){
125800       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
125801       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
125802     }
125803   }else{
125804     int iStart;
125805     int iEnd = 0x7FFFFFFF;
125806 
125807     for(i=0; i<pIter->nPhrase; i++){
125808       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
125809       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
125810         iEnd = pPhrase->iHead;
125811       }
125812     }
125813     if( iEnd==0x7FFFFFFF ){
125814       return 1;
125815     }
125816 
125817     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
125818     for(i=0; i<pIter->nPhrase; i++){
125819       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
125820       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
125821       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
125822     }
125823   }
125824 
125825   return 0;
125826 }
125827 
125828 /*
125829 ** Retrieve information about the current candidate snippet of snippet
125830 ** iterator pIter.
125831 */
125832 static void fts3SnippetDetails(
125833   SnippetIter *pIter,             /* Snippet iterator */
125834   u64 mCovered,                   /* Bitmask of phrases already covered */
125835   int *piToken,                   /* OUT: First token of proposed snippet */
125836   int *piScore,                   /* OUT: "Score" for this snippet */
125837   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
125838   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
125839 ){
125840   int iStart = pIter->iCurrent;   /* First token of snippet */
125841   int iScore = 0;                 /* Score of this snippet */
125842   int i;                          /* Loop counter */
125843   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
125844   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
125845 
125846   for(i=0; i<pIter->nPhrase; i++){
125847     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
125848     if( pPhrase->pTail ){
125849       char *pCsr = pPhrase->pTail;
125850       int iCsr = pPhrase->iTail;
125851 
125852       while( iCsr<(iStart+pIter->nSnippet) ){
125853         int j;
125854         u64 mPhrase = (u64)1 << i;
125855         u64 mPos = (u64)1 << (iCsr - iStart);
125856         assert( iCsr>=iStart );
125857         if( (mCover|mCovered)&mPhrase ){
125858           iScore++;
125859         }else{
125860           iScore += 1000;
125861         }
125862         mCover |= mPhrase;
125863 
125864         for(j=0; j<pPhrase->nToken; j++){
125865           mHighlight |= (mPos>>j);
125866         }
125867 
125868         if( 0==(*pCsr & 0x0FE) ) break;
125869         fts3GetDeltaPosition(&pCsr, &iCsr);
125870       }
125871     }
125872   }
125873 
125874   /* Set the output variables before returning. */
125875   *piToken = iStart;
125876   *piScore = iScore;
125877   *pmCover = mCover;
125878   *pmHighlight = mHighlight;
125879 }
125880 
125881 /*
125882 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
125883 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
125884 */
125885 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
125886   SnippetIter *p = (SnippetIter *)ctx;
125887   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
125888   char *pCsr;
125889 
125890   pPhrase->nToken = pExpr->pPhrase->nToken;
125891 
125892   pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
125893   if( pCsr ){
125894     int iFirst = 0;
125895     pPhrase->pList = pCsr;
125896     fts3GetDeltaPosition(&pCsr, &iFirst);
125897     pPhrase->pHead = pCsr;
125898     pPhrase->pTail = pCsr;
125899     pPhrase->iHead = iFirst;
125900     pPhrase->iTail = iFirst;
125901   }else{
125902     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
125903   }
125904 
125905   return SQLITE_OK;
125906 }
125907 
125908 /*
125909 ** Select the fragment of text consisting of nFragment contiguous tokens
125910 ** from column iCol that represent the "best" snippet. The best snippet
125911 ** is the snippet with the highest score, where scores are calculated
125912 ** by adding:
125913 **
125914 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
125915 **
125916 **   (b) +1000 points for the first occurence of each matchable phrase in
125917 **       the snippet for which the corresponding mCovered bit is not set.
125918 **
125919 ** The selected snippet parameters are stored in structure *pFragment before
125920 ** returning. The score of the selected snippet is stored in *piScore
125921 ** before returning.
125922 */
125923 static int fts3BestSnippet(
125924   int nSnippet,                   /* Desired snippet length */
125925   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
125926   int iCol,                       /* Index of column to create snippet from */
125927   u64 mCovered,                   /* Mask of phrases already covered */
125928   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
125929   SnippetFragment *pFragment,     /* OUT: Best snippet found */
125930   int *piScore                    /* OUT: Score of snippet pFragment */
125931 ){
125932   int rc;                         /* Return Code */
125933   int nList;                      /* Number of phrases in expression */
125934   SnippetIter sIter;              /* Iterates through snippet candidates */
125935   int nByte;                      /* Number of bytes of space to allocate */
125936   int iBestScore = -1;            /* Best snippet score found so far */
125937   int i;                          /* Loop counter */
125938 
125939   memset(&sIter, 0, sizeof(sIter));
125940 
125941   /* Iterate through the phrases in the expression to count them. The same
125942   ** callback makes sure the doclists are loaded for each phrase.
125943   */
125944   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
125945   if( rc!=SQLITE_OK ){
125946     return rc;
125947   }
125948 
125949   /* Now that it is known how many phrases there are, allocate and zero
125950   ** the required space using malloc().
125951   */
125952   nByte = sizeof(SnippetPhrase) * nList;
125953   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
125954   if( !sIter.aPhrase ){
125955     return SQLITE_NOMEM;
125956   }
125957   memset(sIter.aPhrase, 0, nByte);
125958 
125959   /* Initialize the contents of the SnippetIter object. Then iterate through
125960   ** the set of phrases in the expression to populate the aPhrase[] array.
125961   */
125962   sIter.pCsr = pCsr;
125963   sIter.iCol = iCol;
125964   sIter.nSnippet = nSnippet;
125965   sIter.nPhrase = nList;
125966   sIter.iCurrent = -1;
125967   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
125968 
125969   /* Set the *pmSeen output variable. */
125970   for(i=0; i<nList; i++){
125971     if( sIter.aPhrase[i].pHead ){
125972       *pmSeen |= (u64)1 << i;
125973     }
125974   }
125975 
125976   /* Loop through all candidate snippets. Store the best snippet in
125977   ** *pFragment. Store its associated 'score' in iBestScore.
125978   */
125979   pFragment->iCol = iCol;
125980   while( !fts3SnippetNextCandidate(&sIter) ){
125981     int iPos;
125982     int iScore;
125983     u64 mCover;
125984     u64 mHighlight;
125985     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
125986     assert( iScore>=0 );
125987     if( iScore>iBestScore ){
125988       pFragment->iPos = iPos;
125989       pFragment->hlmask = mHighlight;
125990       pFragment->covered = mCover;
125991       iBestScore = iScore;
125992     }
125993   }
125994 
125995   sqlite3_free(sIter.aPhrase);
125996   *piScore = iBestScore;
125997   return SQLITE_OK;
125998 }
125999 
126000 
126001 /*
126002 ** Append a string to the string-buffer passed as the first argument.
126003 **
126004 ** If nAppend is negative, then the length of the string zAppend is
126005 ** determined using strlen().
126006 */
126007 static int fts3StringAppend(
126008   StrBuffer *pStr,                /* Buffer to append to */
126009   const char *zAppend,            /* Pointer to data to append to buffer */
126010   int nAppend                     /* Size of zAppend in bytes (or -1) */
126011 ){
126012   if( nAppend<0 ){
126013     nAppend = (int)strlen(zAppend);
126014   }
126015 
126016   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
126017   ** to grow the buffer until so that it is big enough to accomadate the
126018   ** appended data.
126019   */
126020   if( pStr->n+nAppend+1>=pStr->nAlloc ){
126021     int nAlloc = pStr->nAlloc+nAppend+100;
126022     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
126023     if( !zNew ){
126024       return SQLITE_NOMEM;
126025     }
126026     pStr->z = zNew;
126027     pStr->nAlloc = nAlloc;
126028   }
126029 
126030   /* Append the data to the string buffer. */
126031   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
126032   pStr->n += nAppend;
126033   pStr->z[pStr->n] = '\0';
126034 
126035   return SQLITE_OK;
126036 }
126037 
126038 /*
126039 ** The fts3BestSnippet() function often selects snippets that end with a
126040 ** query term. That is, the final term of the snippet is always a term
126041 ** that requires highlighting. For example, if 'X' is a highlighted term
126042 ** and '.' is a non-highlighted term, BestSnippet() may select:
126043 **
126044 **     ........X.....X
126045 **
126046 ** This function "shifts" the beginning of the snippet forward in the
126047 ** document so that there are approximately the same number of
126048 ** non-highlighted terms to the right of the final highlighted term as there
126049 ** are to the left of the first highlighted term. For example, to this:
126050 **
126051 **     ....X.....X....
126052 **
126053 ** This is done as part of extracting the snippet text, not when selecting
126054 ** the snippet. Snippet selection is done based on doclists only, so there
126055 ** is no way for fts3BestSnippet() to know whether or not the document
126056 ** actually contains terms that follow the final highlighted term.
126057 */
126058 static int fts3SnippetShift(
126059   Fts3Table *pTab,                /* FTS3 table snippet comes from */
126060   int nSnippet,                   /* Number of tokens desired for snippet */
126061   const char *zDoc,               /* Document text to extract snippet from */
126062   int nDoc,                       /* Size of buffer zDoc in bytes */
126063   int *piPos,                     /* IN/OUT: First token of snippet */
126064   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
126065 ){
126066   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
126067 
126068   if( hlmask ){
126069     int nLeft;                    /* Tokens to the left of first highlight */
126070     int nRight;                   /* Tokens to the right of last highlight */
126071     int nDesired;                 /* Ideal number of tokens to shift forward */
126072 
126073     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
126074     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
126075     nDesired = (nLeft-nRight)/2;
126076 
126077     /* Ideally, the start of the snippet should be pushed forward in the
126078     ** document nDesired tokens. This block checks if there are actually
126079     ** nDesired tokens to the right of the snippet. If so, *piPos and
126080     ** *pHlMask are updated to shift the snippet nDesired tokens to the
126081     ** right. Otherwise, the snippet is shifted by the number of tokens
126082     ** available.
126083     */
126084     if( nDesired>0 ){
126085       int nShift;                 /* Number of tokens to shift snippet by */
126086       int iCurrent = 0;           /* Token counter */
126087       int rc;                     /* Return Code */
126088       sqlite3_tokenizer_module *pMod;
126089       sqlite3_tokenizer_cursor *pC;
126090       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
126091 
126092       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
126093       ** or more tokens in zDoc/nDoc.
126094       */
126095       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
126096       if( rc!=SQLITE_OK ){
126097         return rc;
126098       }
126099       pC->pTokenizer = pTab->pTokenizer;
126100       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
126101         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
126102         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
126103       }
126104       pMod->xClose(pC);
126105       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
126106 
126107       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
126108       assert( nShift<=nDesired );
126109       if( nShift>0 ){
126110         *piPos += nShift;
126111         *pHlmask = hlmask >> nShift;
126112       }
126113     }
126114   }
126115   return SQLITE_OK;
126116 }
126117 
126118 /*
126119 ** Extract the snippet text for fragment pFragment from cursor pCsr and
126120 ** append it to string buffer pOut.
126121 */
126122 static int fts3SnippetText(
126123   Fts3Cursor *pCsr,               /* FTS3 Cursor */
126124   SnippetFragment *pFragment,     /* Snippet to extract */
126125   int iFragment,                  /* Fragment number */
126126   int isLast,                     /* True for final fragment in snippet */
126127   int nSnippet,                   /* Number of tokens in extracted snippet */
126128   const char *zOpen,              /* String inserted before highlighted term */
126129   const char *zClose,             /* String inserted after highlighted term */
126130   const char *zEllipsis,          /* String inserted between snippets */
126131   StrBuffer *pOut                 /* Write output here */
126132 ){
126133   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126134   int rc;                         /* Return code */
126135   const char *zDoc;               /* Document text to extract snippet from */
126136   int nDoc;                       /* Size of zDoc in bytes */
126137   int iCurrent = 0;               /* Current token number of document */
126138   int iEnd = 0;                   /* Byte offset of end of current token */
126139   int isShiftDone = 0;            /* True after snippet is shifted */
126140   int iPos = pFragment->iPos;     /* First token of snippet */
126141   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
126142   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
126143   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
126144   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
126145   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
126146   int DUMMY1;                     /* Dummy argument used with tokenizer */
126147 
126148   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
126149   if( zDoc==0 ){
126150     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
126151       return SQLITE_NOMEM;
126152     }
126153     return SQLITE_OK;
126154   }
126155   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
126156 
126157   /* Open a token cursor on the document. */
126158   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
126159   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
126160   if( rc!=SQLITE_OK ){
126161     return rc;
126162   }
126163   pC->pTokenizer = pTab->pTokenizer;
126164 
126165   while( rc==SQLITE_OK ){
126166     int iBegin;                   /* Offset in zDoc of start of token */
126167     int iFin;                     /* Offset in zDoc of end of token */
126168     int isHighlight;              /* True for highlighted terms */
126169 
126170     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
126171     if( rc!=SQLITE_OK ){
126172       if( rc==SQLITE_DONE ){
126173         /* Special case - the last token of the snippet is also the last token
126174         ** of the column. Append any punctuation that occurred between the end
126175         ** of the previous token and the end of the document to the output.
126176         ** Then break out of the loop. */
126177         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
126178       }
126179       break;
126180     }
126181     if( iCurrent<iPos ){ continue; }
126182 
126183     if( !isShiftDone ){
126184       int n = nDoc - iBegin;
126185       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
126186       isShiftDone = 1;
126187 
126188       /* Now that the shift has been done, check if the initial "..." are
126189       ** required. They are required if (a) this is not the first fragment,
126190       ** or (b) this fragment does not begin at position 0 of its column.
126191       */
126192       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
126193         rc = fts3StringAppend(pOut, zEllipsis, -1);
126194       }
126195       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
126196     }
126197 
126198     if( iCurrent>=(iPos+nSnippet) ){
126199       if( isLast ){
126200         rc = fts3StringAppend(pOut, zEllipsis, -1);
126201       }
126202       break;
126203     }
126204 
126205     /* Set isHighlight to true if this term should be highlighted. */
126206     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
126207 
126208     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
126209     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
126210     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
126211     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
126212 
126213     iEnd = iFin;
126214   }
126215 
126216   pMod->xClose(pC);
126217   return rc;
126218 }
126219 
126220 
126221 /*
126222 ** This function is used to count the entries in a column-list (a
126223 ** delta-encoded list of term offsets within a single column of a single
126224 ** row). When this function is called, *ppCollist should point to the
126225 ** beginning of the first varint in the column-list (the varint that
126226 ** contains the position of the first matching term in the column data).
126227 ** Before returning, *ppCollist is set to point to the first byte after
126228 ** the last varint in the column-list (either the 0x00 signifying the end
126229 ** of the position-list, or the 0x01 that precedes the column number of
126230 ** the next column in the position-list).
126231 **
126232 ** The number of elements in the column-list is returned.
126233 */
126234 static int fts3ColumnlistCount(char **ppCollist){
126235   char *pEnd = *ppCollist;
126236   char c = 0;
126237   int nEntry = 0;
126238 
126239   /* A column-list is terminated by either a 0x01 or 0x00. */
126240   while( 0xFE & (*pEnd | c) ){
126241     c = *pEnd++ & 0x80;
126242     if( !c ) nEntry++;
126243   }
126244 
126245   *ppCollist = pEnd;
126246   return nEntry;
126247 }
126248 
126249 /*
126250 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
126251 ** for a single query.
126252 **
126253 ** fts3ExprIterate() callback to load the 'global' elements of a
126254 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
126255 ** of the matchinfo array that are constant for all rows returned by the
126256 ** current query.
126257 **
126258 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
126259 ** function populates Matchinfo.aMatchinfo[] as follows:
126260 **
126261 **   for(iCol=0; iCol<nCol; iCol++){
126262 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
126263 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
126264 **   }
126265 **
126266 ** where X is the number of matches for phrase iPhrase is column iCol of all
126267 ** rows of the table. Y is the number of rows for which column iCol contains
126268 ** at least one instance of phrase iPhrase.
126269 **
126270 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
126271 ** Y values are set to nDoc, where nDoc is the number of documents in the
126272 ** file system. This is done because the full-text index doclist is required
126273 ** to calculate these values properly, and the full-text index doclist is
126274 ** not available for deferred tokens.
126275 */
126276 static int fts3ExprGlobalHitsCb(
126277   Fts3Expr *pExpr,                /* Phrase expression node */
126278   int iPhrase,                    /* Phrase number (numbered from zero) */
126279   void *pCtx                      /* Pointer to MatchInfo structure */
126280 ){
126281   MatchInfo *p = (MatchInfo *)pCtx;
126282   return sqlite3Fts3EvalPhraseStats(
126283       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
126284   );
126285 }
126286 
126287 /*
126288 ** fts3ExprIterate() callback used to collect the "local" part of the
126289 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
126290 ** array that are different for each row returned by the query.
126291 */
126292 static int fts3ExprLocalHitsCb(
126293   Fts3Expr *pExpr,                /* Phrase expression node */
126294   int iPhrase,                    /* Phrase number */
126295   void *pCtx                      /* Pointer to MatchInfo structure */
126296 ){
126297   MatchInfo *p = (MatchInfo *)pCtx;
126298   int iStart = iPhrase * p->nCol * 3;
126299   int i;
126300 
126301   for(i=0; i<p->nCol; i++){
126302     char *pCsr;
126303     pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
126304     if( pCsr ){
126305       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
126306     }else{
126307       p->aMatchinfo[iStart+i*3] = 0;
126308     }
126309   }
126310 
126311   return SQLITE_OK;
126312 }
126313 
126314 static int fts3MatchinfoCheck(
126315   Fts3Table *pTab,
126316   char cArg,
126317   char **pzErr
126318 ){
126319   if( (cArg==FTS3_MATCHINFO_NPHRASE)
126320    || (cArg==FTS3_MATCHINFO_NCOL)
126321    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
126322    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
126323    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
126324    || (cArg==FTS3_MATCHINFO_LCS)
126325    || (cArg==FTS3_MATCHINFO_HITS)
126326   ){
126327     return SQLITE_OK;
126328   }
126329   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
126330   return SQLITE_ERROR;
126331 }
126332 
126333 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
126334   int nVal;                       /* Number of integers output by cArg */
126335 
126336   switch( cArg ){
126337     case FTS3_MATCHINFO_NDOC:
126338     case FTS3_MATCHINFO_NPHRASE:
126339     case FTS3_MATCHINFO_NCOL:
126340       nVal = 1;
126341       break;
126342 
126343     case FTS3_MATCHINFO_AVGLENGTH:
126344     case FTS3_MATCHINFO_LENGTH:
126345     case FTS3_MATCHINFO_LCS:
126346       nVal = pInfo->nCol;
126347       break;
126348 
126349     default:
126350       assert( cArg==FTS3_MATCHINFO_HITS );
126351       nVal = pInfo->nCol * pInfo->nPhrase * 3;
126352       break;
126353   }
126354 
126355   return nVal;
126356 }
126357 
126358 static int fts3MatchinfoSelectDoctotal(
126359   Fts3Table *pTab,
126360   sqlite3_stmt **ppStmt,
126361   sqlite3_int64 *pnDoc,
126362   const char **paLen
126363 ){
126364   sqlite3_stmt *pStmt;
126365   const char *a;
126366   sqlite3_int64 nDoc;
126367 
126368   if( !*ppStmt ){
126369     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
126370     if( rc!=SQLITE_OK ) return rc;
126371   }
126372   pStmt = *ppStmt;
126373   assert( sqlite3_data_count(pStmt)==1 );
126374 
126375   a = sqlite3_column_blob(pStmt, 0);
126376   a += sqlite3Fts3GetVarint(a, &nDoc);
126377   if( nDoc==0 ) return SQLITE_CORRUPT_VTAB;
126378   *pnDoc = (u32)nDoc;
126379 
126380   if( paLen ) *paLen = a;
126381   return SQLITE_OK;
126382 }
126383 
126384 /*
126385 ** An instance of the following structure is used to store state while
126386 ** iterating through a multi-column position-list corresponding to the
126387 ** hits for a single phrase on a single row in order to calculate the
126388 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
126389 */
126390 typedef struct LcsIterator LcsIterator;
126391 struct LcsIterator {
126392   Fts3Expr *pExpr;                /* Pointer to phrase expression */
126393   int iPosOffset;                 /* Tokens count up to end of this phrase */
126394   char *pRead;                    /* Cursor used to iterate through aDoclist */
126395   int iPos;                       /* Current position */
126396 };
126397 
126398 /*
126399 ** If LcsIterator.iCol is set to the following value, the iterator has
126400 ** finished iterating through all offsets for all columns.
126401 */
126402 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
126403 
126404 static int fts3MatchinfoLcsCb(
126405   Fts3Expr *pExpr,                /* Phrase expression node */
126406   int iPhrase,                    /* Phrase number (numbered from zero) */
126407   void *pCtx                      /* Pointer to MatchInfo structure */
126408 ){
126409   LcsIterator *aIter = (LcsIterator *)pCtx;
126410   aIter[iPhrase].pExpr = pExpr;
126411   return SQLITE_OK;
126412 }
126413 
126414 /*
126415 ** Advance the iterator passed as an argument to the next position. Return
126416 ** 1 if the iterator is at EOF or if it now points to the start of the
126417 ** position list for the next column.
126418 */
126419 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
126420   char *pRead = pIter->pRead;
126421   sqlite3_int64 iRead;
126422   int rc = 0;
126423 
126424   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
126425   if( iRead==0 || iRead==1 ){
126426     pRead = 0;
126427     rc = 1;
126428   }else{
126429     pIter->iPos += (int)(iRead-2);
126430   }
126431 
126432   pIter->pRead = pRead;
126433   return rc;
126434 }
126435 
126436 /*
126437 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
126438 **
126439 ** If the call is successful, the longest-common-substring lengths for each
126440 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
126441 ** array before returning. SQLITE_OK is returned in this case.
126442 **
126443 ** Otherwise, if an error occurs, an SQLite error code is returned and the
126444 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
126445 ** undefined.
126446 */
126447 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
126448   LcsIterator *aIter;
126449   int i;
126450   int iCol;
126451   int nToken = 0;
126452 
126453   /* Allocate and populate the array of LcsIterator objects. The array
126454   ** contains one element for each matchable phrase in the query.
126455   **/
126456   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
126457   if( !aIter ) return SQLITE_NOMEM;
126458   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
126459   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
126460 
126461   for(i=0; i<pInfo->nPhrase; i++){
126462     LcsIterator *pIter = &aIter[i];
126463     nToken -= pIter->pExpr->pPhrase->nToken;
126464     pIter->iPosOffset = nToken;
126465   }
126466 
126467   for(iCol=0; iCol<pInfo->nCol; iCol++){
126468     int nLcs = 0;                 /* LCS value for this column */
126469     int nLive = 0;                /* Number of iterators in aIter not at EOF */
126470 
126471     for(i=0; i<pInfo->nPhrase; i++){
126472       LcsIterator *pIt = &aIter[i];
126473       pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
126474       if( pIt->pRead ){
126475         pIt->iPos = pIt->iPosOffset;
126476         fts3LcsIteratorAdvance(&aIter[i]);
126477         nLive++;
126478       }
126479     }
126480 
126481     while( nLive>0 ){
126482       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
126483       int nThisLcs = 0;           /* LCS for the current iterator positions */
126484 
126485       for(i=0; i<pInfo->nPhrase; i++){
126486         LcsIterator *pIter = &aIter[i];
126487         if( pIter->pRead==0 ){
126488           /* This iterator is already at EOF for this column. */
126489           nThisLcs = 0;
126490         }else{
126491           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
126492             pAdv = pIter;
126493           }
126494           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
126495             nThisLcs++;
126496           }else{
126497             nThisLcs = 1;
126498           }
126499           if( nThisLcs>nLcs ) nLcs = nThisLcs;
126500         }
126501       }
126502       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
126503     }
126504 
126505     pInfo->aMatchinfo[iCol] = nLcs;
126506   }
126507 
126508   sqlite3_free(aIter);
126509   return SQLITE_OK;
126510 }
126511 
126512 /*
126513 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
126514 ** be returned by the matchinfo() function. Argument zArg contains the
126515 ** format string passed as the second argument to matchinfo (or the
126516 ** default value "pcx" if no second argument was specified). The format
126517 ** string has already been validated and the pInfo->aMatchinfo[] array
126518 ** is guaranteed to be large enough for the output.
126519 **
126520 ** If bGlobal is true, then populate all fields of the matchinfo() output.
126521 ** If it is false, then assume that those fields that do not change between
126522 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
126523 ** have already been populated.
126524 **
126525 ** Return SQLITE_OK if successful, or an SQLite error code if an error
126526 ** occurs. If a value other than SQLITE_OK is returned, the state the
126527 ** pInfo->aMatchinfo[] buffer is left in is undefined.
126528 */
126529 static int fts3MatchinfoValues(
126530   Fts3Cursor *pCsr,               /* FTS3 cursor object */
126531   int bGlobal,                    /* True to grab the global stats */
126532   MatchInfo *pInfo,               /* Matchinfo context object */
126533   const char *zArg                /* Matchinfo format string */
126534 ){
126535   int rc = SQLITE_OK;
126536   int i;
126537   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126538   sqlite3_stmt *pSelect = 0;
126539 
126540   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
126541 
126542     switch( zArg[i] ){
126543       case FTS3_MATCHINFO_NPHRASE:
126544         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
126545         break;
126546 
126547       case FTS3_MATCHINFO_NCOL:
126548         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
126549         break;
126550 
126551       case FTS3_MATCHINFO_NDOC:
126552         if( bGlobal ){
126553           sqlite3_int64 nDoc = 0;
126554           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
126555           pInfo->aMatchinfo[0] = (u32)nDoc;
126556         }
126557         break;
126558 
126559       case FTS3_MATCHINFO_AVGLENGTH:
126560         if( bGlobal ){
126561           sqlite3_int64 nDoc;     /* Number of rows in table */
126562           const char *a;          /* Aggregate column length array */
126563 
126564           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
126565           if( rc==SQLITE_OK ){
126566             int iCol;
126567             for(iCol=0; iCol<pInfo->nCol; iCol++){
126568               u32 iVal;
126569               sqlite3_int64 nToken;
126570               a += sqlite3Fts3GetVarint(a, &nToken);
126571               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
126572               pInfo->aMatchinfo[iCol] = iVal;
126573             }
126574           }
126575         }
126576         break;
126577 
126578       case FTS3_MATCHINFO_LENGTH: {
126579         sqlite3_stmt *pSelectDocsize = 0;
126580         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
126581         if( rc==SQLITE_OK ){
126582           int iCol;
126583           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
126584           for(iCol=0; iCol<pInfo->nCol; iCol++){
126585             sqlite3_int64 nToken;
126586             a += sqlite3Fts3GetVarint(a, &nToken);
126587             pInfo->aMatchinfo[iCol] = (u32)nToken;
126588           }
126589         }
126590         sqlite3_reset(pSelectDocsize);
126591         break;
126592       }
126593 
126594       case FTS3_MATCHINFO_LCS:
126595         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
126596         if( rc==SQLITE_OK ){
126597           rc = fts3MatchinfoLcs(pCsr, pInfo);
126598         }
126599         break;
126600 
126601       default: {
126602         Fts3Expr *pExpr;
126603         assert( zArg[i]==FTS3_MATCHINFO_HITS );
126604         pExpr = pCsr->pExpr;
126605         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
126606         if( rc!=SQLITE_OK ) break;
126607         if( bGlobal ){
126608           if( pCsr->pDeferred ){
126609             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
126610             if( rc!=SQLITE_OK ) break;
126611           }
126612           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
126613           if( rc!=SQLITE_OK ) break;
126614         }
126615         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
126616         break;
126617       }
126618     }
126619 
126620     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
126621   }
126622 
126623   sqlite3_reset(pSelect);
126624   return rc;
126625 }
126626 
126627 
126628 /*
126629 ** Populate pCsr->aMatchinfo[] with data for the current row. The
126630 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
126631 */
126632 static int fts3GetMatchinfo(
126633   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
126634   const char *zArg                /* Second argument to matchinfo() function */
126635 ){
126636   MatchInfo sInfo;
126637   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126638   int rc = SQLITE_OK;
126639   int bGlobal = 0;                /* Collect 'global' stats as well as local */
126640 
126641   memset(&sInfo, 0, sizeof(MatchInfo));
126642   sInfo.pCursor = pCsr;
126643   sInfo.nCol = pTab->nColumn;
126644 
126645   /* If there is cached matchinfo() data, but the format string for the
126646   ** cache does not match the format string for this request, discard
126647   ** the cached data. */
126648   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
126649     assert( pCsr->aMatchinfo );
126650     sqlite3_free(pCsr->aMatchinfo);
126651     pCsr->zMatchinfo = 0;
126652     pCsr->aMatchinfo = 0;
126653   }
126654 
126655   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
126656   ** matchinfo function has been called for this query. In this case
126657   ** allocate the array used to accumulate the matchinfo data and
126658   ** initialize those elements that are constant for every row.
126659   */
126660   if( pCsr->aMatchinfo==0 ){
126661     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
126662     int nArg;                     /* Bytes in zArg */
126663     int i;                        /* Used to iterate through zArg */
126664 
126665     /* Determine the number of phrases in the query */
126666     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
126667     sInfo.nPhrase = pCsr->nPhrase;
126668 
126669     /* Determine the number of integers in the buffer returned by this call. */
126670     for(i=0; zArg[i]; i++){
126671       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
126672     }
126673 
126674     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
126675     nArg = (int)strlen(zArg);
126676     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
126677     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
126678 
126679     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
126680     pCsr->nMatchinfo = nMatchinfo;
126681     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
126682     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
126683     pCsr->isMatchinfoNeeded = 1;
126684     bGlobal = 1;
126685   }
126686 
126687   sInfo.aMatchinfo = pCsr->aMatchinfo;
126688   sInfo.nPhrase = pCsr->nPhrase;
126689   if( pCsr->isMatchinfoNeeded ){
126690     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
126691     pCsr->isMatchinfoNeeded = 0;
126692   }
126693 
126694   return rc;
126695 }
126696 
126697 /*
126698 ** Implementation of snippet() function.
126699 */
126700 SQLITE_PRIVATE void sqlite3Fts3Snippet(
126701   sqlite3_context *pCtx,          /* SQLite function call context */
126702   Fts3Cursor *pCsr,               /* Cursor object */
126703   const char *zStart,             /* Snippet start text - "<b>" */
126704   const char *zEnd,               /* Snippet end text - "</b>" */
126705   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
126706   int iCol,                       /* Extract snippet from this column */
126707   int nToken                      /* Approximate number of tokens in snippet */
126708 ){
126709   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126710   int rc = SQLITE_OK;
126711   int i;
126712   StrBuffer res = {0, 0, 0};
126713 
126714   /* The returned text includes up to four fragments of text extracted from
126715   ** the data in the current row. The first iteration of the for(...) loop
126716   ** below attempts to locate a single fragment of text nToken tokens in
126717   ** size that contains at least one instance of all phrases in the query
126718   ** expression that appear in the current row. If such a fragment of text
126719   ** cannot be found, the second iteration of the loop attempts to locate
126720   ** a pair of fragments, and so on.
126721   */
126722   int nSnippet = 0;               /* Number of fragments in this snippet */
126723   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
126724   int nFToken = -1;               /* Number of tokens in each fragment */
126725 
126726   if( !pCsr->pExpr ){
126727     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
126728     return;
126729   }
126730 
126731   for(nSnippet=1; 1; nSnippet++){
126732 
126733     int iSnip;                    /* Loop counter 0..nSnippet-1 */
126734     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
126735     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
126736 
126737     if( nToken>=0 ){
126738       nFToken = (nToken+nSnippet-1) / nSnippet;
126739     }else{
126740       nFToken = -1 * nToken;
126741     }
126742 
126743     for(iSnip=0; iSnip<nSnippet; iSnip++){
126744       int iBestScore = -1;        /* Best score of columns checked so far */
126745       int iRead;                  /* Used to iterate through columns */
126746       SnippetFragment *pFragment = &aSnippet[iSnip];
126747 
126748       memset(pFragment, 0, sizeof(*pFragment));
126749 
126750       /* Loop through all columns of the table being considered for snippets.
126751       ** If the iCol argument to this function was negative, this means all
126752       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
126753       */
126754       for(iRead=0; iRead<pTab->nColumn; iRead++){
126755         SnippetFragment sF = {0, 0, 0, 0};
126756         int iS;
126757         if( iCol>=0 && iRead!=iCol ) continue;
126758 
126759         /* Find the best snippet of nFToken tokens in column iRead. */
126760         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
126761         if( rc!=SQLITE_OK ){
126762           goto snippet_out;
126763         }
126764         if( iS>iBestScore ){
126765           *pFragment = sF;
126766           iBestScore = iS;
126767         }
126768       }
126769 
126770       mCovered |= pFragment->covered;
126771     }
126772 
126773     /* If all query phrases seen by fts3BestSnippet() are present in at least
126774     ** one of the nSnippet snippet fragments, break out of the loop.
126775     */
126776     assert( (mCovered&mSeen)==mCovered );
126777     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
126778   }
126779 
126780   assert( nFToken>0 );
126781 
126782   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
126783     rc = fts3SnippetText(pCsr, &aSnippet[i],
126784         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
126785     );
126786   }
126787 
126788  snippet_out:
126789   sqlite3Fts3SegmentsClose(pTab);
126790   if( rc!=SQLITE_OK ){
126791     sqlite3_result_error_code(pCtx, rc);
126792     sqlite3_free(res.z);
126793   }else{
126794     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
126795   }
126796 }
126797 
126798 
126799 typedef struct TermOffset TermOffset;
126800 typedef struct TermOffsetCtx TermOffsetCtx;
126801 
126802 struct TermOffset {
126803   char *pList;                    /* Position-list */
126804   int iPos;                       /* Position just read from pList */
126805   int iOff;                       /* Offset of this term from read positions */
126806 };
126807 
126808 struct TermOffsetCtx {
126809   Fts3Cursor *pCsr;
126810   int iCol;                       /* Column of table to populate aTerm for */
126811   int iTerm;
126812   sqlite3_int64 iDocid;
126813   TermOffset *aTerm;
126814 };
126815 
126816 /*
126817 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
126818 */
126819 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
126820   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
126821   int nTerm;                      /* Number of tokens in phrase */
126822   int iTerm;                      /* For looping through nTerm phrase terms */
126823   char *pList;                    /* Pointer to position list for phrase */
126824   int iPos = 0;                   /* First position in position-list */
126825 
126826   UNUSED_PARAMETER(iPhrase);
126827   pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
126828   nTerm = pExpr->pPhrase->nToken;
126829   if( pList ){
126830     fts3GetDeltaPosition(&pList, &iPos);
126831     assert( iPos>=0 );
126832   }
126833 
126834   for(iTerm=0; iTerm<nTerm; iTerm++){
126835     TermOffset *pT = &p->aTerm[p->iTerm++];
126836     pT->iOff = nTerm-iTerm-1;
126837     pT->pList = pList;
126838     pT->iPos = iPos;
126839   }
126840 
126841   return SQLITE_OK;
126842 }
126843 
126844 /*
126845 ** Implementation of offsets() function.
126846 */
126847 SQLITE_PRIVATE void sqlite3Fts3Offsets(
126848   sqlite3_context *pCtx,          /* SQLite function call context */
126849   Fts3Cursor *pCsr                /* Cursor object */
126850 ){
126851   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126852   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
126853   const char *ZDUMMY;             /* Dummy argument used with xNext() */
126854   int NDUMMY;                     /* Dummy argument used with xNext() */
126855   int rc;                         /* Return Code */
126856   int nToken;                     /* Number of tokens in query */
126857   int iCol;                       /* Column currently being processed */
126858   StrBuffer res = {0, 0, 0};      /* Result string */
126859   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
126860 
126861   if( !pCsr->pExpr ){
126862     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
126863     return;
126864   }
126865 
126866   memset(&sCtx, 0, sizeof(sCtx));
126867   assert( pCsr->isRequireSeek==0 );
126868 
126869   /* Count the number of terms in the query */
126870   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
126871   if( rc!=SQLITE_OK ) goto offsets_out;
126872 
126873   /* Allocate the array of TermOffset iterators. */
126874   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
126875   if( 0==sCtx.aTerm ){
126876     rc = SQLITE_NOMEM;
126877     goto offsets_out;
126878   }
126879   sCtx.iDocid = pCsr->iPrevId;
126880   sCtx.pCsr = pCsr;
126881 
126882   /* Loop through the table columns, appending offset information to
126883   ** string-buffer res for each column.
126884   */
126885   for(iCol=0; iCol<pTab->nColumn; iCol++){
126886     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
126887     int iStart;
126888     int iEnd;
126889     int iCurrent;
126890     const char *zDoc;
126891     int nDoc;
126892 
126893     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
126894     ** no way that this operation can fail, so the return code from
126895     ** fts3ExprIterate() can be discarded.
126896     */
126897     sCtx.iCol = iCol;
126898     sCtx.iTerm = 0;
126899     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
126900 
126901     /* Retreive the text stored in column iCol. If an SQL NULL is stored
126902     ** in column iCol, jump immediately to the next iteration of the loop.
126903     ** If an OOM occurs while retrieving the data (this can happen if SQLite
126904     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
126905     ** to the caller.
126906     */
126907     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
126908     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
126909     if( zDoc==0 ){
126910       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
126911         continue;
126912       }
126913       rc = SQLITE_NOMEM;
126914       goto offsets_out;
126915     }
126916 
126917     /* Initialize a tokenizer iterator to iterate through column iCol. */
126918     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
126919     if( rc!=SQLITE_OK ) goto offsets_out;
126920     pC->pTokenizer = pTab->pTokenizer;
126921 
126922     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
126923     while( rc==SQLITE_OK ){
126924       int i;                      /* Used to loop through terms */
126925       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
126926       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
126927 
126928       for(i=0; i<nToken; i++){
126929         TermOffset *pT = &sCtx.aTerm[i];
126930         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
126931           iMinPos = pT->iPos-pT->iOff;
126932           pTerm = pT;
126933         }
126934       }
126935 
126936       if( !pTerm ){
126937         /* All offsets for this column have been gathered. */
126938         break;
126939       }else{
126940         assert( iCurrent<=iMinPos );
126941         if( 0==(0xFE&*pTerm->pList) ){
126942           pTerm->pList = 0;
126943         }else{
126944           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
126945         }
126946         while( rc==SQLITE_OK && iCurrent<iMinPos ){
126947           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
126948         }
126949         if( rc==SQLITE_OK ){
126950           char aBuffer[64];
126951           sqlite3_snprintf(sizeof(aBuffer), aBuffer,
126952               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
126953           );
126954           rc = fts3StringAppend(&res, aBuffer, -1);
126955         }else if( rc==SQLITE_DONE ){
126956           rc = SQLITE_CORRUPT_VTAB;
126957         }
126958       }
126959     }
126960     if( rc==SQLITE_DONE ){
126961       rc = SQLITE_OK;
126962     }
126963 
126964     pMod->xClose(pC);
126965     if( rc!=SQLITE_OK ) goto offsets_out;
126966   }
126967 
126968  offsets_out:
126969   sqlite3_free(sCtx.aTerm);
126970   assert( rc!=SQLITE_DONE );
126971   sqlite3Fts3SegmentsClose(pTab);
126972   if( rc!=SQLITE_OK ){
126973     sqlite3_result_error_code(pCtx,  rc);
126974     sqlite3_free(res.z);
126975   }else{
126976     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
126977   }
126978   return;
126979 }
126980 
126981 /*
126982 ** Implementation of matchinfo() function.
126983 */
126984 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
126985   sqlite3_context *pContext,      /* Function call context */
126986   Fts3Cursor *pCsr,               /* FTS3 table cursor */
126987   const char *zArg                /* Second arg to matchinfo() function */
126988 ){
126989   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
126990   int rc;
126991   int i;
126992   const char *zFormat;
126993 
126994   if( zArg ){
126995     for(i=0; zArg[i]; i++){
126996       char *zErr = 0;
126997       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
126998         sqlite3_result_error(pContext, zErr, -1);
126999         sqlite3_free(zErr);
127000         return;
127001       }
127002     }
127003     zFormat = zArg;
127004   }else{
127005     zFormat = FTS3_MATCHINFO_DEFAULT;
127006   }
127007 
127008   if( !pCsr->pExpr ){
127009     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
127010     return;
127011   }
127012 
127013   /* Retrieve matchinfo() data. */
127014   rc = fts3GetMatchinfo(pCsr, zFormat);
127015   sqlite3Fts3SegmentsClose(pTab);
127016 
127017   if( rc!=SQLITE_OK ){
127018     sqlite3_result_error_code(pContext, rc);
127019   }else{
127020     int n = pCsr->nMatchinfo * sizeof(u32);
127021     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
127022   }
127023 }
127024 
127025 #endif
127026 
127027 /************** End of fts3_snippet.c ****************************************/
127028 /************** Begin file rtree.c *******************************************/
127029 /*
127030 ** 2001 September 15
127031 **
127032 ** The author disclaims copyright to this source code.  In place of
127033 ** a legal notice, here is a blessing:
127034 **
127035 **    May you do good and not evil.
127036 **    May you find forgiveness for yourself and forgive others.
127037 **    May you share freely, never taking more than you give.
127038 **
127039 *************************************************************************
127040 ** This file contains code for implementations of the r-tree and r*-tree
127041 ** algorithms packaged as an SQLite virtual table module.
127042 */
127043 
127044 /*
127045 ** Database Format of R-Tree Tables
127046 ** --------------------------------
127047 **
127048 ** The data structure for a single virtual r-tree table is stored in three
127049 ** native SQLite tables declared as follows. In each case, the '%' character
127050 ** in the table name is replaced with the user-supplied name of the r-tree
127051 ** table.
127052 **
127053 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
127054 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
127055 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
127056 **
127057 ** The data for each node of the r-tree structure is stored in the %_node
127058 ** table. For each node that is not the root node of the r-tree, there is
127059 ** an entry in the %_parent table associating the node with its parent.
127060 ** And for each row of data in the table, there is an entry in the %_rowid
127061 ** table that maps from the entries rowid to the id of the node that it
127062 ** is stored on.
127063 **
127064 ** The root node of an r-tree always exists, even if the r-tree table is
127065 ** empty. The nodeno of the root node is always 1. All other nodes in the
127066 ** table must be the same size as the root node. The content of each node
127067 ** is formatted as follows:
127068 **
127069 **   1. If the node is the root node (node 1), then the first 2 bytes
127070 **      of the node contain the tree depth as a big-endian integer.
127071 **      For non-root nodes, the first 2 bytes are left unused.
127072 **
127073 **   2. The next 2 bytes contain the number of entries currently
127074 **      stored in the node.
127075 **
127076 **   3. The remainder of the node contains the node entries. Each entry
127077 **      consists of a single 8-byte integer followed by an even number
127078 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
127079 **      of a record. For internal nodes it is the node number of a
127080 **      child page.
127081 */
127082 
127083 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
127084 
127085 /*
127086 ** This file contains an implementation of a couple of different variants
127087 ** of the r-tree algorithm. See the README file for further details. The
127088 ** same data-structure is used for all, but the algorithms for insert and
127089 ** delete operations vary. The variants used are selected at compile time
127090 ** by defining the following symbols:
127091 */
127092 
127093 /* Either, both or none of the following may be set to activate
127094 ** r*tree variant algorithms.
127095 */
127096 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
127097 #define VARIANT_RSTARTREE_REINSERT      1
127098 
127099 /*
127100 ** Exactly one of the following must be set to 1.
127101 */
127102 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
127103 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
127104 #define VARIANT_RSTARTREE_SPLIT         1
127105 
127106 #define VARIANT_GUTTMAN_SPLIT \
127107         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
127108 
127109 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
127110   #define PickNext QuadraticPickNext
127111   #define PickSeeds QuadraticPickSeeds
127112   #define AssignCells splitNodeGuttman
127113 #endif
127114 #if VARIANT_GUTTMAN_LINEAR_SPLIT
127115   #define PickNext LinearPickNext
127116   #define PickSeeds LinearPickSeeds
127117   #define AssignCells splitNodeGuttman
127118 #endif
127119 #if VARIANT_RSTARTREE_SPLIT
127120   #define AssignCells splitNodeStartree
127121 #endif
127122 
127123 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
127124 # define NDEBUG 1
127125 #endif
127126 
127127 #ifndef SQLITE_CORE
127128   SQLITE_EXTENSION_INIT1
127129 #else
127130 #endif
127131 
127132 /* #include <string.h> */
127133 /* #include <assert.h> */
127134 
127135 #ifndef SQLITE_AMALGAMATION
127136 #include "sqlite3rtree.h"
127137 typedef sqlite3_int64 i64;
127138 typedef unsigned char u8;
127139 typedef unsigned int u32;
127140 #endif
127141 
127142 /*  The following macro is used to suppress compiler warnings.
127143 */
127144 #ifndef UNUSED_PARAMETER
127145 # define UNUSED_PARAMETER(x) (void)(x)
127146 #endif
127147 
127148 typedef struct Rtree Rtree;
127149 typedef struct RtreeCursor RtreeCursor;
127150 typedef struct RtreeNode RtreeNode;
127151 typedef struct RtreeCell RtreeCell;
127152 typedef struct RtreeConstraint RtreeConstraint;
127153 typedef struct RtreeMatchArg RtreeMatchArg;
127154 typedef struct RtreeGeomCallback RtreeGeomCallback;
127155 typedef union RtreeCoord RtreeCoord;
127156 
127157 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
127158 #define RTREE_MAX_DIMENSIONS 5
127159 
127160 /* Size of hash table Rtree.aHash. This hash table is not expected to
127161 ** ever contain very many entries, so a fixed number of buckets is
127162 ** used.
127163 */
127164 #define HASHSIZE 128
127165 
127166 /*
127167 ** An rtree virtual-table object.
127168 */
127169 struct Rtree {
127170   sqlite3_vtab base;
127171   sqlite3 *db;                /* Host database connection */
127172   int iNodeSize;              /* Size in bytes of each node in the node table */
127173   int nDim;                   /* Number of dimensions */
127174   int nBytesPerCell;          /* Bytes consumed per cell */
127175   int iDepth;                 /* Current depth of the r-tree structure */
127176   char *zDb;                  /* Name of database containing r-tree table */
127177   char *zName;                /* Name of r-tree table */
127178   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
127179   int nBusy;                  /* Current number of users of this structure */
127180 
127181   /* List of nodes removed during a CondenseTree operation. List is
127182   ** linked together via the pointer normally used for hash chains -
127183   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
127184   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
127185   */
127186   RtreeNode *pDeleted;
127187   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
127188 
127189   /* Statements to read/write/delete a record from xxx_node */
127190   sqlite3_stmt *pReadNode;
127191   sqlite3_stmt *pWriteNode;
127192   sqlite3_stmt *pDeleteNode;
127193 
127194   /* Statements to read/write/delete a record from xxx_rowid */
127195   sqlite3_stmt *pReadRowid;
127196   sqlite3_stmt *pWriteRowid;
127197   sqlite3_stmt *pDeleteRowid;
127198 
127199   /* Statements to read/write/delete a record from xxx_parent */
127200   sqlite3_stmt *pReadParent;
127201   sqlite3_stmt *pWriteParent;
127202   sqlite3_stmt *pDeleteParent;
127203 
127204   int eCoordType;
127205 };
127206 
127207 /* Possible values for eCoordType: */
127208 #define RTREE_COORD_REAL32 0
127209 #define RTREE_COORD_INT32  1
127210 
127211 /*
127212 ** The minimum number of cells allowed for a node is a third of the
127213 ** maximum. In Gutman's notation:
127214 **
127215 **     m = M/3
127216 **
127217 ** If an R*-tree "Reinsert" operation is required, the same number of
127218 ** cells are removed from the overfull node and reinserted into the tree.
127219 */
127220 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
127221 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
127222 #define RTREE_MAXCELLS 51
127223 
127224 /*
127225 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
127226 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
127227 ** Therefore all non-root nodes must contain at least 3 entries. Since
127228 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
127229 ** 40 or less.
127230 */
127231 #define RTREE_MAX_DEPTH 40
127232 
127233 /*
127234 ** An rtree cursor object.
127235 */
127236 struct RtreeCursor {
127237   sqlite3_vtab_cursor base;
127238   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
127239   int iCell;                        /* Index of current cell in pNode */
127240   int iStrategy;                    /* Copy of idxNum search parameter */
127241   int nConstraint;                  /* Number of entries in aConstraint */
127242   RtreeConstraint *aConstraint;     /* Search constraints. */
127243 };
127244 
127245 union RtreeCoord {
127246   float f;
127247   int i;
127248 };
127249 
127250 /*
127251 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
127252 ** formatted as a double. This macro assumes that local variable pRtree points
127253 ** to the Rtree structure associated with the RtreeCoord.
127254 */
127255 #define DCOORD(coord) (                           \
127256   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
127257     ((double)coord.f) :                           \
127258     ((double)coord.i)                             \
127259 )
127260 
127261 /*
127262 ** A search constraint.
127263 */
127264 struct RtreeConstraint {
127265   int iCoord;                     /* Index of constrained coordinate */
127266   int op;                         /* Constraining operation */
127267   double rValue;                  /* Constraint value. */
127268   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
127269   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
127270 };
127271 
127272 /* Possible values for RtreeConstraint.op */
127273 #define RTREE_EQ    0x41
127274 #define RTREE_LE    0x42
127275 #define RTREE_LT    0x43
127276 #define RTREE_GE    0x44
127277 #define RTREE_GT    0x45
127278 #define RTREE_MATCH 0x46
127279 
127280 /*
127281 ** An rtree structure node.
127282 */
127283 struct RtreeNode {
127284   RtreeNode *pParent;               /* Parent node */
127285   i64 iNode;
127286   int nRef;
127287   int isDirty;
127288   u8 *zData;
127289   RtreeNode *pNext;                 /* Next node in this hash chain */
127290 };
127291 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
127292 
127293 /*
127294 ** Structure to store a deserialized rtree record.
127295 */
127296 struct RtreeCell {
127297   i64 iRowid;
127298   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
127299 };
127300 
127301 
127302 /*
127303 ** Value for the first field of every RtreeMatchArg object. The MATCH
127304 ** operator tests that the first field of a blob operand matches this
127305 ** value to avoid operating on invalid blobs (which could cause a segfault).
127306 */
127307 #define RTREE_GEOMETRY_MAGIC 0x891245AB
127308 
127309 /*
127310 ** An instance of this structure must be supplied as a blob argument to
127311 ** the right-hand-side of an SQL MATCH operator used to constrain an
127312 ** r-tree query.
127313 */
127314 struct RtreeMatchArg {
127315   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
127316   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
127317   void *pContext;
127318   int nParam;
127319   double aParam[1];
127320 };
127321 
127322 /*
127323 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
127324 ** a single instance of the following structure is allocated. It is used
127325 ** as the context for the user-function created by by s_r_g_c(). The object
127326 ** is eventually deleted by the destructor mechanism provided by
127327 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
127328 ** the geometry callback function).
127329 */
127330 struct RtreeGeomCallback {
127331   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
127332   void *pContext;
127333 };
127334 
127335 #ifndef MAX
127336 # define MAX(x,y) ((x) < (y) ? (y) : (x))
127337 #endif
127338 #ifndef MIN
127339 # define MIN(x,y) ((x) > (y) ? (y) : (x))
127340 #endif
127341 
127342 /*
127343 ** Functions to deserialize a 16 bit integer, 32 bit real number and
127344 ** 64 bit integer. The deserialized value is returned.
127345 */
127346 static int readInt16(u8 *p){
127347   return (p[0]<<8) + p[1];
127348 }
127349 static void readCoord(u8 *p, RtreeCoord *pCoord){
127350   u32 i = (
127351     (((u32)p[0]) << 24) +
127352     (((u32)p[1]) << 16) +
127353     (((u32)p[2]) <<  8) +
127354     (((u32)p[3]) <<  0)
127355   );
127356   *(u32 *)pCoord = i;
127357 }
127358 static i64 readInt64(u8 *p){
127359   return (
127360     (((i64)p[0]) << 56) +
127361     (((i64)p[1]) << 48) +
127362     (((i64)p[2]) << 40) +
127363     (((i64)p[3]) << 32) +
127364     (((i64)p[4]) << 24) +
127365     (((i64)p[5]) << 16) +
127366     (((i64)p[6]) <<  8) +
127367     (((i64)p[7]) <<  0)
127368   );
127369 }
127370 
127371 /*
127372 ** Functions to serialize a 16 bit integer, 32 bit real number and
127373 ** 64 bit integer. The value returned is the number of bytes written
127374 ** to the argument buffer (always 2, 4 and 8 respectively).
127375 */
127376 static int writeInt16(u8 *p, int i){
127377   p[0] = (i>> 8)&0xFF;
127378   p[1] = (i>> 0)&0xFF;
127379   return 2;
127380 }
127381 static int writeCoord(u8 *p, RtreeCoord *pCoord){
127382   u32 i;
127383   assert( sizeof(RtreeCoord)==4 );
127384   assert( sizeof(u32)==4 );
127385   i = *(u32 *)pCoord;
127386   p[0] = (i>>24)&0xFF;
127387   p[1] = (i>>16)&0xFF;
127388   p[2] = (i>> 8)&0xFF;
127389   p[3] = (i>> 0)&0xFF;
127390   return 4;
127391 }
127392 static int writeInt64(u8 *p, i64 i){
127393   p[0] = (i>>56)&0xFF;
127394   p[1] = (i>>48)&0xFF;
127395   p[2] = (i>>40)&0xFF;
127396   p[3] = (i>>32)&0xFF;
127397   p[4] = (i>>24)&0xFF;
127398   p[5] = (i>>16)&0xFF;
127399   p[6] = (i>> 8)&0xFF;
127400   p[7] = (i>> 0)&0xFF;
127401   return 8;
127402 }
127403 
127404 /*
127405 ** Increment the reference count of node p.
127406 */
127407 static void nodeReference(RtreeNode *p){
127408   if( p ){
127409     p->nRef++;
127410   }
127411 }
127412 
127413 /*
127414 ** Clear the content of node p (set all bytes to 0x00).
127415 */
127416 static void nodeZero(Rtree *pRtree, RtreeNode *p){
127417   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
127418   p->isDirty = 1;
127419 }
127420 
127421 /*
127422 ** Given a node number iNode, return the corresponding key to use
127423 ** in the Rtree.aHash table.
127424 */
127425 static int nodeHash(i64 iNode){
127426   return (
127427     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
127428     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
127429   ) % HASHSIZE;
127430 }
127431 
127432 /*
127433 ** Search the node hash table for node iNode. If found, return a pointer
127434 ** to it. Otherwise, return 0.
127435 */
127436 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
127437   RtreeNode *p;
127438   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
127439   return p;
127440 }
127441 
127442 /*
127443 ** Add node pNode to the node hash table.
127444 */
127445 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
127446   int iHash;
127447   assert( pNode->pNext==0 );
127448   iHash = nodeHash(pNode->iNode);
127449   pNode->pNext = pRtree->aHash[iHash];
127450   pRtree->aHash[iHash] = pNode;
127451 }
127452 
127453 /*
127454 ** Remove node pNode from the node hash table.
127455 */
127456 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
127457   RtreeNode **pp;
127458   if( pNode->iNode!=0 ){
127459     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
127460     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
127461     *pp = pNode->pNext;
127462     pNode->pNext = 0;
127463   }
127464 }
127465 
127466 /*
127467 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
127468 ** indicating that node has not yet been assigned a node number. It is
127469 ** assigned a node number when nodeWrite() is called to write the
127470 ** node contents out to the database.
127471 */
127472 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
127473   RtreeNode *pNode;
127474   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
127475   if( pNode ){
127476     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
127477     pNode->zData = (u8 *)&pNode[1];
127478     pNode->nRef = 1;
127479     pNode->pParent = pParent;
127480     pNode->isDirty = 1;
127481     nodeReference(pParent);
127482   }
127483   return pNode;
127484 }
127485 
127486 /*
127487 ** Obtain a reference to an r-tree node.
127488 */
127489 static int
127490 nodeAcquire(
127491   Rtree *pRtree,             /* R-tree structure */
127492   i64 iNode,                 /* Node number to load */
127493   RtreeNode *pParent,        /* Either the parent node or NULL */
127494   RtreeNode **ppNode         /* OUT: Acquired node */
127495 ){
127496   int rc;
127497   int rc2 = SQLITE_OK;
127498   RtreeNode *pNode;
127499 
127500   /* Check if the requested node is already in the hash table. If so,
127501   ** increase its reference count and return it.
127502   */
127503   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
127504     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
127505     if( pParent && !pNode->pParent ){
127506       nodeReference(pParent);
127507       pNode->pParent = pParent;
127508     }
127509     pNode->nRef++;
127510     *ppNode = pNode;
127511     return SQLITE_OK;
127512   }
127513 
127514   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
127515   rc = sqlite3_step(pRtree->pReadNode);
127516   if( rc==SQLITE_ROW ){
127517     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
127518     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
127519       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
127520       if( !pNode ){
127521         rc2 = SQLITE_NOMEM;
127522       }else{
127523         pNode->pParent = pParent;
127524         pNode->zData = (u8 *)&pNode[1];
127525         pNode->nRef = 1;
127526         pNode->iNode = iNode;
127527         pNode->isDirty = 0;
127528         pNode->pNext = 0;
127529         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
127530         nodeReference(pParent);
127531       }
127532     }
127533   }
127534   rc = sqlite3_reset(pRtree->pReadNode);
127535   if( rc==SQLITE_OK ) rc = rc2;
127536 
127537   /* If the root node was just loaded, set pRtree->iDepth to the height
127538   ** of the r-tree structure. A height of zero means all data is stored on
127539   ** the root node. A height of one means the children of the root node
127540   ** are the leaves, and so on. If the depth as specified on the root node
127541   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
127542   */
127543   if( pNode && iNode==1 ){
127544     pRtree->iDepth = readInt16(pNode->zData);
127545     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
127546       rc = SQLITE_CORRUPT_VTAB;
127547     }
127548   }
127549 
127550   /* If no error has occurred so far, check if the "number of entries"
127551   ** field on the node is too large. If so, set the return code to
127552   ** SQLITE_CORRUPT_VTAB.
127553   */
127554   if( pNode && rc==SQLITE_OK ){
127555     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
127556       rc = SQLITE_CORRUPT_VTAB;
127557     }
127558   }
127559 
127560   if( rc==SQLITE_OK ){
127561     if( pNode!=0 ){
127562       nodeHashInsert(pRtree, pNode);
127563     }else{
127564       rc = SQLITE_CORRUPT_VTAB;
127565     }
127566     *ppNode = pNode;
127567   }else{
127568     sqlite3_free(pNode);
127569     *ppNode = 0;
127570   }
127571 
127572   return rc;
127573 }
127574 
127575 /*
127576 ** Overwrite cell iCell of node pNode with the contents of pCell.
127577 */
127578 static void nodeOverwriteCell(
127579   Rtree *pRtree,
127580   RtreeNode *pNode,
127581   RtreeCell *pCell,
127582   int iCell
127583 ){
127584   int ii;
127585   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
127586   p += writeInt64(p, pCell->iRowid);
127587   for(ii=0; ii<(pRtree->nDim*2); ii++){
127588     p += writeCoord(p, &pCell->aCoord[ii]);
127589   }
127590   pNode->isDirty = 1;
127591 }
127592 
127593 /*
127594 ** Remove cell the cell with index iCell from node pNode.
127595 */
127596 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
127597   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
127598   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
127599   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
127600   memmove(pDst, pSrc, nByte);
127601   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
127602   pNode->isDirty = 1;
127603 }
127604 
127605 /*
127606 ** Insert the contents of cell pCell into node pNode. If the insert
127607 ** is successful, return SQLITE_OK.
127608 **
127609 ** If there is not enough free space in pNode, return SQLITE_FULL.
127610 */
127611 static int
127612 nodeInsertCell(
127613   Rtree *pRtree,
127614   RtreeNode *pNode,
127615   RtreeCell *pCell
127616 ){
127617   int nCell;                    /* Current number of cells in pNode */
127618   int nMaxCell;                 /* Maximum number of cells for pNode */
127619 
127620   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
127621   nCell = NCELL(pNode);
127622 
127623   assert( nCell<=nMaxCell );
127624   if( nCell<nMaxCell ){
127625     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
127626     writeInt16(&pNode->zData[2], nCell+1);
127627     pNode->isDirty = 1;
127628   }
127629 
127630   return (nCell==nMaxCell);
127631 }
127632 
127633 /*
127634 ** If the node is dirty, write it out to the database.
127635 */
127636 static int
127637 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
127638   int rc = SQLITE_OK;
127639   if( pNode->isDirty ){
127640     sqlite3_stmt *p = pRtree->pWriteNode;
127641     if( pNode->iNode ){
127642       sqlite3_bind_int64(p, 1, pNode->iNode);
127643     }else{
127644       sqlite3_bind_null(p, 1);
127645     }
127646     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
127647     sqlite3_step(p);
127648     pNode->isDirty = 0;
127649     rc = sqlite3_reset(p);
127650     if( pNode->iNode==0 && rc==SQLITE_OK ){
127651       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
127652       nodeHashInsert(pRtree, pNode);
127653     }
127654   }
127655   return rc;
127656 }
127657 
127658 /*
127659 ** Release a reference to a node. If the node is dirty and the reference
127660 ** count drops to zero, the node data is written to the database.
127661 */
127662 static int
127663 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
127664   int rc = SQLITE_OK;
127665   if( pNode ){
127666     assert( pNode->nRef>0 );
127667     pNode->nRef--;
127668     if( pNode->nRef==0 ){
127669       if( pNode->iNode==1 ){
127670         pRtree->iDepth = -1;
127671       }
127672       if( pNode->pParent ){
127673         rc = nodeRelease(pRtree, pNode->pParent);
127674       }
127675       if( rc==SQLITE_OK ){
127676         rc = nodeWrite(pRtree, pNode);
127677       }
127678       nodeHashDelete(pRtree, pNode);
127679       sqlite3_free(pNode);
127680     }
127681   }
127682   return rc;
127683 }
127684 
127685 /*
127686 ** Return the 64-bit integer value associated with cell iCell of
127687 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
127688 ** an internal node, then the 64-bit integer is a child page number.
127689 */
127690 static i64 nodeGetRowid(
127691   Rtree *pRtree,
127692   RtreeNode *pNode,
127693   int iCell
127694 ){
127695   assert( iCell<NCELL(pNode) );
127696   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
127697 }
127698 
127699 /*
127700 ** Return coordinate iCoord from cell iCell in node pNode.
127701 */
127702 static void nodeGetCoord(
127703   Rtree *pRtree,
127704   RtreeNode *pNode,
127705   int iCell,
127706   int iCoord,
127707   RtreeCoord *pCoord           /* Space to write result to */
127708 ){
127709   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
127710 }
127711 
127712 /*
127713 ** Deserialize cell iCell of node pNode. Populate the structure pointed
127714 ** to by pCell with the results.
127715 */
127716 static void nodeGetCell(
127717   Rtree *pRtree,
127718   RtreeNode *pNode,
127719   int iCell,
127720   RtreeCell *pCell
127721 ){
127722   int ii;
127723   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
127724   for(ii=0; ii<pRtree->nDim*2; ii++){
127725     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
127726   }
127727 }
127728 
127729 
127730 /* Forward declaration for the function that does the work of
127731 ** the virtual table module xCreate() and xConnect() methods.
127732 */
127733 static int rtreeInit(
127734   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
127735 );
127736 
127737 /*
127738 ** Rtree virtual table module xCreate method.
127739 */
127740 static int rtreeCreate(
127741   sqlite3 *db,
127742   void *pAux,
127743   int argc, const char *const*argv,
127744   sqlite3_vtab **ppVtab,
127745   char **pzErr
127746 ){
127747   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
127748 }
127749 
127750 /*
127751 ** Rtree virtual table module xConnect method.
127752 */
127753 static int rtreeConnect(
127754   sqlite3 *db,
127755   void *pAux,
127756   int argc, const char *const*argv,
127757   sqlite3_vtab **ppVtab,
127758   char **pzErr
127759 ){
127760   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
127761 }
127762 
127763 /*
127764 ** Increment the r-tree reference count.
127765 */
127766 static void rtreeReference(Rtree *pRtree){
127767   pRtree->nBusy++;
127768 }
127769 
127770 /*
127771 ** Decrement the r-tree reference count. When the reference count reaches
127772 ** zero the structure is deleted.
127773 */
127774 static void rtreeRelease(Rtree *pRtree){
127775   pRtree->nBusy--;
127776   if( pRtree->nBusy==0 ){
127777     sqlite3_finalize(pRtree->pReadNode);
127778     sqlite3_finalize(pRtree->pWriteNode);
127779     sqlite3_finalize(pRtree->pDeleteNode);
127780     sqlite3_finalize(pRtree->pReadRowid);
127781     sqlite3_finalize(pRtree->pWriteRowid);
127782     sqlite3_finalize(pRtree->pDeleteRowid);
127783     sqlite3_finalize(pRtree->pReadParent);
127784     sqlite3_finalize(pRtree->pWriteParent);
127785     sqlite3_finalize(pRtree->pDeleteParent);
127786     sqlite3_free(pRtree);
127787   }
127788 }
127789 
127790 /*
127791 ** Rtree virtual table module xDisconnect method.
127792 */
127793 static int rtreeDisconnect(sqlite3_vtab *pVtab){
127794   rtreeRelease((Rtree *)pVtab);
127795   return SQLITE_OK;
127796 }
127797 
127798 /*
127799 ** Rtree virtual table module xDestroy method.
127800 */
127801 static int rtreeDestroy(sqlite3_vtab *pVtab){
127802   Rtree *pRtree = (Rtree *)pVtab;
127803   int rc;
127804   char *zCreate = sqlite3_mprintf(
127805     "DROP TABLE '%q'.'%q_node';"
127806     "DROP TABLE '%q'.'%q_rowid';"
127807     "DROP TABLE '%q'.'%q_parent';",
127808     pRtree->zDb, pRtree->zName,
127809     pRtree->zDb, pRtree->zName,
127810     pRtree->zDb, pRtree->zName
127811   );
127812   if( !zCreate ){
127813     rc = SQLITE_NOMEM;
127814   }else{
127815     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
127816     sqlite3_free(zCreate);
127817   }
127818   if( rc==SQLITE_OK ){
127819     rtreeRelease(pRtree);
127820   }
127821 
127822   return rc;
127823 }
127824 
127825 /*
127826 ** Rtree virtual table module xOpen method.
127827 */
127828 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
127829   int rc = SQLITE_NOMEM;
127830   RtreeCursor *pCsr;
127831 
127832   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
127833   if( pCsr ){
127834     memset(pCsr, 0, sizeof(RtreeCursor));
127835     pCsr->base.pVtab = pVTab;
127836     rc = SQLITE_OK;
127837   }
127838   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
127839 
127840   return rc;
127841 }
127842 
127843 
127844 /*
127845 ** Free the RtreeCursor.aConstraint[] array and its contents.
127846 */
127847 static void freeCursorConstraints(RtreeCursor *pCsr){
127848   if( pCsr->aConstraint ){
127849     int i;                        /* Used to iterate through constraint array */
127850     for(i=0; i<pCsr->nConstraint; i++){
127851       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
127852       if( pGeom ){
127853         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
127854         sqlite3_free(pGeom);
127855       }
127856     }
127857     sqlite3_free(pCsr->aConstraint);
127858     pCsr->aConstraint = 0;
127859   }
127860 }
127861 
127862 /*
127863 ** Rtree virtual table module xClose method.
127864 */
127865 static int rtreeClose(sqlite3_vtab_cursor *cur){
127866   Rtree *pRtree = (Rtree *)(cur->pVtab);
127867   int rc;
127868   RtreeCursor *pCsr = (RtreeCursor *)cur;
127869   freeCursorConstraints(pCsr);
127870   rc = nodeRelease(pRtree, pCsr->pNode);
127871   sqlite3_free(pCsr);
127872   return rc;
127873 }
127874 
127875 /*
127876 ** Rtree virtual table module xEof method.
127877 **
127878 ** Return non-zero if the cursor does not currently point to a valid
127879 ** record (i.e if the scan has finished), or zero otherwise.
127880 */
127881 static int rtreeEof(sqlite3_vtab_cursor *cur){
127882   RtreeCursor *pCsr = (RtreeCursor *)cur;
127883   return (pCsr->pNode==0);
127884 }
127885 
127886 /*
127887 ** The r-tree constraint passed as the second argument to this function is
127888 ** guaranteed to be a MATCH constraint.
127889 */
127890 static int testRtreeGeom(
127891   Rtree *pRtree,                  /* R-Tree object */
127892   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
127893   RtreeCell *pCell,               /* Cell to test */
127894   int *pbRes                      /* OUT: Test result */
127895 ){
127896   int i;
127897   double aCoord[RTREE_MAX_DIMENSIONS*2];
127898   int nCoord = pRtree->nDim*2;
127899 
127900   assert( pConstraint->op==RTREE_MATCH );
127901   assert( pConstraint->pGeom );
127902 
127903   for(i=0; i<nCoord; i++){
127904     aCoord[i] = DCOORD(pCell->aCoord[i]);
127905   }
127906   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
127907 }
127908 
127909 /*
127910 ** Cursor pCursor currently points to a cell in a non-leaf page.
127911 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
127912 ** (excluded) by the constraints in the pCursor->aConstraint[]
127913 ** array, or false otherwise.
127914 **
127915 ** Return SQLITE_OK if successful or an SQLite error code if an error
127916 ** occurs within a geometry callback.
127917 */
127918 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
127919   RtreeCell cell;
127920   int ii;
127921   int bRes = 0;
127922   int rc = SQLITE_OK;
127923 
127924   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
127925   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
127926     RtreeConstraint *p = &pCursor->aConstraint[ii];
127927     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
127928     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
127929 
127930     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
127931         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
127932     );
127933 
127934     switch( p->op ){
127935       case RTREE_LE: case RTREE_LT:
127936         bRes = p->rValue<cell_min;
127937         break;
127938 
127939       case RTREE_GE: case RTREE_GT:
127940         bRes = p->rValue>cell_max;
127941         break;
127942 
127943       case RTREE_EQ:
127944         bRes = (p->rValue>cell_max || p->rValue<cell_min);
127945         break;
127946 
127947       default: {
127948         assert( p->op==RTREE_MATCH );
127949         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
127950         bRes = !bRes;
127951         break;
127952       }
127953     }
127954   }
127955 
127956   *pbEof = bRes;
127957   return rc;
127958 }
127959 
127960 /*
127961 ** Test if the cell that cursor pCursor currently points to
127962 ** would be filtered (excluded) by the constraints in the
127963 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
127964 ** returning. If the cell is not filtered (excluded) by the constraints,
127965 ** set pbEof to zero.
127966 **
127967 ** Return SQLITE_OK if successful or an SQLite error code if an error
127968 ** occurs within a geometry callback.
127969 **
127970 ** This function assumes that the cell is part of a leaf node.
127971 */
127972 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
127973   RtreeCell cell;
127974   int ii;
127975   *pbEof = 0;
127976 
127977   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
127978   for(ii=0; ii<pCursor->nConstraint; ii++){
127979     RtreeConstraint *p = &pCursor->aConstraint[ii];
127980     double coord = DCOORD(cell.aCoord[p->iCoord]);
127981     int res;
127982     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
127983         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
127984     );
127985     switch( p->op ){
127986       case RTREE_LE: res = (coord<=p->rValue); break;
127987       case RTREE_LT: res = (coord<p->rValue);  break;
127988       case RTREE_GE: res = (coord>=p->rValue); break;
127989       case RTREE_GT: res = (coord>p->rValue);  break;
127990       case RTREE_EQ: res = (coord==p->rValue); break;
127991       default: {
127992         int rc;
127993         assert( p->op==RTREE_MATCH );
127994         rc = testRtreeGeom(pRtree, p, &cell, &res);
127995         if( rc!=SQLITE_OK ){
127996           return rc;
127997         }
127998         break;
127999       }
128000     }
128001 
128002     if( !res ){
128003       *pbEof = 1;
128004       return SQLITE_OK;
128005     }
128006   }
128007 
128008   return SQLITE_OK;
128009 }
128010 
128011 /*
128012 ** Cursor pCursor currently points at a node that heads a sub-tree of
128013 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
128014 ** to point to the left-most cell of the sub-tree that matches the
128015 ** configured constraints.
128016 */
128017 static int descendToCell(
128018   Rtree *pRtree,
128019   RtreeCursor *pCursor,
128020   int iHeight,
128021   int *pEof                 /* OUT: Set to true if cannot descend */
128022 ){
128023   int isEof;
128024   int rc;
128025   int ii;
128026   RtreeNode *pChild;
128027   sqlite3_int64 iRowid;
128028 
128029   RtreeNode *pSavedNode = pCursor->pNode;
128030   int iSavedCell = pCursor->iCell;
128031 
128032   assert( iHeight>=0 );
128033 
128034   if( iHeight==0 ){
128035     rc = testRtreeEntry(pRtree, pCursor, &isEof);
128036   }else{
128037     rc = testRtreeCell(pRtree, pCursor, &isEof);
128038   }
128039   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
128040     goto descend_to_cell_out;
128041   }
128042 
128043   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
128044   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
128045   if( rc!=SQLITE_OK ){
128046     goto descend_to_cell_out;
128047   }
128048 
128049   nodeRelease(pRtree, pCursor->pNode);
128050   pCursor->pNode = pChild;
128051   isEof = 1;
128052   for(ii=0; isEof && ii<NCELL(pChild); ii++){
128053     pCursor->iCell = ii;
128054     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
128055     if( rc!=SQLITE_OK ){
128056       goto descend_to_cell_out;
128057     }
128058   }
128059 
128060   if( isEof ){
128061     assert( pCursor->pNode==pChild );
128062     nodeReference(pSavedNode);
128063     nodeRelease(pRtree, pChild);
128064     pCursor->pNode = pSavedNode;
128065     pCursor->iCell = iSavedCell;
128066   }
128067 
128068 descend_to_cell_out:
128069   *pEof = isEof;
128070   return rc;
128071 }
128072 
128073 /*
128074 ** One of the cells in node pNode is guaranteed to have a 64-bit
128075 ** integer value equal to iRowid. Return the index of this cell.
128076 */
128077 static int nodeRowidIndex(
128078   Rtree *pRtree,
128079   RtreeNode *pNode,
128080   i64 iRowid,
128081   int *piIndex
128082 ){
128083   int ii;
128084   int nCell = NCELL(pNode);
128085   for(ii=0; ii<nCell; ii++){
128086     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
128087       *piIndex = ii;
128088       return SQLITE_OK;
128089     }
128090   }
128091   return SQLITE_CORRUPT_VTAB;
128092 }
128093 
128094 /*
128095 ** Return the index of the cell containing a pointer to node pNode
128096 ** in its parent. If pNode is the root node, return -1.
128097 */
128098 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
128099   RtreeNode *pParent = pNode->pParent;
128100   if( pParent ){
128101     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
128102   }
128103   *piIndex = -1;
128104   return SQLITE_OK;
128105 }
128106 
128107 /*
128108 ** Rtree virtual table module xNext method.
128109 */
128110 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
128111   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
128112   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
128113   int rc = SQLITE_OK;
128114 
128115   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
128116   ** already at EOF. It is against the rules to call the xNext() method of
128117   ** a cursor that has already reached EOF.
128118   */
128119   assert( pCsr->pNode );
128120 
128121   if( pCsr->iStrategy==1 ){
128122     /* This "scan" is a direct lookup by rowid. There is no next entry. */
128123     nodeRelease(pRtree, pCsr->pNode);
128124     pCsr->pNode = 0;
128125   }else{
128126     /* Move to the next entry that matches the configured constraints. */
128127     int iHeight = 0;
128128     while( pCsr->pNode ){
128129       RtreeNode *pNode = pCsr->pNode;
128130       int nCell = NCELL(pNode);
128131       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
128132         int isEof;
128133         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
128134         if( rc!=SQLITE_OK || !isEof ){
128135           return rc;
128136         }
128137       }
128138       pCsr->pNode = pNode->pParent;
128139       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
128140       if( rc!=SQLITE_OK ){
128141         return rc;
128142       }
128143       nodeReference(pCsr->pNode);
128144       nodeRelease(pRtree, pNode);
128145       iHeight++;
128146     }
128147   }
128148 
128149   return rc;
128150 }
128151 
128152 /*
128153 ** Rtree virtual table module xRowid method.
128154 */
128155 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
128156   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
128157   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
128158 
128159   assert(pCsr->pNode);
128160   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
128161 
128162   return SQLITE_OK;
128163 }
128164 
128165 /*
128166 ** Rtree virtual table module xColumn method.
128167 */
128168 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
128169   Rtree *pRtree = (Rtree *)cur->pVtab;
128170   RtreeCursor *pCsr = (RtreeCursor *)cur;
128171 
128172   if( i==0 ){
128173     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
128174     sqlite3_result_int64(ctx, iRowid);
128175   }else{
128176     RtreeCoord c;
128177     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
128178     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
128179       sqlite3_result_double(ctx, c.f);
128180     }else{
128181       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
128182       sqlite3_result_int(ctx, c.i);
128183     }
128184   }
128185 
128186   return SQLITE_OK;
128187 }
128188 
128189 /*
128190 ** Use nodeAcquire() to obtain the leaf node containing the record with
128191 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
128192 ** return SQLITE_OK. If there is no such record in the table, set
128193 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
128194 ** to zero and return an SQLite error code.
128195 */
128196 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
128197   int rc;
128198   *ppLeaf = 0;
128199   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
128200   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
128201     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
128202     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
128203     sqlite3_reset(pRtree->pReadRowid);
128204   }else{
128205     rc = sqlite3_reset(pRtree->pReadRowid);
128206   }
128207   return rc;
128208 }
128209 
128210 /*
128211 ** This function is called to configure the RtreeConstraint object passed
128212 ** as the second argument for a MATCH constraint. The value passed as the
128213 ** first argument to this function is the right-hand operand to the MATCH
128214 ** operator.
128215 */
128216 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
128217   RtreeMatchArg *p;
128218   sqlite3_rtree_geometry *pGeom;
128219   int nBlob;
128220 
128221   /* Check that value is actually a blob. */
128222   if( !sqlite3_value_type(pValue)==SQLITE_BLOB ) return SQLITE_ERROR;
128223 
128224   /* Check that the blob is roughly the right size. */
128225   nBlob = sqlite3_value_bytes(pValue);
128226   if( nBlob<(int)sizeof(RtreeMatchArg)
128227    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
128228   ){
128229     return SQLITE_ERROR;
128230   }
128231 
128232   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
128233       sizeof(sqlite3_rtree_geometry) + nBlob
128234   );
128235   if( !pGeom ) return SQLITE_NOMEM;
128236   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
128237   p = (RtreeMatchArg *)&pGeom[1];
128238 
128239   memcpy(p, sqlite3_value_blob(pValue), nBlob);
128240   if( p->magic!=RTREE_GEOMETRY_MAGIC
128241    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
128242   ){
128243     sqlite3_free(pGeom);
128244     return SQLITE_ERROR;
128245   }
128246 
128247   pGeom->pContext = p->pContext;
128248   pGeom->nParam = p->nParam;
128249   pGeom->aParam = p->aParam;
128250 
128251   pCons->xGeom = p->xGeom;
128252   pCons->pGeom = pGeom;
128253   return SQLITE_OK;
128254 }
128255 
128256 /*
128257 ** Rtree virtual table module xFilter method.
128258 */
128259 static int rtreeFilter(
128260   sqlite3_vtab_cursor *pVtabCursor,
128261   int idxNum, const char *idxStr,
128262   int argc, sqlite3_value **argv
128263 ){
128264   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
128265   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
128266 
128267   RtreeNode *pRoot = 0;
128268   int ii;
128269   int rc = SQLITE_OK;
128270 
128271   rtreeReference(pRtree);
128272 
128273   freeCursorConstraints(pCsr);
128274   pCsr->iStrategy = idxNum;
128275 
128276   if( idxNum==1 ){
128277     /* Special case - lookup by rowid. */
128278     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
128279     i64 iRowid = sqlite3_value_int64(argv[0]);
128280     rc = findLeafNode(pRtree, iRowid, &pLeaf);
128281     pCsr->pNode = pLeaf;
128282     if( pLeaf ){
128283       assert( rc==SQLITE_OK );
128284       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
128285     }
128286   }else{
128287     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
128288     ** with the configured constraints.
128289     */
128290     if( argc>0 ){
128291       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
128292       pCsr->nConstraint = argc;
128293       if( !pCsr->aConstraint ){
128294         rc = SQLITE_NOMEM;
128295       }else{
128296         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
128297         assert( (idxStr==0 && argc==0) || (int)strlen(idxStr)==argc*2 );
128298         for(ii=0; ii<argc; ii++){
128299           RtreeConstraint *p = &pCsr->aConstraint[ii];
128300           p->op = idxStr[ii*2];
128301           p->iCoord = idxStr[ii*2+1]-'a';
128302           if( p->op==RTREE_MATCH ){
128303             /* A MATCH operator. The right-hand-side must be a blob that
128304             ** can be cast into an RtreeMatchArg object. One created using
128305             ** an sqlite3_rtree_geometry_callback() SQL user function.
128306             */
128307             rc = deserializeGeometry(argv[ii], p);
128308             if( rc!=SQLITE_OK ){
128309               break;
128310             }
128311           }else{
128312             p->rValue = sqlite3_value_double(argv[ii]);
128313           }
128314         }
128315       }
128316     }
128317 
128318     if( rc==SQLITE_OK ){
128319       pCsr->pNode = 0;
128320       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
128321     }
128322     if( rc==SQLITE_OK ){
128323       int isEof = 1;
128324       int nCell = NCELL(pRoot);
128325       pCsr->pNode = pRoot;
128326       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
128327         assert( pCsr->pNode==pRoot );
128328         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
128329         if( !isEof ){
128330           break;
128331         }
128332       }
128333       if( rc==SQLITE_OK && isEof ){
128334         assert( pCsr->pNode==pRoot );
128335         nodeRelease(pRtree, pRoot);
128336         pCsr->pNode = 0;
128337       }
128338       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
128339     }
128340   }
128341 
128342   rtreeRelease(pRtree);
128343   return rc;
128344 }
128345 
128346 /*
128347 ** Rtree virtual table module xBestIndex method. There are three
128348 ** table scan strategies to choose from (in order from most to
128349 ** least desirable):
128350 **
128351 **   idxNum     idxStr        Strategy
128352 **   ------------------------------------------------
128353 **     1        Unused        Direct lookup by rowid.
128354 **     2        See below     R-tree query or full-table scan.
128355 **   ------------------------------------------------
128356 **
128357 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
128358 ** 2 is used, idxStr is formatted to contain 2 bytes for each
128359 ** constraint used. The first two bytes of idxStr correspond to
128360 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
128361 ** (argvIndex==1) etc.
128362 **
128363 ** The first of each pair of bytes in idxStr identifies the constraint
128364 ** operator as follows:
128365 **
128366 **   Operator    Byte Value
128367 **   ----------------------
128368 **      =        0x41 ('A')
128369 **     <=        0x42 ('B')
128370 **      <        0x43 ('C')
128371 **     >=        0x44 ('D')
128372 **      >        0x45 ('E')
128373 **   MATCH       0x46 ('F')
128374 **   ----------------------
128375 **
128376 ** The second of each pair of bytes identifies the coordinate column
128377 ** to which the constraint applies. The leftmost coordinate column
128378 ** is 'a', the second from the left 'b' etc.
128379 */
128380 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
128381   int rc = SQLITE_OK;
128382   int ii;
128383 
128384   int iIdx = 0;
128385   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
128386   memset(zIdxStr, 0, sizeof(zIdxStr));
128387   UNUSED_PARAMETER(tab);
128388 
128389   assert( pIdxInfo->idxStr==0 );
128390   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
128391     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
128392 
128393     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
128394       /* We have an equality constraint on the rowid. Use strategy 1. */
128395       int jj;
128396       for(jj=0; jj<ii; jj++){
128397         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
128398         pIdxInfo->aConstraintUsage[jj].omit = 0;
128399       }
128400       pIdxInfo->idxNum = 1;
128401       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
128402       pIdxInfo->aConstraintUsage[jj].omit = 1;
128403 
128404       /* This strategy involves a two rowid lookups on an B-Tree structures
128405       ** and then a linear search of an R-Tree node. This should be
128406       ** considered almost as quick as a direct rowid lookup (for which
128407       ** sqlite uses an internal cost of 0.0).
128408       */
128409       pIdxInfo->estimatedCost = 10.0;
128410       return SQLITE_OK;
128411     }
128412 
128413     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
128414       u8 op;
128415       switch( p->op ){
128416         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
128417         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
128418         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
128419         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
128420         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
128421         default:
128422           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
128423           op = RTREE_MATCH;
128424           break;
128425       }
128426       zIdxStr[iIdx++] = op;
128427       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
128428       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
128429       pIdxInfo->aConstraintUsage[ii].omit = 1;
128430     }
128431   }
128432 
128433   pIdxInfo->idxNum = 2;
128434   pIdxInfo->needToFreeIdxStr = 1;
128435   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
128436     return SQLITE_NOMEM;
128437   }
128438   assert( iIdx>=0 );
128439   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
128440   return rc;
128441 }
128442 
128443 /*
128444 ** Return the N-dimensional volumn of the cell stored in *p.
128445 */
128446 static float cellArea(Rtree *pRtree, RtreeCell *p){
128447   float area = 1.0;
128448   int ii;
128449   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
128450     area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
128451   }
128452   return area;
128453 }
128454 
128455 /*
128456 ** Return the margin length of cell p. The margin length is the sum
128457 ** of the objects size in each dimension.
128458 */
128459 static float cellMargin(Rtree *pRtree, RtreeCell *p){
128460   float margin = 0.0;
128461   int ii;
128462   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
128463     margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
128464   }
128465   return margin;
128466 }
128467 
128468 /*
128469 ** Store the union of cells p1 and p2 in p1.
128470 */
128471 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
128472   int ii;
128473   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
128474     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
128475       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
128476       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
128477     }
128478   }else{
128479     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
128480       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
128481       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
128482     }
128483   }
128484 }
128485 
128486 /*
128487 ** Return true if the area covered by p2 is a subset of the area covered
128488 ** by p1. False otherwise.
128489 */
128490 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
128491   int ii;
128492   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
128493   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
128494     RtreeCoord *a1 = &p1->aCoord[ii];
128495     RtreeCoord *a2 = &p2->aCoord[ii];
128496     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
128497      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
128498     ){
128499       return 0;
128500     }
128501   }
128502   return 1;
128503 }
128504 
128505 /*
128506 ** Return the amount cell p would grow by if it were unioned with pCell.
128507 */
128508 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
128509   float area;
128510   RtreeCell cell;
128511   memcpy(&cell, p, sizeof(RtreeCell));
128512   area = cellArea(pRtree, &cell);
128513   cellUnion(pRtree, &cell, pCell);
128514   return (cellArea(pRtree, &cell)-area);
128515 }
128516 
128517 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
128518 static float cellOverlap(
128519   Rtree *pRtree,
128520   RtreeCell *p,
128521   RtreeCell *aCell,
128522   int nCell,
128523   int iExclude
128524 ){
128525   int ii;
128526   float overlap = 0.0;
128527   for(ii=0; ii<nCell; ii++){
128528 #if VARIANT_RSTARTREE_CHOOSESUBTREE
128529     if( ii!=iExclude )
128530 #else
128531     assert( iExclude==-1 );
128532     UNUSED_PARAMETER(iExclude);
128533 #endif
128534     {
128535       int jj;
128536       float o = 1.0;
128537       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
128538         double x1;
128539         double x2;
128540 
128541         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
128542         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
128543 
128544         if( x2<x1 ){
128545           o = 0.0;
128546           break;
128547         }else{
128548           o = o * (float)(x2-x1);
128549         }
128550       }
128551       overlap += o;
128552     }
128553   }
128554   return overlap;
128555 }
128556 #endif
128557 
128558 #if VARIANT_RSTARTREE_CHOOSESUBTREE
128559 static float cellOverlapEnlargement(
128560   Rtree *pRtree,
128561   RtreeCell *p,
128562   RtreeCell *pInsert,
128563   RtreeCell *aCell,
128564   int nCell,
128565   int iExclude
128566 ){
128567   double before;
128568   double after;
128569   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
128570   cellUnion(pRtree, p, pInsert);
128571   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
128572   return (float)(after-before);
128573 }
128574 #endif
128575 
128576 
128577 /*
128578 ** This function implements the ChooseLeaf algorithm from Gutman[84].
128579 ** ChooseSubTree in r*tree terminology.
128580 */
128581 static int ChooseLeaf(
128582   Rtree *pRtree,               /* Rtree table */
128583   RtreeCell *pCell,            /* Cell to insert into rtree */
128584   int iHeight,                 /* Height of sub-tree rooted at pCell */
128585   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
128586 ){
128587   int rc;
128588   int ii;
128589   RtreeNode *pNode;
128590   rc = nodeAcquire(pRtree, 1, 0, &pNode);
128591 
128592   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
128593     int iCell;
128594     sqlite3_int64 iBest = 0;
128595 
128596     float fMinGrowth = 0.0;
128597     float fMinArea = 0.0;
128598     float fMinOverlap = 0.0;
128599 
128600     int nCell = NCELL(pNode);
128601     RtreeCell cell;
128602     RtreeNode *pChild;
128603 
128604     RtreeCell *aCell = 0;
128605 
128606 #if VARIANT_RSTARTREE_CHOOSESUBTREE
128607     if( ii==(pRtree->iDepth-1) ){
128608       int jj;
128609       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
128610       if( !aCell ){
128611         rc = SQLITE_NOMEM;
128612         nodeRelease(pRtree, pNode);
128613         pNode = 0;
128614         continue;
128615       }
128616       for(jj=0; jj<nCell; jj++){
128617         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
128618       }
128619     }
128620 #endif
128621 
128622     /* Select the child node which will be enlarged the least if pCell
128623     ** is inserted into it. Resolve ties by choosing the entry with
128624     ** the smallest area.
128625     */
128626     for(iCell=0; iCell<nCell; iCell++){
128627       int bBest = 0;
128628       float growth;
128629       float area;
128630       float overlap = 0.0;
128631       nodeGetCell(pRtree, pNode, iCell, &cell);
128632       growth = cellGrowth(pRtree, &cell, pCell);
128633       area = cellArea(pRtree, &cell);
128634 
128635 #if VARIANT_RSTARTREE_CHOOSESUBTREE
128636       if( ii==(pRtree->iDepth-1) ){
128637         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
128638       }
128639       if( (iCell==0)
128640        || (overlap<fMinOverlap)
128641        || (overlap==fMinOverlap && growth<fMinGrowth)
128642        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
128643       ){
128644         bBest = 1;
128645       }
128646 #else
128647       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
128648         bBest = 1;
128649       }
128650 #endif
128651       if( bBest ){
128652         fMinOverlap = overlap;
128653         fMinGrowth = growth;
128654         fMinArea = area;
128655         iBest = cell.iRowid;
128656       }
128657     }
128658 
128659     sqlite3_free(aCell);
128660     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
128661     nodeRelease(pRtree, pNode);
128662     pNode = pChild;
128663   }
128664 
128665   *ppLeaf = pNode;
128666   return rc;
128667 }
128668 
128669 /*
128670 ** A cell with the same content as pCell has just been inserted into
128671 ** the node pNode. This function updates the bounding box cells in
128672 ** all ancestor elements.
128673 */
128674 static int AdjustTree(
128675   Rtree *pRtree,                    /* Rtree table */
128676   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
128677   RtreeCell *pCell                  /* This cell was just inserted */
128678 ){
128679   RtreeNode *p = pNode;
128680   while( p->pParent ){
128681     RtreeNode *pParent = p->pParent;
128682     RtreeCell cell;
128683     int iCell;
128684 
128685     if( nodeParentIndex(pRtree, p, &iCell) ){
128686       return SQLITE_CORRUPT_VTAB;
128687     }
128688 
128689     nodeGetCell(pRtree, pParent, iCell, &cell);
128690     if( !cellContains(pRtree, &cell, pCell) ){
128691       cellUnion(pRtree, &cell, pCell);
128692       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
128693     }
128694 
128695     p = pParent;
128696   }
128697   return SQLITE_OK;
128698 }
128699 
128700 /*
128701 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
128702 */
128703 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
128704   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
128705   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
128706   sqlite3_step(pRtree->pWriteRowid);
128707   return sqlite3_reset(pRtree->pWriteRowid);
128708 }
128709 
128710 /*
128711 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
128712 */
128713 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
128714   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
128715   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
128716   sqlite3_step(pRtree->pWriteParent);
128717   return sqlite3_reset(pRtree->pWriteParent);
128718 }
128719 
128720 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
128721 
128722 #if VARIANT_GUTTMAN_LINEAR_SPLIT
128723 /*
128724 ** Implementation of the linear variant of the PickNext() function from
128725 ** Guttman[84].
128726 */
128727 static RtreeCell *LinearPickNext(
128728   Rtree *pRtree,
128729   RtreeCell *aCell,
128730   int nCell,
128731   RtreeCell *pLeftBox,
128732   RtreeCell *pRightBox,
128733   int *aiUsed
128734 ){
128735   int ii;
128736   for(ii=0; aiUsed[ii]; ii++);
128737   aiUsed[ii] = 1;
128738   return &aCell[ii];
128739 }
128740 
128741 /*
128742 ** Implementation of the linear variant of the PickSeeds() function from
128743 ** Guttman[84].
128744 */
128745 static void LinearPickSeeds(
128746   Rtree *pRtree,
128747   RtreeCell *aCell,
128748   int nCell,
128749   int *piLeftSeed,
128750   int *piRightSeed
128751 ){
128752   int i;
128753   int iLeftSeed = 0;
128754   int iRightSeed = 1;
128755   float maxNormalInnerWidth = 0.0;
128756 
128757   /* Pick two "seed" cells from the array of cells. The algorithm used
128758   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
128759   ** indices of the two seed cells in the array are stored in local
128760   ** variables iLeftSeek and iRightSeed.
128761   */
128762   for(i=0; i<pRtree->nDim; i++){
128763     float x1 = DCOORD(aCell[0].aCoord[i*2]);
128764     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
128765     float x3 = x1;
128766     float x4 = x2;
128767     int jj;
128768 
128769     int iCellLeft = 0;
128770     int iCellRight = 0;
128771 
128772     for(jj=1; jj<nCell; jj++){
128773       float left = DCOORD(aCell[jj].aCoord[i*2]);
128774       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
128775 
128776       if( left<x1 ) x1 = left;
128777       if( right>x4 ) x4 = right;
128778       if( left>x3 ){
128779         x3 = left;
128780         iCellRight = jj;
128781       }
128782       if( right<x2 ){
128783         x2 = right;
128784         iCellLeft = jj;
128785       }
128786     }
128787 
128788     if( x4!=x1 ){
128789       float normalwidth = (x3 - x2) / (x4 - x1);
128790       if( normalwidth>maxNormalInnerWidth ){
128791         iLeftSeed = iCellLeft;
128792         iRightSeed = iCellRight;
128793       }
128794     }
128795   }
128796 
128797   *piLeftSeed = iLeftSeed;
128798   *piRightSeed = iRightSeed;
128799 }
128800 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
128801 
128802 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
128803 /*
128804 ** Implementation of the quadratic variant of the PickNext() function from
128805 ** Guttman[84].
128806 */
128807 static RtreeCell *QuadraticPickNext(
128808   Rtree *pRtree,
128809   RtreeCell *aCell,
128810   int nCell,
128811   RtreeCell *pLeftBox,
128812   RtreeCell *pRightBox,
128813   int *aiUsed
128814 ){
128815   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
128816 
128817   int iSelect = -1;
128818   float fDiff;
128819   int ii;
128820   for(ii=0; ii<nCell; ii++){
128821     if( aiUsed[ii]==0 ){
128822       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
128823       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
128824       float diff = FABS(right-left);
128825       if( iSelect<0 || diff>fDiff ){
128826         fDiff = diff;
128827         iSelect = ii;
128828       }
128829     }
128830   }
128831   aiUsed[iSelect] = 1;
128832   return &aCell[iSelect];
128833 }
128834 
128835 /*
128836 ** Implementation of the quadratic variant of the PickSeeds() function from
128837 ** Guttman[84].
128838 */
128839 static void QuadraticPickSeeds(
128840   Rtree *pRtree,
128841   RtreeCell *aCell,
128842   int nCell,
128843   int *piLeftSeed,
128844   int *piRightSeed
128845 ){
128846   int ii;
128847   int jj;
128848 
128849   int iLeftSeed = 0;
128850   int iRightSeed = 1;
128851   float fWaste = 0.0;
128852 
128853   for(ii=0; ii<nCell; ii++){
128854     for(jj=ii+1; jj<nCell; jj++){
128855       float right = cellArea(pRtree, &aCell[jj]);
128856       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
128857       float waste = growth - right;
128858 
128859       if( waste>fWaste ){
128860         iLeftSeed = ii;
128861         iRightSeed = jj;
128862         fWaste = waste;
128863       }
128864     }
128865   }
128866 
128867   *piLeftSeed = iLeftSeed;
128868   *piRightSeed = iRightSeed;
128869 }
128870 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
128871 
128872 /*
128873 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
128874 ** nIdx. The aIdx array contains the set of integers from 0 to
128875 ** (nIdx-1) in no particular order. This function sorts the values
128876 ** in aIdx according to the indexed values in aDistance. For
128877 ** example, assuming the inputs:
128878 **
128879 **   aIdx      = { 0,   1,   2,   3 }
128880 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
128881 **
128882 ** this function sets the aIdx array to contain:
128883 **
128884 **   aIdx      = { 0,   1,   2,   3 }
128885 **
128886 ** The aSpare array is used as temporary working space by the
128887 ** sorting algorithm.
128888 */
128889 static void SortByDistance(
128890   int *aIdx,
128891   int nIdx,
128892   float *aDistance,
128893   int *aSpare
128894 ){
128895   if( nIdx>1 ){
128896     int iLeft = 0;
128897     int iRight = 0;
128898 
128899     int nLeft = nIdx/2;
128900     int nRight = nIdx-nLeft;
128901     int *aLeft = aIdx;
128902     int *aRight = &aIdx[nLeft];
128903 
128904     SortByDistance(aLeft, nLeft, aDistance, aSpare);
128905     SortByDistance(aRight, nRight, aDistance, aSpare);
128906 
128907     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
128908     aLeft = aSpare;
128909 
128910     while( iLeft<nLeft || iRight<nRight ){
128911       if( iLeft==nLeft ){
128912         aIdx[iLeft+iRight] = aRight[iRight];
128913         iRight++;
128914       }else if( iRight==nRight ){
128915         aIdx[iLeft+iRight] = aLeft[iLeft];
128916         iLeft++;
128917       }else{
128918         float fLeft = aDistance[aLeft[iLeft]];
128919         float fRight = aDistance[aRight[iRight]];
128920         if( fLeft<fRight ){
128921           aIdx[iLeft+iRight] = aLeft[iLeft];
128922           iLeft++;
128923         }else{
128924           aIdx[iLeft+iRight] = aRight[iRight];
128925           iRight++;
128926         }
128927       }
128928     }
128929 
128930 #if 0
128931     /* Check that the sort worked */
128932     {
128933       int jj;
128934       for(jj=1; jj<nIdx; jj++){
128935         float left = aDistance[aIdx[jj-1]];
128936         float right = aDistance[aIdx[jj]];
128937         assert( left<=right );
128938       }
128939     }
128940 #endif
128941   }
128942 }
128943 
128944 /*
128945 ** Arguments aIdx, aCell and aSpare all point to arrays of size
128946 ** nIdx. The aIdx array contains the set of integers from 0 to
128947 ** (nIdx-1) in no particular order. This function sorts the values
128948 ** in aIdx according to dimension iDim of the cells in aCell. The
128949 ** minimum value of dimension iDim is considered first, the
128950 ** maximum used to break ties.
128951 **
128952 ** The aSpare array is used as temporary working space by the
128953 ** sorting algorithm.
128954 */
128955 static void SortByDimension(
128956   Rtree *pRtree,
128957   int *aIdx,
128958   int nIdx,
128959   int iDim,
128960   RtreeCell *aCell,
128961   int *aSpare
128962 ){
128963   if( nIdx>1 ){
128964 
128965     int iLeft = 0;
128966     int iRight = 0;
128967 
128968     int nLeft = nIdx/2;
128969     int nRight = nIdx-nLeft;
128970     int *aLeft = aIdx;
128971     int *aRight = &aIdx[nLeft];
128972 
128973     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
128974     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
128975 
128976     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
128977     aLeft = aSpare;
128978     while( iLeft<nLeft || iRight<nRight ){
128979       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
128980       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
128981       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
128982       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
128983       if( (iLeft!=nLeft) && ((iRight==nRight)
128984        || (xleft1<xright1)
128985        || (xleft1==xright1 && xleft2<xright2)
128986       )){
128987         aIdx[iLeft+iRight] = aLeft[iLeft];
128988         iLeft++;
128989       }else{
128990         aIdx[iLeft+iRight] = aRight[iRight];
128991         iRight++;
128992       }
128993     }
128994 
128995 #if 0
128996     /* Check that the sort worked */
128997     {
128998       int jj;
128999       for(jj=1; jj<nIdx; jj++){
129000         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
129001         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
129002         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
129003         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
129004         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
129005       }
129006     }
129007 #endif
129008   }
129009 }
129010 
129011 #if VARIANT_RSTARTREE_SPLIT
129012 /*
129013 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
129014 */
129015 static int splitNodeStartree(
129016   Rtree *pRtree,
129017   RtreeCell *aCell,
129018   int nCell,
129019   RtreeNode *pLeft,
129020   RtreeNode *pRight,
129021   RtreeCell *pBboxLeft,
129022   RtreeCell *pBboxRight
129023 ){
129024   int **aaSorted;
129025   int *aSpare;
129026   int ii;
129027 
129028   int iBestDim = 0;
129029   int iBestSplit = 0;
129030   float fBestMargin = 0.0;
129031 
129032   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
129033 
129034   aaSorted = (int **)sqlite3_malloc(nByte);
129035   if( !aaSorted ){
129036     return SQLITE_NOMEM;
129037   }
129038 
129039   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
129040   memset(aaSorted, 0, nByte);
129041   for(ii=0; ii<pRtree->nDim; ii++){
129042     int jj;
129043     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
129044     for(jj=0; jj<nCell; jj++){
129045       aaSorted[ii][jj] = jj;
129046     }
129047     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
129048   }
129049 
129050   for(ii=0; ii<pRtree->nDim; ii++){
129051     float margin = 0.0;
129052     float fBestOverlap = 0.0;
129053     float fBestArea = 0.0;
129054     int iBestLeft = 0;
129055     int nLeft;
129056 
129057     for(
129058       nLeft=RTREE_MINCELLS(pRtree);
129059       nLeft<=(nCell-RTREE_MINCELLS(pRtree));
129060       nLeft++
129061     ){
129062       RtreeCell left;
129063       RtreeCell right;
129064       int kk;
129065       float overlap;
129066       float area;
129067 
129068       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
129069       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
129070       for(kk=1; kk<(nCell-1); kk++){
129071         if( kk<nLeft ){
129072           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
129073         }else{
129074           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
129075         }
129076       }
129077       margin += cellMargin(pRtree, &left);
129078       margin += cellMargin(pRtree, &right);
129079       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
129080       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
129081       if( (nLeft==RTREE_MINCELLS(pRtree))
129082        || (overlap<fBestOverlap)
129083        || (overlap==fBestOverlap && area<fBestArea)
129084       ){
129085         iBestLeft = nLeft;
129086         fBestOverlap = overlap;
129087         fBestArea = area;
129088       }
129089     }
129090 
129091     if( ii==0 || margin<fBestMargin ){
129092       iBestDim = ii;
129093       fBestMargin = margin;
129094       iBestSplit = iBestLeft;
129095     }
129096   }
129097 
129098   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
129099   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
129100   for(ii=0; ii<nCell; ii++){
129101     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
129102     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
129103     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
129104     nodeInsertCell(pRtree, pTarget, pCell);
129105     cellUnion(pRtree, pBbox, pCell);
129106   }
129107 
129108   sqlite3_free(aaSorted);
129109   return SQLITE_OK;
129110 }
129111 #endif
129112 
129113 #if VARIANT_GUTTMAN_SPLIT
129114 /*
129115 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
129116 */
129117 static int splitNodeGuttman(
129118   Rtree *pRtree,
129119   RtreeCell *aCell,
129120   int nCell,
129121   RtreeNode *pLeft,
129122   RtreeNode *pRight,
129123   RtreeCell *pBboxLeft,
129124   RtreeCell *pBboxRight
129125 ){
129126   int iLeftSeed = 0;
129127   int iRightSeed = 1;
129128   int *aiUsed;
129129   int i;
129130 
129131   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
129132   if( !aiUsed ){
129133     return SQLITE_NOMEM;
129134   }
129135   memset(aiUsed, 0, sizeof(int)*nCell);
129136 
129137   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
129138 
129139   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
129140   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
129141   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
129142   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
129143   aiUsed[iLeftSeed] = 1;
129144   aiUsed[iRightSeed] = 1;
129145 
129146   for(i=nCell-2; i>0; i--){
129147     RtreeCell *pNext;
129148     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
129149     float diff =
129150       cellGrowth(pRtree, pBboxLeft, pNext) -
129151       cellGrowth(pRtree, pBboxRight, pNext)
129152     ;
129153     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
129154      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
129155     ){
129156       nodeInsertCell(pRtree, pRight, pNext);
129157       cellUnion(pRtree, pBboxRight, pNext);
129158     }else{
129159       nodeInsertCell(pRtree, pLeft, pNext);
129160       cellUnion(pRtree, pBboxLeft, pNext);
129161     }
129162   }
129163 
129164   sqlite3_free(aiUsed);
129165   return SQLITE_OK;
129166 }
129167 #endif
129168 
129169 static int updateMapping(
129170   Rtree *pRtree,
129171   i64 iRowid,
129172   RtreeNode *pNode,
129173   int iHeight
129174 ){
129175   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
129176   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
129177   if( iHeight>0 ){
129178     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
129179     if( pChild ){
129180       nodeRelease(pRtree, pChild->pParent);
129181       nodeReference(pNode);
129182       pChild->pParent = pNode;
129183     }
129184   }
129185   return xSetMapping(pRtree, iRowid, pNode->iNode);
129186 }
129187 
129188 static int SplitNode(
129189   Rtree *pRtree,
129190   RtreeNode *pNode,
129191   RtreeCell *pCell,
129192   int iHeight
129193 ){
129194   int i;
129195   int newCellIsRight = 0;
129196 
129197   int rc = SQLITE_OK;
129198   int nCell = NCELL(pNode);
129199   RtreeCell *aCell;
129200   int *aiUsed;
129201 
129202   RtreeNode *pLeft = 0;
129203   RtreeNode *pRight = 0;
129204 
129205   RtreeCell leftbbox;
129206   RtreeCell rightbbox;
129207 
129208   /* Allocate an array and populate it with a copy of pCell and
129209   ** all cells from node pLeft. Then zero the original node.
129210   */
129211   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
129212   if( !aCell ){
129213     rc = SQLITE_NOMEM;
129214     goto splitnode_out;
129215   }
129216   aiUsed = (int *)&aCell[nCell+1];
129217   memset(aiUsed, 0, sizeof(int)*(nCell+1));
129218   for(i=0; i<nCell; i++){
129219     nodeGetCell(pRtree, pNode, i, &aCell[i]);
129220   }
129221   nodeZero(pRtree, pNode);
129222   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
129223   nCell++;
129224 
129225   if( pNode->iNode==1 ){
129226     pRight = nodeNew(pRtree, pNode);
129227     pLeft = nodeNew(pRtree, pNode);
129228     pRtree->iDepth++;
129229     pNode->isDirty = 1;
129230     writeInt16(pNode->zData, pRtree->iDepth);
129231   }else{
129232     pLeft = pNode;
129233     pRight = nodeNew(pRtree, pLeft->pParent);
129234     nodeReference(pLeft);
129235   }
129236 
129237   if( !pLeft || !pRight ){
129238     rc = SQLITE_NOMEM;
129239     goto splitnode_out;
129240   }
129241 
129242   memset(pLeft->zData, 0, pRtree->iNodeSize);
129243   memset(pRight->zData, 0, pRtree->iNodeSize);
129244 
129245   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
129246   if( rc!=SQLITE_OK ){
129247     goto splitnode_out;
129248   }
129249 
129250   /* Ensure both child nodes have node numbers assigned to them by calling
129251   ** nodeWrite(). Node pRight always needs a node number, as it was created
129252   ** by nodeNew() above. But node pLeft sometimes already has a node number.
129253   ** In this case avoid the all to nodeWrite().
129254   */
129255   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
129256    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
129257   ){
129258     goto splitnode_out;
129259   }
129260 
129261   rightbbox.iRowid = pRight->iNode;
129262   leftbbox.iRowid = pLeft->iNode;
129263 
129264   if( pNode->iNode==1 ){
129265     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
129266     if( rc!=SQLITE_OK ){
129267       goto splitnode_out;
129268     }
129269   }else{
129270     RtreeNode *pParent = pLeft->pParent;
129271     int iCell;
129272     rc = nodeParentIndex(pRtree, pLeft, &iCell);
129273     if( rc==SQLITE_OK ){
129274       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
129275       rc = AdjustTree(pRtree, pParent, &leftbbox);
129276     }
129277     if( rc!=SQLITE_OK ){
129278       goto splitnode_out;
129279     }
129280   }
129281   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
129282     goto splitnode_out;
129283   }
129284 
129285   for(i=0; i<NCELL(pRight); i++){
129286     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
129287     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
129288     if( iRowid==pCell->iRowid ){
129289       newCellIsRight = 1;
129290     }
129291     if( rc!=SQLITE_OK ){
129292       goto splitnode_out;
129293     }
129294   }
129295   if( pNode->iNode==1 ){
129296     for(i=0; i<NCELL(pLeft); i++){
129297       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
129298       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
129299       if( rc!=SQLITE_OK ){
129300         goto splitnode_out;
129301       }
129302     }
129303   }else if( newCellIsRight==0 ){
129304     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
129305   }
129306 
129307   if( rc==SQLITE_OK ){
129308     rc = nodeRelease(pRtree, pRight);
129309     pRight = 0;
129310   }
129311   if( rc==SQLITE_OK ){
129312     rc = nodeRelease(pRtree, pLeft);
129313     pLeft = 0;
129314   }
129315 
129316 splitnode_out:
129317   nodeRelease(pRtree, pRight);
129318   nodeRelease(pRtree, pLeft);
129319   sqlite3_free(aCell);
129320   return rc;
129321 }
129322 
129323 /*
129324 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
129325 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
129326 ** the pLeaf->pParent chain all the way up to the root node.
129327 **
129328 ** This operation is required when a row is deleted (or updated - an update
129329 ** is implemented as a delete followed by an insert). SQLite provides the
129330 ** rowid of the row to delete, which can be used to find the leaf on which
129331 ** the entry resides (argument pLeaf). Once the leaf is located, this
129332 ** function is called to determine its ancestry.
129333 */
129334 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
129335   int rc = SQLITE_OK;
129336   RtreeNode *pChild = pLeaf;
129337   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
129338     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
129339     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
129340     rc = sqlite3_step(pRtree->pReadParent);
129341     if( rc==SQLITE_ROW ){
129342       RtreeNode *pTest;           /* Used to test for reference loops */
129343       i64 iNode;                  /* Node number of parent node */
129344 
129345       /* Before setting pChild->pParent, test that we are not creating a
129346       ** loop of references (as we would if, say, pChild==pParent). We don't
129347       ** want to do this as it leads to a memory leak when trying to delete
129348       ** the referenced counted node structures.
129349       */
129350       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
129351       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
129352       if( !pTest ){
129353         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
129354       }
129355     }
129356     rc = sqlite3_reset(pRtree->pReadParent);
129357     if( rc==SQLITE_OK ) rc = rc2;
129358     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
129359     pChild = pChild->pParent;
129360   }
129361   return rc;
129362 }
129363 
129364 static int deleteCell(Rtree *, RtreeNode *, int, int);
129365 
129366 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
129367   int rc;
129368   int rc2;
129369   RtreeNode *pParent = 0;
129370   int iCell;
129371 
129372   assert( pNode->nRef==1 );
129373 
129374   /* Remove the entry in the parent cell. */
129375   rc = nodeParentIndex(pRtree, pNode, &iCell);
129376   if( rc==SQLITE_OK ){
129377     pParent = pNode->pParent;
129378     pNode->pParent = 0;
129379     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
129380   }
129381   rc2 = nodeRelease(pRtree, pParent);
129382   if( rc==SQLITE_OK ){
129383     rc = rc2;
129384   }
129385   if( rc!=SQLITE_OK ){
129386     return rc;
129387   }
129388 
129389   /* Remove the xxx_node entry. */
129390   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
129391   sqlite3_step(pRtree->pDeleteNode);
129392   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
129393     return rc;
129394   }
129395 
129396   /* Remove the xxx_parent entry. */
129397   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
129398   sqlite3_step(pRtree->pDeleteParent);
129399   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
129400     return rc;
129401   }
129402 
129403   /* Remove the node from the in-memory hash table and link it into
129404   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
129405   */
129406   nodeHashDelete(pRtree, pNode);
129407   pNode->iNode = iHeight;
129408   pNode->pNext = pRtree->pDeleted;
129409   pNode->nRef++;
129410   pRtree->pDeleted = pNode;
129411 
129412   return SQLITE_OK;
129413 }
129414 
129415 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
129416   RtreeNode *pParent = pNode->pParent;
129417   int rc = SQLITE_OK;
129418   if( pParent ){
129419     int ii;
129420     int nCell = NCELL(pNode);
129421     RtreeCell box;                            /* Bounding box for pNode */
129422     nodeGetCell(pRtree, pNode, 0, &box);
129423     for(ii=1; ii<nCell; ii++){
129424       RtreeCell cell;
129425       nodeGetCell(pRtree, pNode, ii, &cell);
129426       cellUnion(pRtree, &box, &cell);
129427     }
129428     box.iRowid = pNode->iNode;
129429     rc = nodeParentIndex(pRtree, pNode, &ii);
129430     if( rc==SQLITE_OK ){
129431       nodeOverwriteCell(pRtree, pParent, &box, ii);
129432       rc = fixBoundingBox(pRtree, pParent);
129433     }
129434   }
129435   return rc;
129436 }
129437 
129438 /*
129439 ** Delete the cell at index iCell of node pNode. After removing the
129440 ** cell, adjust the r-tree data structure if required.
129441 */
129442 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
129443   RtreeNode *pParent;
129444   int rc;
129445 
129446   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
129447     return rc;
129448   }
129449 
129450   /* Remove the cell from the node. This call just moves bytes around
129451   ** the in-memory node image, so it cannot fail.
129452   */
129453   nodeDeleteCell(pRtree, pNode, iCell);
129454 
129455   /* If the node is not the tree root and now has less than the minimum
129456   ** number of cells, remove it from the tree. Otherwise, update the
129457   ** cell in the parent node so that it tightly contains the updated
129458   ** node.
129459   */
129460   pParent = pNode->pParent;
129461   assert( pParent || pNode->iNode==1 );
129462   if( pParent ){
129463     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
129464       rc = removeNode(pRtree, pNode, iHeight);
129465     }else{
129466       rc = fixBoundingBox(pRtree, pNode);
129467     }
129468   }
129469 
129470   return rc;
129471 }
129472 
129473 static int Reinsert(
129474   Rtree *pRtree,
129475   RtreeNode *pNode,
129476   RtreeCell *pCell,
129477   int iHeight
129478 ){
129479   int *aOrder;
129480   int *aSpare;
129481   RtreeCell *aCell;
129482   float *aDistance;
129483   int nCell;
129484   float aCenterCoord[RTREE_MAX_DIMENSIONS];
129485   int iDim;
129486   int ii;
129487   int rc = SQLITE_OK;
129488 
129489   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
129490 
129491   nCell = NCELL(pNode)+1;
129492 
129493   /* Allocate the buffers used by this operation. The allocation is
129494   ** relinquished before this function returns.
129495   */
129496   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
129497     sizeof(RtreeCell) +         /* aCell array */
129498     sizeof(int)       +         /* aOrder array */
129499     sizeof(int)       +         /* aSpare array */
129500     sizeof(float)               /* aDistance array */
129501   ));
129502   if( !aCell ){
129503     return SQLITE_NOMEM;
129504   }
129505   aOrder    = (int *)&aCell[nCell];
129506   aSpare    = (int *)&aOrder[nCell];
129507   aDistance = (float *)&aSpare[nCell];
129508 
129509   for(ii=0; ii<nCell; ii++){
129510     if( ii==(nCell-1) ){
129511       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
129512     }else{
129513       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
129514     }
129515     aOrder[ii] = ii;
129516     for(iDim=0; iDim<pRtree->nDim; iDim++){
129517       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
129518       aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
129519     }
129520   }
129521   for(iDim=0; iDim<pRtree->nDim; iDim++){
129522     aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
129523   }
129524 
129525   for(ii=0; ii<nCell; ii++){
129526     aDistance[ii] = 0.0;
129527     for(iDim=0; iDim<pRtree->nDim; iDim++){
129528       float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
129529           DCOORD(aCell[ii].aCoord[iDim*2]));
129530       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
129531     }
129532   }
129533 
129534   SortByDistance(aOrder, nCell, aDistance, aSpare);
129535   nodeZero(pRtree, pNode);
129536 
129537   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
129538     RtreeCell *p = &aCell[aOrder[ii]];
129539     nodeInsertCell(pRtree, pNode, p);
129540     if( p->iRowid==pCell->iRowid ){
129541       if( iHeight==0 ){
129542         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
129543       }else{
129544         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
129545       }
129546     }
129547   }
129548   if( rc==SQLITE_OK ){
129549     rc = fixBoundingBox(pRtree, pNode);
129550   }
129551   for(; rc==SQLITE_OK && ii<nCell; ii++){
129552     /* Find a node to store this cell in. pNode->iNode currently contains
129553     ** the height of the sub-tree headed by the cell.
129554     */
129555     RtreeNode *pInsert;
129556     RtreeCell *p = &aCell[aOrder[ii]];
129557     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
129558     if( rc==SQLITE_OK ){
129559       int rc2;
129560       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
129561       rc2 = nodeRelease(pRtree, pInsert);
129562       if( rc==SQLITE_OK ){
129563         rc = rc2;
129564       }
129565     }
129566   }
129567 
129568   sqlite3_free(aCell);
129569   return rc;
129570 }
129571 
129572 /*
129573 ** Insert cell pCell into node pNode. Node pNode is the head of a
129574 ** subtree iHeight high (leaf nodes have iHeight==0).
129575 */
129576 static int rtreeInsertCell(
129577   Rtree *pRtree,
129578   RtreeNode *pNode,
129579   RtreeCell *pCell,
129580   int iHeight
129581 ){
129582   int rc = SQLITE_OK;
129583   if( iHeight>0 ){
129584     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
129585     if( pChild ){
129586       nodeRelease(pRtree, pChild->pParent);
129587       nodeReference(pNode);
129588       pChild->pParent = pNode;
129589     }
129590   }
129591   if( nodeInsertCell(pRtree, pNode, pCell) ){
129592 #if VARIANT_RSTARTREE_REINSERT
129593     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
129594       rc = SplitNode(pRtree, pNode, pCell, iHeight);
129595     }else{
129596       pRtree->iReinsertHeight = iHeight;
129597       rc = Reinsert(pRtree, pNode, pCell, iHeight);
129598     }
129599 #else
129600     rc = SplitNode(pRtree, pNode, pCell, iHeight);
129601 #endif
129602   }else{
129603     rc = AdjustTree(pRtree, pNode, pCell);
129604     if( rc==SQLITE_OK ){
129605       if( iHeight==0 ){
129606         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
129607       }else{
129608         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
129609       }
129610     }
129611   }
129612   return rc;
129613 }
129614 
129615 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
129616   int ii;
129617   int rc = SQLITE_OK;
129618   int nCell = NCELL(pNode);
129619 
129620   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
129621     RtreeNode *pInsert;
129622     RtreeCell cell;
129623     nodeGetCell(pRtree, pNode, ii, &cell);
129624 
129625     /* Find a node to store this cell in. pNode->iNode currently contains
129626     ** the height of the sub-tree headed by the cell.
129627     */
129628     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
129629     if( rc==SQLITE_OK ){
129630       int rc2;
129631       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
129632       rc2 = nodeRelease(pRtree, pInsert);
129633       if( rc==SQLITE_OK ){
129634         rc = rc2;
129635       }
129636     }
129637   }
129638   return rc;
129639 }
129640 
129641 /*
129642 ** Select a currently unused rowid for a new r-tree record.
129643 */
129644 static int newRowid(Rtree *pRtree, i64 *piRowid){
129645   int rc;
129646   sqlite3_bind_null(pRtree->pWriteRowid, 1);
129647   sqlite3_bind_null(pRtree->pWriteRowid, 2);
129648   sqlite3_step(pRtree->pWriteRowid);
129649   rc = sqlite3_reset(pRtree->pWriteRowid);
129650   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
129651   return rc;
129652 }
129653 
129654 /*
129655 ** Remove the entry with rowid=iDelete from the r-tree structure.
129656 */
129657 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
129658   int rc;                         /* Return code */
129659   RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
129660   int iCell;                      /* Index of iDelete cell in pLeaf */
129661   RtreeNode *pRoot;               /* Root node of rtree structure */
129662 
129663 
129664   /* Obtain a reference to the root node to initialise Rtree.iDepth */
129665   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
129666 
129667   /* Obtain a reference to the leaf node that contains the entry
129668   ** about to be deleted.
129669   */
129670   if( rc==SQLITE_OK ){
129671     rc = findLeafNode(pRtree, iDelete, &pLeaf);
129672   }
129673 
129674   /* Delete the cell in question from the leaf node. */
129675   if( rc==SQLITE_OK ){
129676     int rc2;
129677     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
129678     if( rc==SQLITE_OK ){
129679       rc = deleteCell(pRtree, pLeaf, iCell, 0);
129680     }
129681     rc2 = nodeRelease(pRtree, pLeaf);
129682     if( rc==SQLITE_OK ){
129683       rc = rc2;
129684     }
129685   }
129686 
129687   /* Delete the corresponding entry in the <rtree>_rowid table. */
129688   if( rc==SQLITE_OK ){
129689     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
129690     sqlite3_step(pRtree->pDeleteRowid);
129691     rc = sqlite3_reset(pRtree->pDeleteRowid);
129692   }
129693 
129694   /* Check if the root node now has exactly one child. If so, remove
129695   ** it, schedule the contents of the child for reinsertion and
129696   ** reduce the tree height by one.
129697   **
129698   ** This is equivalent to copying the contents of the child into
129699   ** the root node (the operation that Gutman's paper says to perform
129700   ** in this scenario).
129701   */
129702   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
129703     int rc2;
129704     RtreeNode *pChild;
129705     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
129706     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
129707     if( rc==SQLITE_OK ){
129708       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
129709     }
129710     rc2 = nodeRelease(pRtree, pChild);
129711     if( rc==SQLITE_OK ) rc = rc2;
129712     if( rc==SQLITE_OK ){
129713       pRtree->iDepth--;
129714       writeInt16(pRoot->zData, pRtree->iDepth);
129715       pRoot->isDirty = 1;
129716     }
129717   }
129718 
129719   /* Re-insert the contents of any underfull nodes removed from the tree. */
129720   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
129721     if( rc==SQLITE_OK ){
129722       rc = reinsertNodeContent(pRtree, pLeaf);
129723     }
129724     pRtree->pDeleted = pLeaf->pNext;
129725     sqlite3_free(pLeaf);
129726   }
129727 
129728   /* Release the reference to the root node. */
129729   if( rc==SQLITE_OK ){
129730     rc = nodeRelease(pRtree, pRoot);
129731   }else{
129732     nodeRelease(pRtree, pRoot);
129733   }
129734 
129735   return rc;
129736 }
129737 
129738 /*
129739 ** The xUpdate method for rtree module virtual tables.
129740 */
129741 static int rtreeUpdate(
129742   sqlite3_vtab *pVtab,
129743   int nData,
129744   sqlite3_value **azData,
129745   sqlite_int64 *pRowid
129746 ){
129747   Rtree *pRtree = (Rtree *)pVtab;
129748   int rc = SQLITE_OK;
129749   RtreeCell cell;                 /* New cell to insert if nData>1 */
129750   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
129751 
129752   rtreeReference(pRtree);
129753   assert(nData>=1);
129754 
129755   /* Constraint handling. A write operation on an r-tree table may return
129756   ** SQLITE_CONSTRAINT for two reasons:
129757   **
129758   **   1. A duplicate rowid value, or
129759   **   2. The supplied data violates the "x2>=x1" constraint.
129760   **
129761   ** In the first case, if the conflict-handling mode is REPLACE, then
129762   ** the conflicting row can be removed before proceeding. In the second
129763   ** case, SQLITE_CONSTRAINT must be returned regardless of the
129764   ** conflict-handling mode specified by the user.
129765   */
129766   if( nData>1 ){
129767     int ii;
129768 
129769     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
129770     assert( nData==(pRtree->nDim*2 + 3) );
129771     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
129772       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129773         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
129774         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
129775         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
129776           rc = SQLITE_CONSTRAINT;
129777           goto constraint;
129778         }
129779       }
129780     }else{
129781       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
129782         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
129783         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
129784         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
129785           rc = SQLITE_CONSTRAINT;
129786           goto constraint;
129787         }
129788       }
129789     }
129790 
129791     /* If a rowid value was supplied, check if it is already present in
129792     ** the table. If so, the constraint has failed. */
129793     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
129794       cell.iRowid = sqlite3_value_int64(azData[2]);
129795       if( sqlite3_value_type(azData[0])==SQLITE_NULL
129796        || sqlite3_value_int64(azData[0])!=cell.iRowid
129797       ){
129798         int steprc;
129799         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
129800         steprc = sqlite3_step(pRtree->pReadRowid);
129801         rc = sqlite3_reset(pRtree->pReadRowid);
129802         if( SQLITE_ROW==steprc ){
129803           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
129804             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
129805           }else{
129806             rc = SQLITE_CONSTRAINT;
129807             goto constraint;
129808           }
129809         }
129810       }
129811       bHaveRowid = 1;
129812     }
129813   }
129814 
129815   /* If azData[0] is not an SQL NULL value, it is the rowid of a
129816   ** record to delete from the r-tree table. The following block does
129817   ** just that.
129818   */
129819   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
129820     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
129821   }
129822 
129823   /* If the azData[] array contains more than one element, elements
129824   ** (azData[2]..azData[argc-1]) contain a new record to insert into
129825   ** the r-tree structure.
129826   */
129827   if( rc==SQLITE_OK && nData>1 ){
129828     /* Insert the new record into the r-tree */
129829     RtreeNode *pLeaf;
129830 
129831     /* Figure out the rowid of the new row. */
129832     if( bHaveRowid==0 ){
129833       rc = newRowid(pRtree, &cell.iRowid);
129834     }
129835     *pRowid = cell.iRowid;
129836 
129837     if( rc==SQLITE_OK ){
129838       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
129839     }
129840     if( rc==SQLITE_OK ){
129841       int rc2;
129842       pRtree->iReinsertHeight = -1;
129843       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
129844       rc2 = nodeRelease(pRtree, pLeaf);
129845       if( rc==SQLITE_OK ){
129846         rc = rc2;
129847       }
129848     }
129849   }
129850 
129851 constraint:
129852   rtreeRelease(pRtree);
129853   return rc;
129854 }
129855 
129856 /*
129857 ** The xRename method for rtree module virtual tables.
129858 */
129859 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
129860   Rtree *pRtree = (Rtree *)pVtab;
129861   int rc = SQLITE_NOMEM;
129862   char *zSql = sqlite3_mprintf(
129863     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
129864     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
129865     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
129866     , pRtree->zDb, pRtree->zName, zNewName
129867     , pRtree->zDb, pRtree->zName, zNewName
129868     , pRtree->zDb, pRtree->zName, zNewName
129869   );
129870   if( zSql ){
129871     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
129872     sqlite3_free(zSql);
129873   }
129874   return rc;
129875 }
129876 
129877 static sqlite3_module rtreeModule = {
129878   0,                          /* iVersion */
129879   rtreeCreate,                /* xCreate - create a table */
129880   rtreeConnect,               /* xConnect - connect to an existing table */
129881   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
129882   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
129883   rtreeDestroy,               /* xDestroy - Drop a table */
129884   rtreeOpen,                  /* xOpen - open a cursor */
129885   rtreeClose,                 /* xClose - close a cursor */
129886   rtreeFilter,                /* xFilter - configure scan constraints */
129887   rtreeNext,                  /* xNext - advance a cursor */
129888   rtreeEof,                   /* xEof */
129889   rtreeColumn,                /* xColumn - read data */
129890   rtreeRowid,                 /* xRowid - read data */
129891   rtreeUpdate,                /* xUpdate - write data */
129892   0,                          /* xBegin - begin transaction */
129893   0,                          /* xSync - sync transaction */
129894   0,                          /* xCommit - commit transaction */
129895   0,                          /* xRollback - rollback transaction */
129896   0,                          /* xFindFunction - function overloading */
129897   rtreeRename,                /* xRename - rename the table */
129898   0,                          /* xSavepoint */
129899   0,                          /* xRelease */
129900   0                           /* xRollbackTo */
129901 };
129902 
129903 static int rtreeSqlInit(
129904   Rtree *pRtree,
129905   sqlite3 *db,
129906   const char *zDb,
129907   const char *zPrefix,
129908   int isCreate
129909 ){
129910   int rc = SQLITE_OK;
129911 
129912   #define N_STATEMENT 9
129913   static const char *azSql[N_STATEMENT] = {
129914     /* Read and write the xxx_node table */
129915     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
129916     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
129917     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
129918 
129919     /* Read and write the xxx_rowid table */
129920     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
129921     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
129922     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
129923 
129924     /* Read and write the xxx_parent table */
129925     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
129926     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
129927     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
129928   };
129929   sqlite3_stmt **appStmt[N_STATEMENT];
129930   int i;
129931 
129932   pRtree->db = db;
129933 
129934   if( isCreate ){
129935     char *zCreate = sqlite3_mprintf(
129936 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
129937 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
129938 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
129939 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
129940       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
129941     );
129942     if( !zCreate ){
129943       return SQLITE_NOMEM;
129944     }
129945     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
129946     sqlite3_free(zCreate);
129947     if( rc!=SQLITE_OK ){
129948       return rc;
129949     }
129950   }
129951 
129952   appStmt[0] = &pRtree->pReadNode;
129953   appStmt[1] = &pRtree->pWriteNode;
129954   appStmt[2] = &pRtree->pDeleteNode;
129955   appStmt[3] = &pRtree->pReadRowid;
129956   appStmt[4] = &pRtree->pWriteRowid;
129957   appStmt[5] = &pRtree->pDeleteRowid;
129958   appStmt[6] = &pRtree->pReadParent;
129959   appStmt[7] = &pRtree->pWriteParent;
129960   appStmt[8] = &pRtree->pDeleteParent;
129961 
129962   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
129963     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
129964     if( zSql ){
129965       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
129966     }else{
129967       rc = SQLITE_NOMEM;
129968     }
129969     sqlite3_free(zSql);
129970   }
129971 
129972   return rc;
129973 }
129974 
129975 /*
129976 ** The second argument to this function contains the text of an SQL statement
129977 ** that returns a single integer value. The statement is compiled and executed
129978 ** using database connection db. If successful, the integer value returned
129979 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
129980 ** code is returned and the value of *piVal after returning is not defined.
129981 */
129982 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
129983   int rc = SQLITE_NOMEM;
129984   if( zSql ){
129985     sqlite3_stmt *pStmt = 0;
129986     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
129987     if( rc==SQLITE_OK ){
129988       if( SQLITE_ROW==sqlite3_step(pStmt) ){
129989         *piVal = sqlite3_column_int(pStmt, 0);
129990       }
129991       rc = sqlite3_finalize(pStmt);
129992     }
129993   }
129994   return rc;
129995 }
129996 
129997 /*
129998 ** This function is called from within the xConnect() or xCreate() method to
129999 ** determine the node-size used by the rtree table being created or connected
130000 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
130001 ** Otherwise, an SQLite error code is returned.
130002 **
130003 ** If this function is being called as part of an xConnect(), then the rtree
130004 ** table already exists. In this case the node-size is determined by inspecting
130005 ** the root node of the tree.
130006 **
130007 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
130008 ** This ensures that each node is stored on a single database page. If the
130009 ** database page-size is so large that more than RTREE_MAXCELLS entries
130010 ** would fit in a single node, use a smaller node-size.
130011 */
130012 static int getNodeSize(
130013   sqlite3 *db,                    /* Database handle */
130014   Rtree *pRtree,                  /* Rtree handle */
130015   int isCreate                    /* True for xCreate, false for xConnect */
130016 ){
130017   int rc;
130018   char *zSql;
130019   if( isCreate ){
130020     int iPageSize = 0;
130021     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
130022     rc = getIntFromStmt(db, zSql, &iPageSize);
130023     if( rc==SQLITE_OK ){
130024       pRtree->iNodeSize = iPageSize-64;
130025       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
130026         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
130027       }
130028     }
130029   }else{
130030     zSql = sqlite3_mprintf(
130031         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
130032         pRtree->zDb, pRtree->zName
130033     );
130034     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
130035   }
130036 
130037   sqlite3_free(zSql);
130038   return rc;
130039 }
130040 
130041 /*
130042 ** This function is the implementation of both the xConnect and xCreate
130043 ** methods of the r-tree virtual table.
130044 **
130045 **   argv[0]   -> module name
130046 **   argv[1]   -> database name
130047 **   argv[2]   -> table name
130048 **   argv[...] -> column names...
130049 */
130050 static int rtreeInit(
130051   sqlite3 *db,                        /* Database connection */
130052   void *pAux,                         /* One of the RTREE_COORD_* constants */
130053   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
130054   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
130055   char **pzErr,                       /* OUT: Error message, if any */
130056   int isCreate                        /* True for xCreate, false for xConnect */
130057 ){
130058   int rc = SQLITE_OK;
130059   Rtree *pRtree;
130060   int nDb;              /* Length of string argv[1] */
130061   int nName;            /* Length of string argv[2] */
130062   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
130063 
130064   const char *aErrMsg[] = {
130065     0,                                                    /* 0 */
130066     "Wrong number of columns for an rtree table",         /* 1 */
130067     "Too few columns for an rtree table",                 /* 2 */
130068     "Too many columns for an rtree table"                 /* 3 */
130069   };
130070 
130071   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
130072   if( aErrMsg[iErr] ){
130073     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
130074     return SQLITE_ERROR;
130075   }
130076 
130077   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
130078 
130079   /* Allocate the sqlite3_vtab structure */
130080   nDb = strlen(argv[1]);
130081   nName = strlen(argv[2]);
130082   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
130083   if( !pRtree ){
130084     return SQLITE_NOMEM;
130085   }
130086   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
130087   pRtree->nBusy = 1;
130088   pRtree->base.pModule = &rtreeModule;
130089   pRtree->zDb = (char *)&pRtree[1];
130090   pRtree->zName = &pRtree->zDb[nDb+1];
130091   pRtree->nDim = (argc-4)/2;
130092   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
130093   pRtree->eCoordType = eCoordType;
130094   memcpy(pRtree->zDb, argv[1], nDb);
130095   memcpy(pRtree->zName, argv[2], nName);
130096 
130097   /* Figure out the node size to use. */
130098   rc = getNodeSize(db, pRtree, isCreate);
130099 
130100   /* Create/Connect to the underlying relational database schema. If
130101   ** that is successful, call sqlite3_declare_vtab() to configure
130102   ** the r-tree table schema.
130103   */
130104   if( rc==SQLITE_OK ){
130105     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
130106       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
130107     }else{
130108       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
130109       char *zTmp;
130110       int ii;
130111       for(ii=4; zSql && ii<argc; ii++){
130112         zTmp = zSql;
130113         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
130114         sqlite3_free(zTmp);
130115       }
130116       if( zSql ){
130117         zTmp = zSql;
130118         zSql = sqlite3_mprintf("%s);", zTmp);
130119         sqlite3_free(zTmp);
130120       }
130121       if( !zSql ){
130122         rc = SQLITE_NOMEM;
130123       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
130124         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
130125       }
130126       sqlite3_free(zSql);
130127     }
130128   }
130129 
130130   if( rc==SQLITE_OK ){
130131     *ppVtab = (sqlite3_vtab *)pRtree;
130132   }else{
130133     rtreeRelease(pRtree);
130134   }
130135   return rc;
130136 }
130137 
130138 
130139 /*
130140 ** Implementation of a scalar function that decodes r-tree nodes to
130141 ** human readable strings. This can be used for debugging and analysis.
130142 **
130143 ** The scalar function takes two arguments, a blob of data containing
130144 ** an r-tree node, and the number of dimensions the r-tree indexes.
130145 ** For a two-dimensional r-tree structure called "rt", to deserialize
130146 ** all nodes, a statement like:
130147 **
130148 **   SELECT rtreenode(2, data) FROM rt_node;
130149 **
130150 ** The human readable string takes the form of a Tcl list with one
130151 ** entry for each cell in the r-tree node. Each entry is itself a
130152 ** list, containing the 8-byte rowid/pageno followed by the
130153 ** <num-dimension>*2 coordinates.
130154 */
130155 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
130156   char *zText = 0;
130157   RtreeNode node;
130158   Rtree tree;
130159   int ii;
130160 
130161   UNUSED_PARAMETER(nArg);
130162   memset(&node, 0, sizeof(RtreeNode));
130163   memset(&tree, 0, sizeof(Rtree));
130164   tree.nDim = sqlite3_value_int(apArg[0]);
130165   tree.nBytesPerCell = 8 + 8 * tree.nDim;
130166   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
130167 
130168   for(ii=0; ii<NCELL(&node); ii++){
130169     char zCell[512];
130170     int nCell = 0;
130171     RtreeCell cell;
130172     int jj;
130173 
130174     nodeGetCell(&tree, &node, ii, &cell);
130175     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
130176     nCell = strlen(zCell);
130177     for(jj=0; jj<tree.nDim*2; jj++){
130178       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
130179       nCell = strlen(zCell);
130180     }
130181 
130182     if( zText ){
130183       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
130184       sqlite3_free(zText);
130185       zText = zTextNew;
130186     }else{
130187       zText = sqlite3_mprintf("{%s}", zCell);
130188     }
130189   }
130190 
130191   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
130192 }
130193 
130194 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
130195   UNUSED_PARAMETER(nArg);
130196   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
130197    || sqlite3_value_bytes(apArg[0])<2
130198   ){
130199     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
130200   }else{
130201     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
130202     sqlite3_result_int(ctx, readInt16(zBlob));
130203   }
130204 }
130205 
130206 /*
130207 ** Register the r-tree module with database handle db. This creates the
130208 ** virtual table module "rtree" and the debugging/analysis scalar
130209 ** function "rtreenode".
130210 */
130211 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
130212   const int utf8 = SQLITE_UTF8;
130213   int rc;
130214 
130215   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
130216   if( rc==SQLITE_OK ){
130217     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
130218   }
130219   if( rc==SQLITE_OK ){
130220     void *c = (void *)RTREE_COORD_REAL32;
130221     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
130222   }
130223   if( rc==SQLITE_OK ){
130224     void *c = (void *)RTREE_COORD_INT32;
130225     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
130226   }
130227 
130228   return rc;
130229 }
130230 
130231 /*
130232 ** A version of sqlite3_free() that can be used as a callback. This is used
130233 ** in two places - as the destructor for the blob value returned by the
130234 ** invocation of a geometry function, and as the destructor for the geometry
130235 ** functions themselves.
130236 */
130237 static void doSqlite3Free(void *p){
130238   sqlite3_free(p);
130239 }
130240 
130241 /*
130242 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
130243 ** scalar user function. This C function is the callback used for all such
130244 ** registered SQL functions.
130245 **
130246 ** The scalar user functions return a blob that is interpreted by r-tree
130247 ** table MATCH operators.
130248 */
130249 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
130250   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
130251   RtreeMatchArg *pBlob;
130252   int nBlob;
130253 
130254   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
130255   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
130256   if( !pBlob ){
130257     sqlite3_result_error_nomem(ctx);
130258   }else{
130259     int i;
130260     pBlob->magic = RTREE_GEOMETRY_MAGIC;
130261     pBlob->xGeom = pGeomCtx->xGeom;
130262     pBlob->pContext = pGeomCtx->pContext;
130263     pBlob->nParam = nArg;
130264     for(i=0; i<nArg; i++){
130265       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
130266     }
130267     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
130268   }
130269 }
130270 
130271 /*
130272 ** Register a new geometry function for use with the r-tree MATCH operator.
130273 */
130274 SQLITE_API int sqlite3_rtree_geometry_callback(
130275   sqlite3 *db,
130276   const char *zGeom,
130277   int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
130278   void *pContext
130279 ){
130280   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
130281 
130282   /* Allocate and populate the context object. */
130283   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
130284   if( !pGeomCtx ) return SQLITE_NOMEM;
130285   pGeomCtx->xGeom = xGeom;
130286   pGeomCtx->pContext = pContext;
130287 
130288   /* Create the new user-function. Register a destructor function to delete
130289   ** the context object when it is no longer required.  */
130290   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
130291       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
130292   );
130293 }
130294 
130295 #if !SQLITE_CORE
130296 SQLITE_API int sqlite3_extension_init(
130297   sqlite3 *db,
130298   char **pzErrMsg,
130299   const sqlite3_api_routines *pApi
130300 ){
130301   SQLITE_EXTENSION_INIT2(pApi)
130302   return sqlite3RtreeInit(db);
130303 }
130304 #endif
130305 
130306 #endif
130307 
130308 /************** End of rtree.c ***********************************************/
130309 /************** Begin file icu.c *********************************************/
130310 /*
130311 ** 2007 May 6
130312 **
130313 ** The author disclaims copyright to this source code.  In place of
130314 ** a legal notice, here is a blessing:
130315 **
130316 **    May you do good and not evil.
130317 **    May you find forgiveness for yourself and forgive others.
130318 **    May you share freely, never taking more than you give.
130319 **
130320 *************************************************************************
130321 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
130322 **
130323 ** This file implements an integration between the ICU library
130324 ** ("International Components for Unicode", an open-source library
130325 ** for handling unicode data) and SQLite. The integration uses
130326 ** ICU to provide the following to SQLite:
130327 **
130328 **   * An implementation of the SQL regexp() function (and hence REGEXP
130329 **     operator) using the ICU uregex_XX() APIs.
130330 **
130331 **   * Implementations of the SQL scalar upper() and lower() functions
130332 **     for case mapping.
130333 **
130334 **   * Integration of ICU and SQLite collation seqences.
130335 **
130336 **   * An implementation of the LIKE operator that uses ICU to
130337 **     provide case-independent matching.
130338 */
130339 
130340 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
130341 
130342 /* Include ICU headers */
130343 #include <unicode/utypes.h>
130344 #include <unicode/uregex.h>
130345 #include <unicode/ustring.h>
130346 #include <unicode/ucol.h>
130347 
130348 /* #include <assert.h> */
130349 
130350 #ifndef SQLITE_CORE
130351   SQLITE_EXTENSION_INIT1
130352 #else
130353 #endif
130354 
130355 /*
130356 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
130357 ** operator.
130358 */
130359 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
130360 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
130361 #endif
130362 
130363 /*
130364 ** Version of sqlite3_free() that is always a function, never a macro.
130365 */
130366 static void xFree(void *p){
130367   sqlite3_free(p);
130368 }
130369 
130370 /*
130371 ** Compare two UTF-8 strings for equality where the first string is
130372 ** a "LIKE" expression. Return true (1) if they are the same and
130373 ** false (0) if they are different.
130374 */
130375 static int icuLikeCompare(
130376   const uint8_t *zPattern,   /* LIKE pattern */
130377   const uint8_t *zString,    /* The UTF-8 string to compare against */
130378   const UChar32 uEsc         /* The escape character */
130379 ){
130380   static const int MATCH_ONE = (UChar32)'_';
130381   static const int MATCH_ALL = (UChar32)'%';
130382 
130383   int iPattern = 0;       /* Current byte index in zPattern */
130384   int iString = 0;        /* Current byte index in zString */
130385 
130386   int prevEscape = 0;     /* True if the previous character was uEsc */
130387 
130388   while( zPattern[iPattern]!=0 ){
130389 
130390     /* Read (and consume) the next character from the input pattern. */
130391     UChar32 uPattern;
130392     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
130393     assert(uPattern!=0);
130394 
130395     /* There are now 4 possibilities:
130396     **
130397     **     1. uPattern is an unescaped match-all character "%",
130398     **     2. uPattern is an unescaped match-one character "_",
130399     **     3. uPattern is an unescaped escape character, or
130400     **     4. uPattern is to be handled as an ordinary character
130401     */
130402     if( !prevEscape && uPattern==MATCH_ALL ){
130403       /* Case 1. */
130404       uint8_t c;
130405 
130406       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
130407       ** MATCH_ALL. For each MATCH_ONE, skip one character in the
130408       ** test string.
130409       */
130410       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
130411         if( c==MATCH_ONE ){
130412           if( zString[iString]==0 ) return 0;
130413           U8_FWD_1_UNSAFE(zString, iString);
130414         }
130415         iPattern++;
130416       }
130417 
130418       if( zPattern[iPattern]==0 ) return 1;
130419 
130420       while( zString[iString] ){
130421         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
130422           return 1;
130423         }
130424         U8_FWD_1_UNSAFE(zString, iString);
130425       }
130426       return 0;
130427 
130428     }else if( !prevEscape && uPattern==MATCH_ONE ){
130429       /* Case 2. */
130430       if( zString[iString]==0 ) return 0;
130431       U8_FWD_1_UNSAFE(zString, iString);
130432 
130433     }else if( !prevEscape && uPattern==uEsc){
130434       /* Case 3. */
130435       prevEscape = 1;
130436 
130437     }else{
130438       /* Case 4. */
130439       UChar32 uString;
130440       U8_NEXT_UNSAFE(zString, iString, uString);
130441       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
130442       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
130443       if( uString!=uPattern ){
130444         return 0;
130445       }
130446       prevEscape = 0;
130447     }
130448   }
130449 
130450   return zString[iString]==0;
130451 }
130452 
130453 /*
130454 ** Implementation of the like() SQL function.  This function implements
130455 ** the build-in LIKE operator.  The first argument to the function is the
130456 ** pattern and the second argument is the string.  So, the SQL statements:
130457 **
130458 **       A LIKE B
130459 **
130460 ** is implemented as like(B, A). If there is an escape character E,
130461 **
130462 **       A LIKE B ESCAPE E
130463 **
130464 ** is mapped to like(B, A, E).
130465 */
130466 static void icuLikeFunc(
130467   sqlite3_context *context,
130468   int argc,
130469   sqlite3_value **argv
130470 ){
130471   const unsigned char *zA = sqlite3_value_text(argv[0]);
130472   const unsigned char *zB = sqlite3_value_text(argv[1]);
130473   UChar32 uEsc = 0;
130474 
130475   /* Limit the length of the LIKE or GLOB pattern to avoid problems
130476   ** of deep recursion and N*N behavior in patternCompare().
130477   */
130478   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
130479     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
130480     return;
130481   }
130482 
130483 
130484   if( argc==3 ){
130485     /* The escape character string must consist of a single UTF-8 character.
130486     ** Otherwise, return an error.
130487     */
130488     int nE= sqlite3_value_bytes(argv[2]);
130489     const unsigned char *zE = sqlite3_value_text(argv[2]);
130490     int i = 0;
130491     if( zE==0 ) return;
130492     U8_NEXT(zE, i, nE, uEsc);
130493     if( i!=nE){
130494       sqlite3_result_error(context,
130495           "ESCAPE expression must be a single character", -1);
130496       return;
130497     }
130498   }
130499 
130500   if( zA && zB ){
130501     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
130502   }
130503 }
130504 
130505 /*
130506 ** This function is called when an ICU function called from within
130507 ** the implementation of an SQL scalar function returns an error.
130508 **
130509 ** The scalar function context passed as the first argument is
130510 ** loaded with an error message based on the following two args.
130511 */
130512 static void icuFunctionError(
130513   sqlite3_context *pCtx,       /* SQLite scalar function context */
130514   const char *zName,           /* Name of ICU function that failed */
130515   UErrorCode e                 /* Error code returned by ICU function */
130516 ){
130517   char zBuf[128];
130518   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
130519   zBuf[127] = '\0';
130520   sqlite3_result_error(pCtx, zBuf, -1);
130521 }
130522 
130523 /*
130524 ** Function to delete compiled regexp objects. Registered as
130525 ** a destructor function with sqlite3_set_auxdata().
130526 */
130527 static void icuRegexpDelete(void *p){
130528   URegularExpression *pExpr = (URegularExpression *)p;
130529   uregex_close(pExpr);
130530 }
130531 
130532 /*
130533 ** Implementation of SQLite REGEXP operator. This scalar function takes
130534 ** two arguments. The first is a regular expression pattern to compile
130535 ** the second is a string to match against that pattern. If either
130536 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
130537 ** is 1 if the string matches the pattern, or 0 otherwise.
130538 **
130539 ** SQLite maps the regexp() function to the regexp() operator such
130540 ** that the following two are equivalent:
130541 **
130542 **     zString REGEXP zPattern
130543 **     regexp(zPattern, zString)
130544 **
130545 ** Uses the following ICU regexp APIs:
130546 **
130547 **     uregex_open()
130548 **     uregex_matches()
130549 **     uregex_close()
130550 */
130551 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
130552   UErrorCode status = U_ZERO_ERROR;
130553   URegularExpression *pExpr;
130554   UBool res;
130555   const UChar *zString = sqlite3_value_text16(apArg[1]);
130556 
130557   (void)nArg;  /* Unused parameter */
130558 
130559   /* If the left hand side of the regexp operator is NULL,
130560   ** then the result is also NULL.
130561   */
130562   if( !zString ){
130563     return;
130564   }
130565 
130566   pExpr = sqlite3_get_auxdata(p, 0);
130567   if( !pExpr ){
130568     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
130569     if( !zPattern ){
130570       return;
130571     }
130572     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
130573 
130574     if( U_SUCCESS(status) ){
130575       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
130576     }else{
130577       assert(!pExpr);
130578       icuFunctionError(p, "uregex_open", status);
130579       return;
130580     }
130581   }
130582 
130583   /* Configure the text that the regular expression operates on. */
130584   uregex_setText(pExpr, zString, -1, &status);
130585   if( !U_SUCCESS(status) ){
130586     icuFunctionError(p, "uregex_setText", status);
130587     return;
130588   }
130589 
130590   /* Attempt the match */
130591   res = uregex_matches(pExpr, 0, &status);
130592   if( !U_SUCCESS(status) ){
130593     icuFunctionError(p, "uregex_matches", status);
130594     return;
130595   }
130596 
130597   /* Set the text that the regular expression operates on to a NULL
130598   ** pointer. This is not really necessary, but it is tidier than
130599   ** leaving the regular expression object configured with an invalid
130600   ** pointer after this function returns.
130601   */
130602   uregex_setText(pExpr, 0, 0, &status);
130603 
130604   /* Return 1 or 0. */
130605   sqlite3_result_int(p, res ? 1 : 0);
130606 }
130607 
130608 /*
130609 ** Implementations of scalar functions for case mapping - upper() and
130610 ** lower(). Function upper() converts its input to upper-case (ABC).
130611 ** Function lower() converts to lower-case (abc).
130612 **
130613 ** ICU provides two types of case mapping, "general" case mapping and
130614 ** "language specific". Refer to ICU documentation for the differences
130615 ** between the two.
130616 **
130617 ** To utilise "general" case mapping, the upper() or lower() scalar
130618 ** functions are invoked with one argument:
130619 **
130620 **     upper('ABC') -> 'abc'
130621 **     lower('abc') -> 'ABC'
130622 **
130623 ** To access ICU "language specific" case mapping, upper() or lower()
130624 ** should be invoked with two arguments. The second argument is the name
130625 ** of the locale to use. Passing an empty string ("") or SQL NULL value
130626 ** as the second argument is the same as invoking the 1 argument version
130627 ** of upper() or lower().
130628 **
130629 **     lower('I', 'en_us') -> 'i'
130630 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
130631 **
130632 ** http://www.icu-project.org/userguide/posix.html#case_mappings
130633 */
130634 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
130635   const UChar *zInput;
130636   UChar *zOutput;
130637   int nInput;
130638   int nOutput;
130639 
130640   UErrorCode status = U_ZERO_ERROR;
130641   const char *zLocale = 0;
130642 
130643   assert(nArg==1 || nArg==2);
130644   if( nArg==2 ){
130645     zLocale = (const char *)sqlite3_value_text(apArg[1]);
130646   }
130647 
130648   zInput = sqlite3_value_text16(apArg[0]);
130649   if( !zInput ){
130650     return;
130651   }
130652   nInput = sqlite3_value_bytes16(apArg[0]);
130653 
130654   nOutput = nInput * 2 + 2;
130655   zOutput = sqlite3_malloc(nOutput);
130656   if( !zOutput ){
130657     return;
130658   }
130659 
130660   if( sqlite3_user_data(p) ){
130661     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
130662   }else{
130663     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
130664   }
130665 
130666   if( !U_SUCCESS(status) ){
130667     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
130668     return;
130669   }
130670 
130671   sqlite3_result_text16(p, zOutput, -1, xFree);
130672 }
130673 
130674 /*
130675 ** Collation sequence destructor function. The pCtx argument points to
130676 ** a UCollator structure previously allocated using ucol_open().
130677 */
130678 static void icuCollationDel(void *pCtx){
130679   UCollator *p = (UCollator *)pCtx;
130680   ucol_close(p);
130681 }
130682 
130683 /*
130684 ** Collation sequence comparison function. The pCtx argument points to
130685 ** a UCollator structure previously allocated using ucol_open().
130686 */
130687 static int icuCollationColl(
130688   void *pCtx,
130689   int nLeft,
130690   const void *zLeft,
130691   int nRight,
130692   const void *zRight
130693 ){
130694   UCollationResult res;
130695   UCollator *p = (UCollator *)pCtx;
130696   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
130697   switch( res ){
130698     case UCOL_LESS:    return -1;
130699     case UCOL_GREATER: return +1;
130700     case UCOL_EQUAL:   return 0;
130701   }
130702   assert(!"Unexpected return value from ucol_strcoll()");
130703   return 0;
130704 }
130705 
130706 /*
130707 ** Implementation of the scalar function icu_load_collation().
130708 **
130709 ** This scalar function is used to add ICU collation based collation
130710 ** types to an SQLite database connection. It is intended to be called
130711 ** as follows:
130712 **
130713 **     SELECT icu_load_collation(<locale>, <collation-name>);
130714 **
130715 ** Where <locale> is a string containing an ICU locale identifier (i.e.
130716 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
130717 ** collation sequence to create.
130718 */
130719 static void icuLoadCollation(
130720   sqlite3_context *p,
130721   int nArg,
130722   sqlite3_value **apArg
130723 ){
130724   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
130725   UErrorCode status = U_ZERO_ERROR;
130726   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
130727   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
130728   UCollator *pUCollator;    /* ICU library collation object */
130729   int rc;                   /* Return code from sqlite3_create_collation_x() */
130730 
130731   assert(nArg==2);
130732   zLocale = (const char *)sqlite3_value_text(apArg[0]);
130733   zName = (const char *)sqlite3_value_text(apArg[1]);
130734 
130735   if( !zLocale || !zName ){
130736     return;
130737   }
130738 
130739   pUCollator = ucol_open(zLocale, &status);
130740   if( !U_SUCCESS(status) ){
130741     icuFunctionError(p, "ucol_open", status);
130742     return;
130743   }
130744   assert(p);
130745 
130746   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
130747       icuCollationColl, icuCollationDel
130748   );
130749   if( rc!=SQLITE_OK ){
130750     ucol_close(pUCollator);
130751     sqlite3_result_error(p, "Error registering collation function", -1);
130752   }
130753 }
130754 
130755 /*
130756 ** Register the ICU extension functions with database db.
130757 */
130758 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
130759   struct IcuScalar {
130760     const char *zName;                        /* Function name */
130761     int nArg;                                 /* Number of arguments */
130762     int enc;                                  /* Optimal text encoding */
130763     void *pContext;                           /* sqlite3_user_data() context */
130764     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
130765   } scalars[] = {
130766     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
130767 
130768     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
130769     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
130770     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
130771     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
130772 
130773     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
130774     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
130775     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
130776     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
130777 
130778     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
130779     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
130780 
130781     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
130782   };
130783 
130784   int rc = SQLITE_OK;
130785   int i;
130786 
130787   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
130788     struct IcuScalar *p = &scalars[i];
130789     rc = sqlite3_create_function(
130790         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
130791     );
130792   }
130793 
130794   return rc;
130795 }
130796 
130797 #if !SQLITE_CORE
130798 SQLITE_API int sqlite3_extension_init(
130799   sqlite3 *db,
130800   char **pzErrMsg,
130801   const sqlite3_api_routines *pApi
130802 ){
130803   SQLITE_EXTENSION_INIT2(pApi)
130804   return sqlite3IcuInit(db);
130805 }
130806 #endif
130807 
130808 #endif
130809 
130810 /************** End of icu.c *************************************************/
130811 /************** Begin file fts3_icu.c ****************************************/
130812 /*
130813 ** 2007 June 22
130814 **
130815 ** The author disclaims copyright to this source code.  In place of
130816 ** a legal notice, here is a blessing:
130817 **
130818 **    May you do good and not evil.
130819 **    May you find forgiveness for yourself and forgive others.
130820 **    May you share freely, never taking more than you give.
130821 **
130822 *************************************************************************
130823 ** This file implements a tokenizer for fts3 based on the ICU library.
130824 */
130825 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
130826 #ifdef SQLITE_ENABLE_ICU
130827 
130828 /* #include <assert.h> */
130829 /* #include <string.h> */
130830 
130831 #include <unicode/ubrk.h>
130832 /* #include <unicode/ucol.h> */
130833 /* #include <unicode/ustring.h> */
130834 #include <unicode/utf16.h>
130835 
130836 typedef struct IcuTokenizer IcuTokenizer;
130837 typedef struct IcuCursor IcuCursor;
130838 
130839 struct IcuTokenizer {
130840   sqlite3_tokenizer base;
130841   char *zLocale;
130842 };
130843 
130844 struct IcuCursor {
130845   sqlite3_tokenizer_cursor base;
130846 
130847   UBreakIterator *pIter;      /* ICU break-iterator object */
130848   int nChar;                  /* Number of UChar elements in pInput */
130849   UChar *aChar;               /* Copy of input using utf-16 encoding */
130850   int *aOffset;               /* Offsets of each character in utf-8 input */
130851 
130852   int nBuffer;
130853   char *zBuffer;
130854 
130855   int iToken;
130856 };
130857 
130858 /*
130859 ** Create a new tokenizer instance.
130860 */
130861 static int icuCreate(
130862   int argc,                            /* Number of entries in argv[] */
130863   const char * const *argv,            /* Tokenizer creation arguments */
130864   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
130865 ){
130866   IcuTokenizer *p;
130867   int n = 0;
130868 
130869   if( argc>0 ){
130870     n = strlen(argv[0])+1;
130871   }
130872   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
130873   if( !p ){
130874     return SQLITE_NOMEM;
130875   }
130876   memset(p, 0, sizeof(IcuTokenizer));
130877 
130878   if( n ){
130879     p->zLocale = (char *)&p[1];
130880     memcpy(p->zLocale, argv[0], n);
130881   }
130882 
130883   *ppTokenizer = (sqlite3_tokenizer *)p;
130884 
130885   return SQLITE_OK;
130886 }
130887 
130888 /*
130889 ** Destroy a tokenizer
130890 */
130891 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
130892   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
130893   sqlite3_free(p);
130894   return SQLITE_OK;
130895 }
130896 
130897 /*
130898 ** Prepare to begin tokenizing a particular string.  The input
130899 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
130900 ** used to incrementally tokenize this string is returned in
130901 ** *ppCursor.
130902 */
130903 static int icuOpen(
130904   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
130905   const char *zInput,                    /* Input string */
130906   int nInput,                            /* Length of zInput in bytes */
130907   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
130908 ){
130909   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
130910   IcuCursor *pCsr;
130911 
130912   const int32_t opt = U_FOLD_CASE_DEFAULT;
130913   UErrorCode status = U_ZERO_ERROR;
130914   int nChar;
130915 
130916   UChar32 c;
130917   int iInput = 0;
130918   int iOut = 0;
130919 
130920   *ppCursor = 0;
130921 
130922   if( nInput<0 ){
130923     nInput = strlen(zInput);
130924   }
130925   nChar = nInput+1;
130926   pCsr = (IcuCursor *)sqlite3_malloc(
130927       sizeof(IcuCursor) +                /* IcuCursor */
130928       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
130929       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
130930   );
130931   if( !pCsr ){
130932     return SQLITE_NOMEM;
130933   }
130934   memset(pCsr, 0, sizeof(IcuCursor));
130935   pCsr->aChar = (UChar *)&pCsr[1];
130936   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
130937 
130938   pCsr->aOffset[iOut] = iInput;
130939   U8_NEXT(zInput, iInput, nInput, c);
130940   while( c>0 ){
130941     int isError = 0;
130942     c = u_foldCase(c, opt);
130943     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
130944     if( isError ){
130945       sqlite3_free(pCsr);
130946       return SQLITE_ERROR;
130947     }
130948     pCsr->aOffset[iOut] = iInput;
130949 
130950     if( iInput<nInput ){
130951       U8_NEXT(zInput, iInput, nInput, c);
130952     }else{
130953       c = 0;
130954     }
130955   }
130956 
130957   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
130958   if( !U_SUCCESS(status) ){
130959     sqlite3_free(pCsr);
130960     return SQLITE_ERROR;
130961   }
130962   pCsr->nChar = iOut;
130963 
130964   ubrk_first(pCsr->pIter);
130965   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
130966   return SQLITE_OK;
130967 }
130968 
130969 /*
130970 ** Close a tokenization cursor previously opened by a call to icuOpen().
130971 */
130972 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
130973   IcuCursor *pCsr = (IcuCursor *)pCursor;
130974   ubrk_close(pCsr->pIter);
130975   sqlite3_free(pCsr->zBuffer);
130976   sqlite3_free(pCsr);
130977   return SQLITE_OK;
130978 }
130979 
130980 /*
130981 ** Extract the next token from a tokenization cursor.
130982 */
130983 static int icuNext(
130984   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
130985   const char **ppToken,               /* OUT: *ppToken is the token text */
130986   int *pnBytes,                       /* OUT: Number of bytes in token */
130987   int *piStartOffset,                 /* OUT: Starting offset of token */
130988   int *piEndOffset,                   /* OUT: Ending offset of token */
130989   int *piPosition                     /* OUT: Position integer of token */
130990 ){
130991   IcuCursor *pCsr = (IcuCursor *)pCursor;
130992 
130993   int iStart = 0;
130994   int iEnd = 0;
130995   int nByte = 0;
130996 
130997   while( iStart==iEnd ){
130998     UChar32 c;
130999 
131000     iStart = ubrk_current(pCsr->pIter);
131001     iEnd = ubrk_next(pCsr->pIter);
131002     if( iEnd==UBRK_DONE ){
131003       return SQLITE_DONE;
131004     }
131005 
131006     while( iStart<iEnd ){
131007       int iWhite = iStart;
131008       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
131009       if( u_isspace(c) ){
131010         iStart = iWhite;
131011       }else{
131012         break;
131013       }
131014     }
131015     assert(iStart<=iEnd);
131016   }
131017 
131018   do {
131019     UErrorCode status = U_ZERO_ERROR;
131020     if( nByte ){
131021       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
131022       if( !zNew ){
131023         return SQLITE_NOMEM;
131024       }
131025       pCsr->zBuffer = zNew;
131026       pCsr->nBuffer = nByte;
131027     }
131028 
131029     u_strToUTF8(
131030         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
131031         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
131032         &status                                  /* Output success/failure */
131033     );
131034   } while( nByte>pCsr->nBuffer );
131035 
131036   *ppToken = pCsr->zBuffer;
131037   *pnBytes = nByte;
131038   *piStartOffset = pCsr->aOffset[iStart];
131039   *piEndOffset = pCsr->aOffset[iEnd];
131040   *piPosition = pCsr->iToken++;
131041 
131042   return SQLITE_OK;
131043 }
131044 
131045 /*
131046 ** The set of routines that implement the simple tokenizer
131047 */
131048 static const sqlite3_tokenizer_module icuTokenizerModule = {
131049   0,                           /* iVersion */
131050   icuCreate,                   /* xCreate  */
131051   icuDestroy,                  /* xCreate  */
131052   icuOpen,                     /* xOpen    */
131053   icuClose,                    /* xClose   */
131054   icuNext,                     /* xNext    */
131055 };
131056 
131057 /*
131058 ** Set *ppModule to point at the implementation of the ICU tokenizer.
131059 */
131060 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
131061   sqlite3_tokenizer_module const**ppModule
131062 ){
131063   *ppModule = &icuTokenizerModule;
131064 }
131065 
131066 #endif /* defined(SQLITE_ENABLE_ICU) */
131067 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
131068 
131069 /************** End of fts3_icu.c ********************************************/
131070